croft-software 0.2.232

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
//! The window chrome: side bars, the activity bar, panels, the status bar,
//! Zen Mode, splitters and Customize Layout.

use super::*;

/// Negative for #1133: two rows, and a normal size after one row, still
/// draw the bottom panel's tab strip where it was.
#[test]
fn the_panel_tab_strip_still_paints_once_there_is_room() {
    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(100, 2)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 30)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer();
    let rows: Vec<String> = (0..30)
        .map(|y| (0..100).map(|x| buf[(x, y)].symbol().to_string()).collect())
        .collect();
    assert!(
        rows.iter()
            .any(|r| r.contains("PROBLEMS") && r.contains("TERMINAL")),
        "{rows:#?}"
    );
}

/// #1132: editor groups that can't all sit at their minimum width ran past
/// the frame, and the tab strip painted the first column outside it.
#[test]
fn splitting_the_editor_in_a_narrow_window_renders_without_panicking() {
    let tmp = tempfile::tempdir().unwrap();
    let draw = |app: &mut App, w: u16, h: u16| {
        let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(w, h)).unwrap();
        term.draw(|f| app.render(f)).unwrap();
    };
    let mut app = app_with_open_file(tmp.path(), "api.py", "def f():\n    pass\n");
    draw(&mut app, 80, 24);
    for _ in 0..4 {
        app.split_editor();
        draw(&mut app, 80, 24);
    }
    assert_eq!(app.editor_layout.leaf_count(), 5);
    draw(&mut app, 60, 20);
    draw(&mut app, 22, 8);

    let mut two = app_with_open_file(tmp.path(), "b.py", "x = 1\n");
    two.split_editor();
    draw(&mut two, 22, 8);
    draw(&mut two, 20, 8);
}

/// #1132 (comment): the secondary side bar's OUTLINE scrollbar at 30x9.
#[test]
fn a_secondary_side_bar_in_a_narrow_window_renders_without_panicking() {
    let tmp = tempfile::tempdir().unwrap();
    let src: String = (0..80)
        .map(|i| format!("def f{i}():\n    pass\n"))
        .collect();
    let mut app = app_with_open_file(tmp.path(), "sessions.py", &src);
    app.toggle_secondary_side_bar();
    for (w, h) in [(120, 35), (30, 9), (30, 24), (12, 9)] {
        let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(w, h)).unwrap();
        term.draw(|f| app.render(f)).unwrap();
    }
}

#[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.activity_icons[ActivityIcon::Search];
    let (cx, cy) = (icon.x + icon.width / 2, icon.y);
    app.on_mouse_moved(cx, cy, false);
    assert_eq!(
        app.ui_tooltip_label.as_deref(),
        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 = app.theme.ui(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 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"));
}

#[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.dwell.mark_fired();
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    assert!(
        app.hover
            .dwell
            .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"
    );
}

/// Negative: opening a location from a panel (a search hit, a problem) is
/// not a code navigation from the tab, so a preview tab is still replaced
/// as before.
#[test]
fn a_panel_open_still_replaces_the_preview_tab() {
    let (_tmp, mut app, mc, main, mh) = preview_nav_fixture();
    app.editor.open_preview(&main).unwrap();
    app.open_at(&mh, 1, 0).unwrap();
    assert_eq!(open_tab_paths(&app), vec![mc, mh]);
}

#[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 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 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");
}

/// Guard (#843): the shell keeps `Ctrl`+`K` only while it has the keyboard.
/// With the bottom panel on PROBLEMS the focused panel is not a shell, so
/// `Ctrl`+`K` leads there as in any other pane.
#[cfg(not(target_os = "macos"))]
#[test]
fn ctrl_k_leads_from_the_panel_while_it_shows_problems() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.bottom_panel_tab = BottomPanelTab::Problems;
    app.focus_pane(Pane::Terminal);
    app.handle_key(key(KeyCode::Char('k'), KeyModifiers::CONTROL))
        .unwrap();
    assert!(app.cmd_k_leader.is_some());
}

/// A bake input for an 8x16-pixel cell on a Kitty-protocol terminal.
fn kitty_chrome_bake_input() -> ChromeBakeInput {
    ChromeBakeInput {
        protocol: crate::iterm2_inline::InlineImageProtocol::Kitty,
        cell: (8, 16),
        is_tmux: false,
        icon_bg: ::image::Rgba([0x1e, 0x1e, 0x1e, 0xff]),
        icon_ink: crate::iterm2_inline::IconInk::default(),
        sponsor_ink: crate::iterm2_inline::IconInk::default(),
    }
}

/// #1973: the activity-bar icons and panel illustrations bake on a thread of
/// their own, so startup and a theme switch never wait for some fifty
/// rasterisations. The bar draws its codicon glyphs until they land, then
/// the pictures go up, the badges with them.
#[test]
fn the_activity_bar_icons_bake_off_the_ui_thread() {
    let tmp = tempfile::tempdir().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.start_chrome_bake(kitty_chrome_bake_input());
    assert!(
        !app.overlays.activity.has_images(),
        "the caller waited for the icon bake"
    );
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 40)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let bar: String = (0..40)
        .flat_map(|y| (0..ACTIVITY_BAR_WIDTH).map(move |x| (x, y)))
        .map(|(x, y)| term.backend().buffer()[(x, y)].symbol().to_string())
        .collect();
    assert!(
        bar.contains(crate::icons::ACTIVITY_EXPLORER),
        "the bar must draw its glyphs while the icons bake: {bar:?}"
    );
    crate::test_budget::await_spawned(
        std::time::Duration::from_secs(3),
        "the activity-bar icon bake to land",
        || app.poll_chrome_bake(),
    );
    assert!(app.overlays.activity.has_images());
    assert!(app.overlays.activity.dirty(), "the icons are due on screen");
    assert!(app.overlays.run_debug.has_image());
    assert!(app.overlays.ssh.has_image());
}

/// A newer bake (a theme switch, a font zoom) replaces one still running:
/// only one set of icons ever goes up.
#[test]
fn a_newer_icon_bake_replaces_one_still_running() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.start_chrome_bake(kitty_chrome_bake_input());
    app.start_chrome_bake(kitty_chrome_bake_input());
    crate::test_budget::await_spawned(
        std::time::Duration::from_secs(3),
        "the activity-bar icon bake to land",
        || app.poll_chrome_bake(),
    );
    assert!(app.overlays.activity.has_images());
    assert!(!app.poll_chrome_bake(), "a second set of icons went up");
}

/// Bake `input` and wait for its pictures to go up.
fn bake_chrome_and_wait(app: &mut App, input: ChromeBakeInput) {
    app.start_chrome_bake(input);
    crate::test_budget::await_spawned(
        std::time::Duration::from_secs(3),
        "the activity-bar icon bake to land",
        || app.poll_chrome_bake(),
    );
}

/// A theme switch takes the old theme's icons down at once: they carry its
/// ink and opaque background, and re-sent while the new ones bake they
/// would paint the old theme onto the new one. The glyphs, in the new
/// theme, stand in until the new icons land.
#[test]
fn a_theme_switch_takes_the_old_themes_icons_down_while_the_new_ones_bake() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    bake_chrome_and_wait(&mut app, kitty_chrome_bake_input());
    let _ = app.consume_activity_image_clear();
    let light = ChromeBakeInput {
        icon_bg: ::image::Rgba([0xf3, 0xf3, 0xf3, 0xff]),
        ..kitty_chrome_bake_input()
    };
    app.start_chrome_bake(light);
    assert!(
        !app.overlays.activity.has_images(),
        "the old theme's icons stayed up while the new ones baked"
    );
    assert!(!app.overlays.run_debug.has_image());
    assert!(
        app.consume_activity_image_clear(),
        "the old icons must be evicted from the screen, not just forgotten"
    );
    crate::test_budget::await_spawned(
        std::time::Duration::from_secs(3),
        "the new theme's icons to land",
        || app.poll_chrome_bake(),
    );
    assert!(app.overlays.activity.has_images());
}

/// A font zoom on Kitty rescales the icons in their cells, so they stay up
/// until the ones for the new cell size land; on sixel a picture is sized
/// in pixels and would outgrow its cells (#1843), so it comes down at once.
#[test]
fn a_cell_size_change_takes_icons_down_only_on_sixel() {
    for (protocol, stays) in [
        (crate::iterm2_inline::InlineImageProtocol::Kitty, true),
        (crate::iterm2_inline::InlineImageProtocol::Sixel, false),
    ] {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        let input = ChromeBakeInput {
            protocol,
            ..kitty_chrome_bake_input()
        };
        bake_chrome_and_wait(&mut app, input);
        app.start_chrome_bake(ChromeBakeInput {
            cell: (10, 20),
            ..input
        });
        assert_eq!(
            app.overlays.activity.has_images(),
            stays,
            "{protocol:?}: icons {} while the new cell size baked",
            if stays { "came down" } else { "stayed up" }
        );
    }
}

#[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(empty_activity_images());
    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(empty_activity_images());
    let place = |app: &mut App, base: u16| {
        app.sidebar_areas.activity_icons[ActivityIcon::Explorer] = Rect::new(0, base, 2, 1);
        app.sidebar_areas.activity_icons[ActivityIcon::Search] = Rect::new(0, base + 2, 2, 1);
        app.sidebar_areas.activity_icons[ActivityIcon::SourceControl] =
            Rect::new(0, base + 4, 2, 1);
        app.sidebar_areas.activity_icons[ActivityIcon::Remote] = Rect::new(0, base + 6, 2, 1);
        app.sidebar_areas.activity_icons[ActivityIcon::RunDebug] = Rect::new(0, base + 8, 2, 1);
        app.sidebar_areas.activity_icons[ActivityIcon::Extensions] = Rect::new(0, base + 10, 2, 1);
        app.sidebar_areas.activity_icons[ActivityIcon::Testing] = 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",
    );
}

/// #1356: the status bar and the git status name the operation and, for
/// a rebase, the step.
#[test]
fn the_status_bar_names_the_operation_in_progress() {
    let tmp = diverged_repo();
    let p = tmp.path();
    assert!(!git_succeeds(p, &["merge", "feat"]));
    let status = crate::git::query(p);
    let text: String = git_status_spans(&status, crate::theme::Theme::default())
        .iter()
        .map(|s| s.content.to_string())
        .collect();
    assert!(text.contains("main") && text.contains("MERGING"), "{text}");
    assert!(git_succeeds(p, &["merge", "--abort"]));
    assert!(git_succeeds(p, &["checkout", "-q", "feat"]));
    assert!(!git_succeeds(p, &["rebase", "main"]));
    let status = crate::git::query(p);
    let text: String = git_status_spans(&status, crate::theme::Theme::default())
        .iter()
        .map(|s| s.content.to_string())
        .collect();
    assert!(text.contains("REBASING 1/1"), "{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: seven view icons (CodeQL's is added, not built in) + the sponsor heart + 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"
    );
}

/// 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"
    );
}

/// Croft Loch's activity bar recedes: icons rest muted, a hovered one lifts
/// to body text, the selected one is the strong ink beside the accent pill,
/// no glyph is bold, and a count badge is a tint of the accent rather than a
/// hard teal block.
#[test]
fn croft_loch_activity_icons_rest_muted_hover_to_text_and_tint_their_badge() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, _) = app_with_unsaved_file(tmp.path());
    let t = crate::theme::tones(app.theme).expect("Croft Loch is the default");
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();
    let search = app.sidebar_areas.activity_icons[ActivityIcon::Search];
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Moved,
        column: search.x + 1,
        row: search.y,
        modifiers: KeyModifiers::NONE,
    });
    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)| ((x, y), buf[(x, y)].clone()))
            .unwrap_or_else(|| panic!("the activity bar must paint {glyph:?}"))
    };
    let ((ex, ey), selected) = cell_of(crate::icons::ACTIVITY_EXPLORER);
    let (_, hovered) = cell_of(crate::icons::ACTIVITY_SEARCH);
    let (_, resting) = cell_of(crate::icons::ACTIVITY_EXTENSIONS);
    assert_eq!(selected.fg, t.strong());
    assert_eq!(hovered.fg, t.text());
    assert_eq!(resting.fg, t.muted());
    for cell in [&selected, &hovered, &resting] {
        assert!(!cell.modifier.contains(Modifier::BOLD), "no bold glyphs");
    }
    let pill = &buf[(0, ey)];
    assert_eq!((pill.symbol(), pill.fg), ("\u{258e}", t.accent()));
    // The Explorer's unsaved count rides its slot's bottom-right cell.
    let badge = &buf[(ex + 1, ey + 1)];
    assert_eq!(badge.symbol(), "1");
    let fill = crate::gradient::rgb_color(crate::gradient::lerp_rgb(t.chrome, t.accent, 0.22));
    assert_eq!(badge.bg, fill, "a tint of the accent, not the accent");
    assert!(!badge.modifier.contains(Modifier::BOLD));
}

/// Croft Loch paints the workbench as surfaces on exactly the layout every
/// other theme gets: the same side bar and tree rects as Croft Black, no
/// line box in the side bar or the panel, the side bar and status bar on
/// chrome, and a hairline seam where the side bar meets the editor column.
#[test]
fn croft_loch_paints_surfaces_on_croft_blacks_layout() {
    let render = |id: &str| {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.apply_theme(crate::theme::Theme::from_id(id));
        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().clone();
        let side = app.last_sidebar_area.expect("the side bar is shown");
        let panel = app.terminals[0].last_area;
        (side, app.tree.last_inner, panel, buf)
    };
    let (side, tree, panel, black) = render("black");
    let (loch_side, loch_tree, loch_panel, buf) = render("loch");
    assert_eq!((loch_side, loch_tree, loch_panel), (side, tree, panel));
    assert!(!panel.is_empty(), "the terminal panel is painted");
    let boxed = |r: ratatui::layout::Rect, b: &ratatui::buffer::Buffer| {
        (r.top()..r.bottom())
            .flat_map(|y| (r.left()..r.right()).map(move |x| (x, y)))
            .filter(|&(x, y)| {
                "\u{250c}\u{2510}\u{2500}\u{2502}\u{2501}\u{2503}\u{256d}\u{256e}\u{2570}\u{256f}"
                    .contains(b[(x, y)].symbol())
            })
            .count()
    };
    assert!(boxed(side, &black) > 0 && boxed(panel, &black) > 0);
    assert_eq!(boxed(side, &buf), 0, "no box in Croft Loch's side bar");
    assert_eq!(boxed(panel, &buf), 0, "no box around Croft Loch's terminal");
    let s = crate::theme::Theme::from_id("loch").surfaces().unwrap();
    let seam = (side.top()..side.bottom())
        .map(|y| &buf[(side.right() - 1, y)])
        .filter(|c| c.symbol() == "\u{2595}" && c.fg == s.hairline())
        .count();
    assert!(
        seam > side.height as usize / 2,
        "a hairline down the side bar's edge"
    );
    assert_eq!(buf[(side.x + 2, side.bottom() - 2)].bg, s.chrome());
    assert_eq!(buf[(60, 39)].bg, s.chrome(), "the status bar is chrome");
}

/// Croft Loch fills the activity bar's rows between its baked icons with
/// chrome, and must leave the sponsor heart's rows (#1940) to its image like
/// every other icon's: a cell repainted under an inline image forces the
/// image to be re-sent, and the fill shows through it.
#[test]
fn croft_loch_leaves_the_sponsor_hearts_rows_to_its_baked_image() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.apply_theme(crate::theme::Theme::from_id("loch"));
    app.overlays
        .activity
        .set_images(ActivityBarImages::default());
    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 chrome = crate::theme::Theme::from_id("loch")
        .surfaces()
        .unwrap()
        .chrome();
    let heart = app.sidebar_areas.activity_icons[ActivityIcon::Sponsor];
    assert!(!heart.is_empty(), "a 40-row bar has room for the heart");
    for y in heart.top()..heart.bottom() {
        assert_ne!(
            buf[(heart.x, y)].bg,
            chrome,
            "heart row {y} left to its image"
        );
    }
    let above = heart.top() - 1;
    let last_view = app.sidebar_areas.activity_icons[ActivityIcon::Testing].bottom();
    assert!(
        above >= last_view.max(app.sidebar_areas.activity_icons[ActivityIcon::CodeQL].bottom())
    );
    assert_eq!(
        buf[(heart.x, above)].bg,
        chrome,
        "the gap above the heart is chrome"
    );
}

#[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 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.gesture, Some(Gesture::Splitter(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!(!matches!(app.gesture, Some(Gesture::Splitter(_))));
}

/// A release croft never receives (the button let go outside the window,
/// or a terminal that drops it) must not leave that drag live: the next
/// press starts a new gesture. Here a side-bar splitter press loses its
/// release, then a drag in the editor's text selects text and leaves the
/// side bar's width alone. Before, every later drag kept resizing the side
/// bar until a release arrived.
#[test]
fn a_press_after_a_lost_release_starts_a_new_gesture() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let (mut app, _tmp, _f) = app_with_painted_file("alpha beta gamma delta\nsecond line\n");
    let seam = app
        .sidebar_splitter_x
        .expect("the side bar is shown, so its splitter is drawn");
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), seam, 5));
    assert_eq!(app.gesture, Some(Gesture::Splitter(SplitterDrag::Sidebar)));
    // The release of that press never arrives.
    let width = app.sidebar_width;
    let x = app.editor.last_inner.x + app.editor.last_gutter_width + 1;
    let y = app.editor.last_inner.y;
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), x, y));
    app.handle_mouse(mouse(MouseEventKind::Drag(MouseButton::Left), x + 6, y));
    assert_eq!(
        app.sidebar_width, width,
        "the drag after a new press is the new press's, not the lost splitter drag's"
    );
    assert!(
        app.editor.selection.is_some(),
        "the drag in the text selects text"
    );
    app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), x + 6, y));
    assert!(!matches!(app.gesture, Some(Gesture::Splitter(_))));
}

#[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.gesture, Some(Gesture::Splitter(SplitterDrag::Sidebar)));
}

#[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);
}

/// 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"
    );
}

#[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.panel_hits.rail_rows[0];
    let target = app.panel_hits.rail_rows[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 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.activity_icons[ActivityIcon::SourceControl];
    let run = app.sidebar_areas.activity_icons[ActivityIcon::RunDebug];
    let rem = app.sidebar_areas.activity_icons[ActivityIcon::Remote];
    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
    );
}

// #865: the update pills in the status bar are a click target too, and say
// which chord the updater is on.
#[test]
fn clicking_the_status_bar_update_pill_starts_the_rebuild() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.local_drift = Some(String::from("def456"));
    let backend = ratatui::backend::TestBackend::new(200, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let pill = app.status_hits.update;
    assert!(pill.width > 0, "the drift pill is a click target");
    let bar: String = (0..200)
        .map(|x| term.backend().buffer()[(x, pill.y)].symbol().to_string())
        .collect();
    assert!(
        bar.contains(&format!("{} to rebuild", super::UPDATE_CROFT_CHORD)),
        "{bar}"
    );
    left_click(&mut app, pill.x + 1, pill.y);
    assert!(app.self_install.is_some(), "a click starts the rebuild");
}

#[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.open_commit_actions_menu(false);
    assert!(app.context_menu.is_some());
    // 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.context_menu.is_none(),
        "the commit dropdown must close when the sidebar view changes"
    );
}

// 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.session.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())
    );
}

#[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 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 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",
    );
}

/// OUTPUT's clear empties the log on screen (#2861), not only the bus
/// behind it: the click moves no focus, and the view used to refresh only
/// when focus moved, so the cleared lines stayed up.
#[test]
fn clicking_output_clear_empties_the_shown_log() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // The bus is process-wide, so the channel carries a name no other test
    // uses.
    let channel = "Clear 2861";
    for i in 0..3 {
        crate::output::push(
            channel,
            crate::output::OutputLevel::Info,
            &format!("cleared line {i}"),
        );
    }
    app.output.sync();
    assert!(app.output.select_by_name(channel));
    app.bottom_panel_tab = BottomPanelTab::Output;
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(140, 50)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let area = app.output.last_area;
    let shown = |term: &ratatui::Terminal<ratatui::backend::TestBackend>| {
        let buf = term.backend().buffer();
        (area.y..area.bottom())
            .flat_map(|y| (area.x..area.right()).map(move |x| (x, y)))
            .map(|(x, y)| buf[(x, y)].symbol().to_string())
            .collect::<String>()
    };
    assert!(shown(&term).contains("cleared line 2"), "{}", shown(&term));
    // The toolbar's "clear" token, found by its cells on the header row.
    let header: Vec<String> = {
        let buf = term.backend().buffer();
        (area.x..area.right())
            .map(|x| buf[(x, area.y)].symbol().to_string())
            .collect()
    };
    let at = (0..header.len().saturating_sub(5))
        .find(|&i| header[i..i + 5].concat() == "clear")
        .expect("the toolbar draws its clear button") as u16;
    let (x, y) = (area.x + at + 1, area.y);
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), x, y));
    app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), x, y));
    term.draw(|f| app.render(f)).unwrap();
    assert!(
        !shown(&term).contains("cleared line"),
        "clear empties the shown log: {}",
        shown(&term)
    );
}

#[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.panel_hits.terminal_tab;
    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",
    );
}

/// Croft Loch's panel tabs take three steps: the active title in the strong
/// ink with the accent underline and no bold, a hovered title in body text
/// (not the active ink), the rest muted; and the first title's word starts
/// on the terminal's first text column.
#[test]
fn croft_loch_panel_tabs_step_from_muted_to_text_to_strong() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let t = crate::theme::tones(app.theme).expect("Croft Loch is the default");
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let out = app.panel_hits.output_tab;
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Moved,
        column: out.x + 2,
        row: out.y,
        modifiers: KeyModifiers::NONE,
    });
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer();
    let word = |r: ratatui::layout::Rect| {
        (r.x..r.right())
            .map(|x| &buf[(x, r.y)])
            .find(|c| c.symbol() != " ")
            .unwrap()
            .clone()
    };
    let active = word(app.panel_hits.terminal_tab);
    assert_eq!(active.fg, t.strong());
    assert!(!active.modifier.contains(Modifier::BOLD));
    assert!(active.modifier.contains(Modifier::UNDERLINED));
    assert_eq!(active.underline_color, t.accent());
    assert_eq!(
        word(app.panel_hits.output_tab).fg,
        t.text(),
        "hover is body text"
    );
    assert_eq!(word(app.panel_hits.ports_tab).fg, t.muted());
    let first = app.panel_hits.problems_tab;
    assert_eq!(buf[(first.x, first.y)].symbol(), "P", "no leading pad");
    let inner = app.terminals[0].last_inner;
    assert_eq!(first.x, inner.x, "the first title lines up with the shell");
}

/// Croft Loch: behind an open Command Palette the active panel tab's accent
/// underline sinks with the rest of the backdrop, so the card's lip and its
/// selection bar are the only full-strength accent on screen.
#[test]
fn croft_loch_palette_scrim_sinks_the_active_tabs_underline() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let t = crate::theme::tones(app.theme).expect("Croft Loch is the default");
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    app.open_command_palette();
    // A query that leaves a short card, so the panel's tab strip is
    // clear of it and only the scrim lies over the tab.
    app.command_palette
        .as_mut()
        .unwrap()
        .set_query("toggle terminal");
    term.draw(|f| app.render(f)).unwrap();
    let card = app.command_palette.as_ref().unwrap().last_rect;
    let tab = app.panel_hits.terminal_tab;
    assert!(
        card.intersection(tab).is_empty(),
        "the tab is behind the scrim: {card:?} / {tab:?}"
    );
    let buf = term.backend().buffer();
    let word = (tab.x..tab.right())
        .map(|x| &buf[(x, tab.y)])
        .find(|c| c.symbol() != " ")
        .unwrap();
    assert!(word.modifier.contains(Modifier::UNDERLINED));
    assert_ne!(word.underline_color, t.accent(), "no full-strength teal");
    let ratatui::style::Color::Rgb(r, g, b) = word.bg else {
        panic!("the scrim leaves an RGB fill: {:?}", word.bg);
    };
    let sunk = crate::gradient::lerp_rgb(t.accent, (r, g, b), 0.58);
    assert_eq!(
        word.underline_color,
        crate::gradient::rgb_color(sunk),
        "the underline sinks as far as the title's ink does"
    );
}

/// Croft Loch gives every panel pane a top edge: the terminal and the views
/// that share the panel draw a hairline under the tab strip, and the accent
/// lip while the panel has the keyboard.
#[test]
fn croft_loch_panel_panes_draw_a_hairline_or_the_lip_on_their_top_edge() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let t = crate::theme::tones(app.theme).expect("Croft Loch is the default");
    app.focus_pane(Pane::Editor);
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let pane = app.terminals[0].last_area;
    let top = |term: &ratatui::Terminal<ratatui::backend::TestBackend>, x: u16, y: u16| {
        let c = &term.backend().buffer()[(x, y)];
        (c.symbol().to_string(), c.fg)
    };
    assert_eq!(
        top(&term, pane.x + 4, pane.y),
        ("\u{2594}".to_string(), t.hairline()),
        "an unfocused pane's top edge is the hairline"
    );
    app.focus_pane(Pane::Terminal);
    term.draw(|f| app.render(f)).unwrap();
    assert_eq!(
        top(&term, pane.x, pane.y),
        ("\u{2594}".to_string(), t.accent()),
        "the focused pane's lip starts in the accent"
    );
    app.set_bottom_panel_tab(BottomPanelTab::Problems);
    app.focus_pane(Pane::Editor);
    term.draw(|f| app.render(f)).unwrap();
    let view = app.problems.last_area;
    assert_eq!(
        top(&term, view.x, view.y),
        ("\u{2594}".to_string(), t.hairline()),
        "PROBLEMS draws the same edge"
    );
}

#[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"
    );
}

#[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 {
        icons: [
            ActivityIconImages {
                active: Some("EA".into()),
                inactive: "EI".into(),
                hovered: "EH".into(),
            },
            ActivityIconImages {
                active: Some("SA".into()),
                inactive: "SI".into(),
                hovered: "SH".into(),
            },
            ActivityIconImages {
                active: Some("CA".into()),
                inactive: "CI".into(),
                hovered: "CH".into(),
            },
            ActivityIconImages {
                active: Some("RA".into()),
                inactive: "RI".into(),
                hovered: "RH".into(),
            },
            ActivityIconImages {
                active: Some("DA".into()),
                inactive: "DI".into(),
                hovered: "DH".into(),
            },
            ActivityIconImages {
                active: Some("XA".into()),
                inactive: "XI".into(),
                hovered: "XH".into(),
            },
            ActivityIconImages {
                active: Some("TA".into()),
                inactive: "TI".into(),
                hovered: "TH".into(),
            },
            ActivityIconImages {
                active: Some("CA".into()),
                inactive: "CI".into(),
                hovered: "CH".into(),
            },
            ActivityIconImages {
                active: None,
                inactive: "HI".into(),
                hovered: "HH".into(),
            },
            ActivityIconImages {
                active: Some("GA".into()),
                inactive: "GI".into(),
                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.activity_icons[ActivityIcon::Explorer] = Rect::new(0, 0, 2, 1);
    app.sidebar_areas.activity_icons[ActivityIcon::Search] = Rect::new(0, 2, 2, 1);
    app.sidebar_areas.activity_icons[ActivityIcon::SourceControl] = Rect::new(0, 4, 2, 1);
    app.sidebar_areas.activity_icons[ActivityIcon::Remote] = Rect::new(0, 6, 2, 1);
    app.sidebar_areas.activity_icons[ActivityIcon::RunDebug] = Rect::new(0, 8, 2, 1);
    app.sidebar_areas.activity_icons[ActivityIcon::Extensions] = Rect::new(0, 10, 2, 1);
    app.sidebar_areas.activity_icons[ActivityIcon::Testing] = 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"
    );
}

/// #1940: the sponsor heart emits its resting bake, and swaps to its
/// hovered one while the pointer is on it.
#[test]
fn hovering_the_sponsor_heart_emits_its_hovered_variant() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let mut images = ActivityBarImages::default();
    images.icons[ActivityIcon::Sponsor as usize] = ActivityIconImages {
        active: None,
        inactive: "HI".into(),
        hovered: "HH".into(),
    };
    app.overlays.activity.set_images(images);
    let emitted = |app: &App| -> Vec<String> {
        app.pending_activity_image_overlays()
            .into_iter()
            .map(|(_, s)| s.to_string())
            .collect()
    };
    draw(&mut app, 120, 40);
    assert!(emitted(&app).contains(&"HI".to_string()));
    let heart = app.sidebar_areas.activity_icons[ActivityIcon::Sponsor];
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Moved,
        column: heart.x,
        row: heart.y,
        modifiers: KeyModifiers::NONE,
    });
    assert_eq!(app.hovered_activity_icon, Some(ActivityIcon::Sponsor));
    let hovered = emitted(&app);
    assert!(hovered.contains(&"HH".to_string()), "{hovered:?}");
    assert!(!hovered.contains(&"HI".to_string()), "{hovered:?}");
}

/// #1845: a collapsed side bar selects no view, as in VS Code, so its view's
/// icon drops the pill, and the flip re-sends the baked icons whichever
/// route made it.
#[test]
fn a_collapsed_side_bar_unpills_its_views_activity_icon() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let mut images = ActivityBarImages::default();
    images.icons[ActivityIcon::Explorer as usize] = ActivityIconImages {
        active: Some("EA".into()),
        inactive: "EI".into(),
        hovered: "EH".into(),
    };
    app.overlays.activity.set_images(images);
    let emitted = |app: &App| -> Vec<String> {
        app.pending_activity_image_overlays()
            .into_iter()
            .map(|(_, s)| s.to_string())
            .collect()
    };
    draw(&mut app, 120, 40);
    assert!(emitted(&app).contains(&"EA".to_string()));
    app.overlays.activity.mark_emitted();
    draw(&mut app, 120, 40);
    assert!(
        !app.overlays.activity.dirty(),
        "an unchanged frame re-sends nothing"
    );
    // Cmd+B's route, which marks no overlay dirty itself.
    app.toggle_side_bar();
    draw(&mut app, 120, 40);
    assert!(
        app.overlays.activity.dirty(),
        "closing the side bar re-sends the icons"
    );
    let shown = emitted(&app);
    assert!(shown.contains(&"EI".to_string()), "{shown:?}");
    assert!(!shown.contains(&"EA".to_string()), "{shown:?}");
}

#[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.activity_icons[ActivityIcon::Search] = 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 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:?}"
    );
    // Once a key has been pressed the right cluster is back (#1609), and the
    // message still keeps its tail beside it.
    app.handle_key(key(KeyCode::Right, KeyModifiers::NONE))
        .unwrap();
    app.status = format!("Opened /{deep}main.rs");
    app.status_logged = app.status.clone();
    term.draw(|f| app.render(f)).unwrap();
    let last_row = status_row(&term);
    assert!(last_row.contains("main.rs"), "{last_row:?}");
    assert!(
        last_row.contains("Ln 1, Col 1"),
        "the right cluster must still paint: {last_row:?}"
    );
}

/// #1609: a message is measured in terminal cells, so a path of
/// double-width names is elided to fit beside the right cluster instead of
/// counting half its width and having its tail painted over.
#[test]
fn status_message_with_wide_chars_keeps_its_tail_beside_the_cluster() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let backend = ratatui::backend::TestBackend::new(140, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    let deep = "\u{76ee}\u{5f55}/".repeat(15);
    app.status = format!("Opened /{deep}main.rs");
    app.status_logged = app.status.clone();
    app.status_wide = false;
    term.draw(|f| app.render(f)).unwrap();
    let row = status_row(&term);
    assert!(
        row.contains("Ln 1, Col 1"),
        "the right cluster paints: {row:?}"
    );
    assert!(
        row.contains("main.rs"),
        "the wide-char message keeps its tail: {row:?}"
    );
}

/// The status bar's left cap names the workspace folder, and every click
/// target after it is placed by counting cells: a double-width name
/// (`项目`, four cells for two chars) must not shift the problem counts'
/// target left of the counts it opens.
#[test]
fn a_wide_workspace_name_keeps_the_status_bar_targets_under_their_text() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().join("\u{9879}\u{76ee}");
    std::fs::create_dir(&root).unwrap();
    let mut app = App::new(root).unwrap();
    let backend = ratatui::backend::TestBackend::new(120, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer().clone();
    let y = buf.area.height - 1;
    let glyph_x = (0..buf.area.width)
        .find(|&x| buf[(x, y)].symbol() == "\u{ea87}")
        .expect("the error count's glyph is on the bar");
    // A wide char's second cell reads as a blank in the buffer.
    let row = status_row(&term);
    assert!(
        row.contains("\u{9879} \u{76ee} "),
        "the cap names the folder: {row:?}"
    );
    // The counts' target opens on the space before the glyph.
    assert_eq!(app.status_hits.diagnostics.x + 1, glyph_x);
    assert_eq!(app.status_hits.diagnostics.y, y);
}

/// #925: a message of several lines (git's text, a tool's error) is drawn
/// with a space where each line break or tab was; drawn as is, they were
/// dropped and the words either side ran together.
#[test]
fn a_multi_line_status_message_keeps_its_words_apart() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let backend = ratatui::backend::TestBackend::new(140, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    app.status =
        String::from("Branch: overwritten by checkout:\n\ta.txt\nswitch branches.\nAborting");
    term.draw(|f| app.render(f)).unwrap();
    let row = status_row(&term);
    assert!(
        row.contains("Branch: overwritten by checkout: a.txt switch branches. Aborting"),
        "{row:?}"
    );
}

/// The recorder's prompt from Preferences: Open Keyboard Shortcuts, which
/// is longer than the room the right-hand cluster leaves at 140 columns.
fn recorder_prompt() -> String {
    String::from(
        "Press the new shortcut for \u{201c}Sort Lines Ascending\u{201d} (a function key or a chord with Cmd/Ctrl/Alt; Esc cancels)",
    )
}

/// #1609: a new message too long for the room beside Ln/Col, encoding and
/// language takes the whole bar, so its middle is not cut away; the next key
/// hands the room back.
#[test]
fn a_new_long_status_message_takes_the_whole_bar_until_a_key() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let backend = ratatui::backend::TestBackend::new(140, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    app.status = recorder_prompt();
    term.draw(|f| app.render(f)).unwrap();
    let row = status_row(&term);
    assert!(
        row.contains(&recorder_prompt()),
        "the whole message shows at 140 columns: {row:?}"
    );
    assert!(
        !row.contains("Ln 1, Col 1"),
        "the cluster made room: {row:?}"
    );
    // Redrawing without input keeps it whole.
    term.draw(|f| app.render(f)).unwrap();
    assert!(status_row(&term).contains(&recorder_prompt()));

    app.handle_mouse(MouseEvent {
        kind: MouseEventKind::Down(MouseButton::Left),
        column: 60,
        row: 5,
        modifiers: KeyModifiers::NONE,
    });
    app.status = recorder_prompt();
    term.draw(|f| app.render(f)).unwrap();
    let row = status_row(&term);
    assert!(
        row.contains("Ln 1, Col 1"),
        "a click brings the cluster back: {row:?}"
    );
    assert!(
        row.contains('\u{2026}'),
        "and the old message elides beside it: {row:?}"
    );
}

/// #1609: every message shown is kept, in full, in the Messages output
/// channel, and a click on the message opens it there.
#[test]
fn status_messages_are_kept_in_the_messages_channel() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let backend = ratatui::backend::TestBackend::new(120, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    let first = format!("{} #{}", recorder_prompt(), std::process::id());
    let second = format!("Fleet: no host named web1 #{}", std::process::id());
    app.status = first.clone();
    term.draw(|f| app.render(f)).unwrap();
    app.status = second.clone();
    term.draw(|f| app.render(f)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let lines: Vec<String> = crate::output::snapshot(crate::output::CHANNEL_MESSAGES)
        .unwrap_or_default()
        .into_iter()
        .map(|l| l.text)
        .collect();
    assert_eq!(
        lines.iter().filter(|l| **l == first).count(),
        1,
        "{lines:?}"
    );
    assert_eq!(
        lines.iter().filter(|l| **l == second).count(),
        1,
        "logged once"
    );

    let r = app.status_hits.message;
    assert!(r.width > 0, "the message has a click target");
    app.handle_mouse(MouseEvent {
        kind: MouseEventKind::Down(MouseButton::Left),
        column: r.x + 1,
        row: r.y,
        modifiers: KeyModifiers::NONE,
    });
    assert_eq!(app.bottom_panel_tab, BottomPanelTab::Output);
    assert_eq!(
        app.output.selected_name().as_deref(),
        Some(crate::output::CHANNEL_MESSAGES)
    );
}

/// Negative: a message that fits beside the cluster leaves it in place, and
/// an empty status logs nothing.
#[test]
fn a_status_message_that_fits_keeps_the_cluster() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let backend = ratatui::backend::TestBackend::new(120, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    app.status = String::from("Saved");
    term.draw(|f| app.render(f)).unwrap();
    let row = status_row(&term);
    assert!(
        row.contains("Saved") && row.contains("Ln 1, Col 1"),
        "{row:?}"
    );
    app.status.clear();
    term.draw(|f| app.render(f)).unwrap();
    let lines = crate::output::snapshot(crate::output::CHANNEL_MESSAGES).unwrap_or_default();
    assert!(
        lines.iter().all(|l| !l.text.is_empty()),
        "an empty status is not logged"
    );
    assert_eq!(
        app.status_hits.message.width, 0,
        "no message, no click target"
    );
}

// --- 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 chrome_drops_a_secondary_side_bar_the_window_cannot_fit() {
    // #1132 (comment): at 30 columns the 30-column secondary bar was placed
    // past the right edge of the frame, and its scrollbar wrote outside it.
    let narrow = Rect::new(0, 0, 30, 9);
    for pos in [SideBarPosition::Left, SideBarPosition::Right] {
        let l = compute_chrome_layout(narrow, true, true, true, pos, 20, 30);
        assert!(
            l.secondary_side.is_none(),
            "{pos:?}: {:?}",
            l.secondary_side
        );
        for r in [l.activity, l.primary_side, Some(l.right)]
            .into_iter()
            .flatten()
        {
            assert!(r.right() <= narrow.right(), "{pos:?}: {r:?}");
        }
    }
}

#[test]
fn chrome_keeps_the_secondary_side_bar_when_it_fits() {
    // Negative: with room for it next to the editor's minimum, the secondary
    // bar keeps its full width.
    let l = compute_chrome_layout(
        main_band(),
        true,
        false,
        true,
        SideBarPosition::Left,
        20,
        30,
    );
    assert_eq!(l.secondary_side.map(|s| s.width), Some(30));
}

#[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);
}

/// The editor as last drawn, `(x, width)` (#1585): its text and the
/// minimap strip carved from its right edge. Centered Layout centres the
/// two together, as VS Code centres an editor with its minimap.
fn editor_column(app: &App) -> (u16, u16) {
    let text = app.editor.last_full_area;
    let strip = if app.minimap.visible && app.minimap.room {
        MINIMAP_WIDTH_CELLS
    } else {
        0
    };
    (text.x, text.width + strip)
}

/// #1585: Zen Mode centres the editor: in 200 columns it is 120 wide and
/// starts at column 40, like VS Code's `zenMode.centerLayout`. The
/// minimap is part of those 120 columns; without it the text takes them.
#[test]
fn zen_mode_centres_the_editor_in_a_wide_window() {
    let (_tmp, mut app) = zen_app();
    app.toggle_zen_mode();
    draw_screen(&mut app, 200, 30);
    assert!(app.minimap.visible && app.minimap.room, "the minimap shows");
    assert_eq!(
        editor_column(&app),
        (40, 120),
        "{:?}",
        app.editor.last_full_area
    );
    app.toggle_minimap();
    draw_screen(&mut app, 200, 30);
    let area = app.editor.last_full_area;
    assert_eq!((area.x, area.width), (40, 120), "{area:?}");
    app.toggle_minimap();
    app.toggle_zen_mode();
    draw_screen(&mut app, 200, 30);
    assert!(
        editor_column(&app).1 > 120,
        "out of Zen the editor fills its column again: {:?}",
        app.editor.last_full_area
    );
}

/// #1585: View: Toggle Centered Layout centres the editor outside Zen and
/// persists in the layout; inside a centred Zen it turns the centring off.
#[test]
fn toggle_centered_layout_centres_outside_zen_and_uncentres_zen() {
    let (_tmp, mut app) = zen_app();
    app.show_tree = false;
    app.activity_bar_visible = false;
    app.show_terminal = false;
    app.run_command(crate::widgets::command_palette::Command::ToggleCenteredLayout);
    assert!(app.centered_layout);
    assert_eq!(app.status, "Centered Layout on");
    draw_screen(&mut app, 200, 30);
    assert_eq!(editor_column(&app), (40, 120));
    app.run_command(crate::widgets::command_palette::Command::ToggleCenteredLayout);
    assert!(!app.centered_layout);

    app.toggle_zen_mode();
    assert!(app.centered_layout_active(), "Zen starts centred");
    app.run_command(crate::widgets::command_palette::Command::ToggleCenteredLayout);
    assert!(!app.centered_layout_active() && !app.centered_layout);
    draw_screen(&mut app, 200, 30);
    assert_eq!(editor_column(&app), (0, 200));
    let rows = app.customize_layout_items();
    assert!(
        rows.iter().any(|r| matches!(r, MenuEntry::Item { label, action: MenuAction::ToggleCenteredLayout, .. } if label.contains("Centered Layout"))),
        "the Customize Layout popup has the row"
    );
}

/// #1585, negative: a window no wider than the centred width, or Zen with
/// `zen_center_layout` off, leaves the editor its whole column.
#[test]
fn a_narrow_window_or_zen_without_centring_keeps_the_full_width() {
    let (_tmp, mut app) = zen_app();
    app.toggle_zen_mode();
    draw_screen(&mut app, 110, 30);
    assert_eq!(editor_column(&app), (0, 110));
    app.toggle_zen_mode();
    app.zen_center_layout = false;
    app.toggle_zen_mode();
    draw_screen(&mut app, 200, 30);
    assert_eq!(editor_column(&app), (0, 200));
    assert_eq!(
        centered_editor_rect(Rect::new(5, 1, 50, 9), 0),
        Rect::new(5, 1, 50, 9),
        "a zero width centres nothing"
    );
    assert_eq!(
        centered_editor_rect(Rect::new(5, 1, 51, 9), 20),
        Rect::new(20, 1, 20, 9)
    );
}

/// #1585: Esc Esc leaves Zen Mode and restores the chrome from before it.
#[test]
fn esc_esc_leaves_zen_mode_and_restores_the_chrome() {
    let (_tmp, mut app) = zen_app();
    app.show_tree = true;
    app.status_bar_visible = true;
    app.toggle_zen_mode();
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    assert!(app.zen_mode(), "one Esc is not enough");
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    assert!(!app.zen_mode(), "Esc Esc leaves Zen");
    assert!(app.show_tree && app.status_bar_visible);
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    assert!(!app.zen_mode(), "Esc Esc never enters Zen");
}

/// #1585: Zen hides the status bar, so entering it shows how to leave for
/// a few seconds; leaving takes the hint with it.
#[test]
fn entering_zen_says_how_to_leave_it_for_a_while() {
    let (_tmp, mut app) = zen_app();
    assert!(!draw_screen(&mut app, 120, 30).contains("Esc Esc to exit"));
    app.toggle_zen_mode();
    assert!(draw_screen(&mut app, 120, 30).contains(zen_hint_text()));
    assert!(!app.expire_zen_hint(std::time::Instant::now()), "not yet");
    assert!(app.expire_zen_hint(std::time::Instant::now() + ZEN_HINT_FOR));
    assert!(!draw_screen(&mut app, 120, 30).contains("Esc Esc to exit"));
    app.toggle_zen_mode();
    app.toggle_zen_mode();
    app.toggle_zen_mode();
    assert!(
        app.zen_hint_until.is_none(),
        "leaving Zen drops a hint still showing"
    );
}

#[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");
}

/// #1845: as in VS Code, a click on the icon of the view the side bar is
/// showing collapses the side bar, and the next click on it expands it again.
#[test]
fn clicking_the_open_views_activity_icon_collapses_then_reopens_the_side_bar() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    draw(&mut app, 120, 40);
    let explorer = app.sidebar_areas.activity_icons[ActivityIcon::Explorer];
    assert!(app.show_tree && app.sidebar_view == SidebarView::Explorer);
    app.focus_pane(Pane::Tree);
    left_click(&mut app, explorer.x, explorer.y);
    assert!(
        !app.show_tree,
        "the open view's icon collapses the side bar"
    );
    assert!(
        app.focus == Pane::Editor,
        "focus leaves the hidden side bar"
    );
    draw(&mut app, 120, 40);
    left_click(&mut app, explorer.x, explorer.y);
    assert!(app.show_tree, "the next click expands it again");
    assert_eq!(app.sidebar_view, SidebarView::Explorer);
    assert!(app.focus == Pane::Tree);
}

#[test]
fn clicking_another_views_activity_icon_switches_and_expands_a_collapsed_side_bar() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    draw(&mut app, 120, 40);
    let explorer = app.sidebar_areas.activity_icons[ActivityIcon::Explorer];
    let search = app.sidebar_areas.activity_icons[ActivityIcon::Search];
    left_click(&mut app, search.x, search.y);
    assert!(
        app.show_tree,
        "another view's icon switches, never collapses"
    );
    assert_eq!(app.sidebar_view, SidebarView::Search);
    left_click(&mut app, search.x, search.y);
    assert!(!app.show_tree);
    left_click(&mut app, explorer.x, explorer.y);
    assert!(
        app.show_tree,
        "any view's icon expands a collapsed side bar"
    );
    assert_eq!(app.sidebar_view, SidebarView::Explorer);
}

/// Collapsing from a maximized terminal's side bar hands focus to the
/// terminal: the editor taking it would un-maximize the terminal.
#[test]
fn collapsing_the_side_bar_from_its_icon_keeps_a_maximized_terminal() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    draw(&mut app, 120, 40);
    let explorer = app.sidebar_areas.activity_icons[ActivityIcon::Explorer];
    app.show_terminal = true;
    app.terminal_maximized = true;
    app.focus_pane(Pane::Tree);
    left_click(&mut app, explorer.x, explorer.y);
    assert!(!app.show_tree);
    assert!(app.focus == Pane::Terminal);
    assert!(app.terminal_maximized, "the terminal stays maximized");
}

#[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 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"
    );
}

/// 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.pair.last_check = None;
    a.maybe_seat_navigator();
    assert!(a.pair.host.is_none());
    assert!(
        a.pair.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.pair.last_check = None;
    b.maybe_seat_navigator();
    assert!(
        b.pair.host.is_some(),
        "the working window must be able to host: {}",
        b.status
    );
}

#[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]| git_succeeds(tmp.path(), args);
    git_init(tmp.path());
    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:?}"
    );
}

/// #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.gesture = Some(Gesture::Splitter(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.gesture = None;

    // Zen Mode already owns chrome visibility and wins, as it does today.
    app.pre_zen = Some(PreZenLayout::default());
    assert!(!app.sidebar_auto_hide_allowed(), "zen mode wins");
    app.pre_zen = None;

    // 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");
}

/// 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.gesture = Some(Gesture::Splitter(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.gesture = 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.pre_zen = Some(PreZenLayout::default());
    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 on (`zen_mode()`) — 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");
}

/// #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");
}

#[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.panel_hits.collapsed_strips[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!(
            !matches!(app.gesture, Some(Gesture::Splitter(_))),
            "{pos:?}: a click on a strip is not a sidebar resize"
        );
    }
}

/// 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.panel_hits
            .collapsed_strips
            .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.panel_hits.collapsed_strips[2].width, 1,
        "leaving maximize brings the strip back"
    );
}

#[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"
    );
}

/// #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.inline_protocol = InlineImageProtocol::ITerm2;
    assert!(app.chrome_image_due("k", "img", at, &buf), "new");
    app.end_chrome_flush();
    assert!(
        !app.chrome_image_due("k", "img", at, &buf),
        "unchanged frame"
    );
    app.end_chrome_flush();
    assert!(app.chrome_image_due("k", "img2", at, &buf), "changed");
    assert!(
        app.chrome_image_due("k", "img2", Rect::new(3, 2, 3, 1), &buf),
        "moved"
    );
    app.end_chrome_flush();
    buf[(2, 2)].set_symbol("x");
    assert!(
        app.chrome_image_due("k", "img2", Rect::new(3, 2, 3, 1), &buf),
        "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), &buf),
        "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), &buf));
    app.end_chrome_flush();
    buf[(2, 3)].set_symbol("y");
    assert!(
        !app.chrome_image_due("k", "img2", Rect::new(3, 2, 3, 1), &buf),
        "Kitty ignores neighbours"
    );
}

/// #852: every bottom-panel tab is reachable from the keyboard. Each tab
/// names the palette command that shows it (`show_command` has no
/// catch-all, so a new tab cannot compile without one, and the strip paints
/// from `ALL`, so a clickable tab is always in this loop); here each command
/// must be in the palette and must land on its tab, panel shown and
/// focused, from a hidden panel on another tab.
#[test]
fn every_bottom_panel_tab_is_reachable_from_the_palette() {
    use crate::widgets::command_palette::ALL_COMMANDS;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    for tab in BottomPanelTab::ALL {
        let cmd = tab.show_command();
        assert!(
            ALL_COMMANDS.contains(&cmd),
            "{cmd:?} (shows {tab:?}) is missing from the palette"
        );
        app.show_terminal = false;
        app.focus_pane(Pane::Editor);
        app.bottom_panel_tab = if tab == BottomPanelTab::Terminal {
            BottomPanelTab::Problems
        } else {
            BottomPanelTab::Terminal
        };
        app.run_command(cmd);
        assert_eq!(app.bottom_panel_tab, tab, "{cmd:?}");
        assert!(app.show_terminal, "{cmd:?} must reveal the panel");
        assert!(
            app.focus == Pane::Terminal,
            "{cmd:?} must focus the panel so its keys work at once"
        );
    }
}

/// #852: VS Code's `Ctrl/Cmd+Shift+M` and `+U` show PROBLEMS and OUTPUT from
/// any pane, the live terminal included, and `Cmd+Shift+T` brings the
/// TERMINAL tab back rather than focusing whichever tab was last up.
#[test]
fn panel_tab_chords_switch_between_problems_output_and_terminal() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let ctrl_shift = KeyModifiers::CONTROL | KeyModifiers::SHIFT;
    let cmd_shift = KeyModifiers::SUPER | KeyModifiers::SHIFT;
    app.focus_pane(Pane::Editor);
    app.handle_key(key(KeyCode::Char('M'), ctrl_shift)).unwrap();
    assert_eq!(app.bottom_panel_tab, BottomPanelTab::Problems);
    assert!(app.focus == Pane::Terminal);
    // From the PROBLEMS view itself.
    app.handle_key(key(KeyCode::Char('u'), cmd_shift)).unwrap();
    assert_eq!(app.bottom_panel_tab, BottomPanelTab::Output);
    app.handle_key(key(KeyCode::Char('T'), cmd_shift)).unwrap();
    assert_eq!(
        app.bottom_panel_tab,
        BottomPanelTab::Terminal,
        "Cmd+Shift+T must bring the TERMINAL tab forward"
    );
    assert!(app.focus == Pane::Terminal);
    // From the live shell: the chord is croft's, as the side bar jumps are.
    app.handle_key(key(KeyCode::Char('U'), ctrl_shift)).unwrap();
    assert_eq!(app.bottom_panel_tab, BottomPanelTab::Output);
    // Plain Ctrl+M / Ctrl+U stay the shell's (Enter, kill line).
    assert!(!is_show_problems_key(key(
        KeyCode::Char('m'),
        KeyModifiers::CONTROL
    )));
    assert!(!is_show_output_key(key(
        KeyCode::Char('u'),
        KeyModifiers::CONTROL
    )));
    // Cmd+Opt+Shift+U is Transform to Uppercase, not OUTPUT.
    assert!(!is_show_output_key(key(
        KeyCode::Char('U'),
        cmd_shift | KeyModifiers::ALT
    )));
}

/// #852: Output: Select Channel… is the OUTPUT toolbar's click-only channel
/// dropdown as a keyboard picker; choosing a row shows that channel.
#[test]
fn output_select_channel_picks_a_channel_from_the_keyboard() {
    use crate::widgets::command_palette::Command;
    use crate::widgets::list_picker::ListPurpose;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // The bus is process-wide, so the channel carries a name no other test
    // uses and the picker is narrowed to it.
    let channel = "Keyboard Reach 852";
    crate::output::push(channel, crate::output::OutputLevel::Info, "hello");
    app.run_command(Command::OutputSelectChannel);
    let picker = app.list_picker.as_mut().expect("the channel picker opens");
    assert_eq!(picker.purpose, ListPurpose::OutputChannel);
    for c in "reach 852".chars() {
        picker.push_char(c);
    }
    assert_eq!(picker.visible_count(), 1);
    app.confirm_list_picker();
    assert_eq!(app.bottom_panel_tab, BottomPanelTab::Output);
    assert!(app.focus == Pane::Terminal);
    assert_eq!(app.output.selected_name().as_deref(), Some(channel));
}

/// #2848: OUTPUT draws a scrollbar once its log outgrows the panel, and the
/// bar answers the mouse as every other one does: a press on the track
/// jumps the log there, and dragging the thumb keeps it under the pointer.
#[test]
fn pressing_and_dragging_the_output_scrollbar_scrolls_the_log() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // The bus is process-wide, so the channel carries a name no other test
    // uses.
    let channel = "Scrollbar Drag 2848";
    for i in 0..200 {
        crate::output::push(
            channel,
            crate::output::OutputLevel::Info,
            &format!("log line {i:03}"),
        );
    }
    app.output.sync();
    assert!(app.output.select_by_name(channel));
    app.bottom_panel_tab = BottomPanelTab::Output;

    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let bar = app.output.last_scrollbar;
    assert!(
        bar.width > 0 && bar.height > 2,
        "200 log lines in the panel must draw a scrollbar"
    );
    let left = app.output.last_area.x;
    let top_row = |term: &ratatui::Terminal<ratatui::backend::TestBackend>| {
        let buf = term.backend().buffer();
        (left..bar.x)
            .map(|x| buf[(x, bar.y)].symbol())
            .collect::<String>()
    };
    // The log follows its tail, so it opens on its last lines.
    let opened = top_row(&term);
    assert!(
        opened.contains("log line") && !opened.contains("log line 000"),
        "the log opens on its tail: {opened:?}"
    );

    // A press at the track's top jumps the log to its first line.
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), bar.x, bar.y));
    term.draw(|f| app.render(f)).unwrap();
    let jumped = top_row(&term);
    assert!(
        jumped.contains("log line 000"),
        "a press on the scrollbar's top must jump the log to its start: {jumped:?}"
    );

    // Dragging the thumb to the track's foot follows the pointer back down.
    app.handle_mouse(mouse(
        MouseEventKind::Drag(MouseButton::Left),
        bar.x,
        bar.y + bar.height - 1,
    ));
    term.draw(|f| app.render(f)).unwrap();
    assert_eq!(
        top_row(&term),
        opened,
        "dragging the thumb to the track's foot must bring the tail back"
    );
    app.handle_mouse(mouse(
        MouseEventKind::Up(MouseButton::Left),
        bar.x,
        bar.y + bar.height - 1,
    ));
    assert!(app.gesture.is_none(), "the release ends the drag");
}

/// #2848: the channel list OUTPUT opens over its log can reach the
/// scrollbar's column, so while the list is open a press there is the
/// list's (it closes, or picks the row under it), never a scrollbar drag.
#[test]
fn a_press_on_the_output_scrollbar_with_the_channel_list_open_is_the_lists() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // The bus is process-wide, so the channel carries a name no other test
    // uses.
    let channel = "Scrollbar Under List 2848";
    for i in 0..200 {
        crate::output::push(
            channel,
            crate::output::OutputLevel::Info,
            &format!("log line {i:03}"),
        );
    }
    app.output.sync();
    assert!(app.output.select_by_name(channel));
    app.bottom_panel_tab = BottomPanelTab::Output;

    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let bar = app.output.last_scrollbar;
    assert!(bar.width > 0 && bar.height > 2, "the log draws a scrollbar");
    // The toolbar's channel button shows the channel's name; a click on it
    // opens the list.
    let area = app.output.last_area;
    let toolbar: String = {
        let buf = term.backend().buffer();
        (area.x..area.x + area.width)
            .map(|x| buf[(x, area.y)].symbol())
            .collect()
    };
    let at = toolbar
        .find(channel)
        .expect("the toolbar names the shown channel");
    let button_x = area.x + toolbar[..at].chars().count() as u16;
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Left),
        button_x,
        area.y,
    ));
    app.handle_mouse(mouse(
        MouseEventKind::Up(MouseButton::Left),
        button_x,
        area.y,
    ));
    assert!(
        app.output.dropdown_open(),
        "the channel button opens the list"
    );
    term.draw(|f| app.render(f)).unwrap();

    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), bar.x, bar.y));
    assert!(
        !app.output.dropdown_open(),
        "a press on the bar's column while the list is open is the list's"
    );
    assert!(app.gesture.is_none(), "and does not start a scrollbar drag");
    app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), bar.x, bar.y));
}

/// #852 regression, driven by keys alone: from the editor with the panel
/// hidden, `Ctrl+Shift+M` shows PROBLEMS, `Ctrl+Shift+U` shows OUTPUT and
/// `Cmd+Shift+T` brings TERMINAL back over them, each time with the panel
/// shown and focused.
#[test]
fn panel_tab_chords_reach_problems_output_and_terminal_by_key() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let ctrl_shift = KeyModifiers::CONTROL | KeyModifiers::SHIFT;
    let cmd_shift = KeyModifiers::SUPER | KeyModifiers::SHIFT;
    app.show_terminal = false;
    app.bottom_panel_tab = BottomPanelTab::Terminal;
    app.focus_pane(Pane::Editor);
    app.handle_key(key(KeyCode::Char('M'), ctrl_shift)).unwrap();
    assert_eq!(
        app.bottom_panel_tab,
        BottomPanelTab::Problems,
        "Ctrl+Shift+M must show PROBLEMS"
    );
    assert!(app.show_terminal, "Ctrl+Shift+M must reveal the panel");
    assert!(app.focus == Pane::Terminal);
    app.handle_key(key(KeyCode::Char('U'), ctrl_shift)).unwrap();
    assert_eq!(
        app.bottom_panel_tab,
        BottomPanelTab::Output,
        "Ctrl+Shift+U must show OUTPUT"
    );
    app.handle_key(key(KeyCode::Char('T'), cmd_shift)).unwrap();
    assert_eq!(
        app.bottom_panel_tab,
        BottomPanelTab::Terminal,
        "Cmd+Shift+T must bring TERMINAL forward"
    );
    assert!(app.focus == Pane::Terminal);
}

/// #852 (comment 2): the Customize Layout popup opens from the keyboard.
/// Typing its name in the palette and pressing Enter shows the popup with
/// its rows, where before the palette said "No commands match".
#[test]
fn typing_customize_layout_in_the_palette_opens_the_popup() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    open_palette_852(&mut app);
    type_keys(&mut app, "customize layout");
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    let menu = app
        .context_menu
        .as_ref()
        .expect("View: Customize Layout… opens the Customize Layout popup");
    assert!(
        menu.items.iter().any(|e| matches!(
            e,
            MenuEntry::Item {
                action: MenuAction::ToggleStatusBar,
                ..
            }
        )),
        "the popup is the Customize Layout one"
    );
}

/// #852 guard: no Customize Layout row ships mouse-only. Every row names
/// the palette command that reaches it (a new row fails here until it has
/// one), the command is in the palette and found by "layout", and running
/// it (choosing the row's option where it opens a picker) lands on the
/// state the row's click sets, from a state where that option is not yet
/// the active one.
#[test]
fn every_customize_layout_row_has_a_palette_command_that_does_the_same() {
    use crate::command_registry::{ALL_COMMANDS, Command, LAYOUT_COMMANDS};
    fn command_for(action: &MenuAction) -> Option<Command> {
        match action {
            MenuAction::ToggleActivityBar => Some(Command::ToggleActivityBar),
            MenuAction::ToggleSideBar => Some(Command::ToggleSideBar),
            MenuAction::ToggleSecondarySideBar => Some(Command::ToggleSecondarySideBar),
            MenuAction::TogglePanel => Some(Command::ToggleTerminal),
            MenuAction::ToggleStatusBar => Some(Command::ToggleStatusBar),
            MenuAction::ToggleMinimap => Some(Command::ToggleMinimap),
            MenuAction::ToggleAutoHideSideBar => Some(Command::ToggleAutoHideSideBar),
            MenuAction::SetSideBarPosition(_) => Some(Command::ToggleSideBarPosition),
            MenuAction::SetPanelAlignment(_) => Some(Command::SetPanelAlignment),
            MenuAction::SetQuickInputPosition(_) => Some(Command::SetQuickInputPosition),
            MenuAction::ToggleZenMode => Some(Command::ToggleZenMode),
            MenuAction::ToggleCenteredLayout => Some(Command::ToggleCenteredLayout),
            _ => None,
        }
    }
    // A radio row's setting moved off the row's option first.
    fn off_option(app: &mut App, action: &MenuAction) {
        match *action {
            MenuAction::SetSideBarPosition(p) => {
                app.side_bar_position = if p == SideBarPosition::Left {
                    SideBarPosition::Right
                } else {
                    SideBarPosition::Left
                };
            }
            MenuAction::SetPanelAlignment(al) => {
                app.panel_alignment = if al == PanelAlignment::Left {
                    PanelAlignment::Center
                } else {
                    PanelAlignment::Left
                };
            }
            MenuAction::SetQuickInputPosition(p) => {
                app.quick_input_position = if p == QuickInputPosition::Top {
                    QuickInputPosition::Center
                } else {
                    QuickInputPosition::Top
                };
            }
            _ => {}
        }
    }
    let snapshot = |app: &App| {
        (
            app.activity_bar_visible,
            app.show_tree,
            app.secondary_side_bar_visible,
            app.show_terminal,
            app.status_bar_visible,
            app.minimap.visible,
            app.sidebar_auto_hide,
            app.side_bar_position,
            app.panel_alignment,
            app.quick_input_position,
            app.zen_mode(),
            app.centered_layout,
        )
    };
    let tmp = tempfile::tempdir().unwrap();
    let rows: Vec<(String, MenuAction)> = App::new(tmp.path().to_path_buf())
        .unwrap()
        .customize_layout_items()
        .into_iter()
        .filter_map(|e| match e {
            MenuEntry::Item { label, action } => Some((label, action)),
            _ => None,
        })
        .collect();
    assert!(rows.len() >= 12, "the popup's rows: {rows:?}");
    for (label, action) in rows {
        let cmd = command_for(&action)
            .unwrap_or_else(|| panic!("Customize Layout row {label:?} has no palette command"));
        assert!(ALL_COMMANDS.contains(&cmd), "{cmd:?} is not in the palette");
        assert!(
            LAYOUT_COMMANDS.contains(&cmd),
            "{cmd:?} is not found by the query \"layout\""
        );
        let mut by_click = App::new(tmp.path().to_path_buf()).unwrap();
        let mut by_palette = App::new(tmp.path().to_path_buf()).unwrap();
        off_option(&mut by_click, &action);
        off_option(&mut by_palette, &action);
        assert_eq!(snapshot(&by_click), snapshot(&by_palette), "fixture");
        by_click.dispatch_menu_action(action.clone(), tmp.path().to_path_buf());
        by_palette.run_command(cmd);
        if let Some(picker) = by_palette.list_picker.as_mut() {
            let option = label.trim_start_matches('\u{2713}').trim().to_lowercase();
            for c in option.chars() {
                picker.push_char(c);
            }
            assert_eq!(picker.visible_count(), 1, "{cmd:?} offers {option:?}");
            by_palette.confirm_list_picker();
        }
        assert_eq!(
            snapshot(&by_palette),
            snapshot(&by_click),
            "{cmd:?} must do what the row {label:?} does"
        );
    }
}

/// #852 negative: the alignment picker opens on the current alignment and
/// Esc leaves it unchanged; only a chosen row changes it.
#[test]
fn dismissing_the_panel_alignment_picker_keeps_the_alignment() {
    use crate::widgets::command_palette::Command;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.panel_alignment = PanelAlignment::Right;
    app.run_command(Command::SetPanelAlignment);
    let picker = app.list_picker.as_ref().expect("the picker opens");
    assert_eq!(
        picker.selected_row().map(|r| r.id.as_str()),
        Some("right"),
        "the picker opens on the current alignment"
    );
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    assert!(app.list_picker.is_none());
    assert_eq!(app.panel_alignment, PanelAlignment::Right);
}

/// #2068: the row under the mouse in PROBLEMS, OUTPUT, PORTS and CAPTURES
/// lights up on every move and goes dark when the pointer leaves, as in the
/// side bar. These panels read a pointer copied in only at focus changes, so
/// the highlight stuck on whatever row the pointer was over then; they now
/// draw with the frame's pointer, all four through one context, so this
/// checks the one whose rows show it without fixtures, PORTS.
#[test]
fn bottom_panel_hover_follows_the_pointer() {
    use crate::widgets::ports::PortOrigin;
    use crossterm::event::MouseEventKind;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    // What the user sees: PORTS fills the row under the pointer, and no other
    // row but the selected one, with the selected row's colour. Rows two and
    // three, clear of the selected first row.
    for port in [3000, 3001, 3002] {
        app.ports
            .upsert(port, None, None, PortOrigin::Remote("box".into()));
    }
    app.bottom_panel_tab = BottomPanelTab::Ports;
    draw(&mut app, 140, 50);
    let area = app.ports.last_area;
    let (x, second, third) = (area.x + 2, area.y + 2, area.y + 3);
    let lift = crate::gradient::rgb_color(crate::gradient::POPUP_SEL_BG);
    let lit = |app: &mut App, at: Option<(u16, u16)>| {
        if let Some((px, py)) = at {
            app.handle_mouse(mouse(MouseEventKind::Moved, px, py));
        }
        let buf = draw_buffer(app, 140, 50);
        (buf[(x, second)].bg == lift, buf[(x, third)].bg == lift)
    };
    assert_eq!(lit(&mut app, Some((x, second))), (true, false));
    assert_eq!(
        lit(&mut app, Some((x, third))),
        (false, true),
        "the lift follows the pointer"
    );
    assert_eq!(
        lit(&mut app, Some((x, 2))),
        (false, false),
        "and leaves with it"
    );
}

/// #2068: with the secondary side bar open, the Explorer's own OUTLINE
/// section shows the Explorer's focus: its scrollbar thumb takes the focused
/// colour while the Explorer has the keyboard and the plain one after. The
/// secondary bar drew its Outline unfocused by clearing a flag both shared,
/// every frame, and never put it back; each now draws with its own context.
#[test]
fn the_secondary_side_bar_leaves_the_explorer_outline_s_focus_alone() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, _) = secondary_outline_app(&tmp, 120);
    app.set_sidebar_view(SidebarView::Explorer);
    let focused = app.theme.scrollbar_thumb_focused();
    let thumb_lit = |app: &mut App| {
        let buf = draw_buffer(app, 140, 40);
        let bar = app.outline.last_scrollbar;
        assert!(bar.height > 0, "the Explorer's OUTLINE scrolls");
        (bar.y..bar.bottom()).any(|y| buf[(bar.x, y)].bg == focused)
    };
    assert!(thumb_lit(&mut app), "the Explorer has focus");
    app.focus_pane(Pane::Editor);
    assert!(!thumb_lit(&mut app), "and then it does not");
}

/// #2062: the activity-bar table keeps every view icon where it was: the
/// stack starts one row below the bar's top, one icon height apart, with
/// Run and Debug above Remote and CodeQL last. The table's draw order is
/// also the order its blocks are stored in, so looking up an icon's block
/// finds that icon's.
#[test]
fn the_activity_bar_table_keeps_each_icon_in_its_place() {
    use ratatui::layout::Rect;
    let bar = Rect::new(0, 3, ACTIVITY_BAR_WIDTH, 40);
    let tops: Vec<(ActivityIcon, u16)> = ActivityIcon::ALL
        .into_iter()
        .filter_map(|icon| {
            icon.slot()
                .map(|slot| (icon, activity_view_block(bar, slot).y))
        })
        .collect();
    assert_eq!(
        tops,
        vec![
            (ActivityIcon::Explorer, 4),
            (ActivityIcon::Search, 6),
            (ActivityIcon::SourceControl, 8),
            (ActivityIcon::Remote, 12),
            (ActivityIcon::RunDebug, 10),
            (ActivityIcon::Extensions, 14),
            (ActivityIcon::Testing, 16),
            (ActivityIcon::CodeQL, 18),
        ]
    );
    for (index, icon) in ActivityIcon::ALL.into_iter().enumerate() {
        assert_eq!(icon as usize, index, "{icon:?} is stored where it is drawn");
    }
}

/// #2062: hovering each icon's block finds that icon, and its tooltip names
/// it as before.
#[test]
fn every_activity_icon_is_found_under_the_pointer_and_named() {
    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 names: Vec<(ActivityIcon, &str)> = ActivityIcon::ALL
        .into_iter()
        .filter(|&icon| app.sidebar_areas.activity_icons[icon].width > 0)
        .map(|icon| {
            let block = app.sidebar_areas.activity_icons[icon];
            assert_eq!(app.activity_icon_at(block.x, block.y), Some(icon));
            (icon, icon.label())
        })
        .collect();
    assert_eq!(
        names,
        vec![
            (ActivityIcon::Explorer, "Explorer"),
            (ActivityIcon::Search, "Search"),
            (ActivityIcon::SourceControl, "Source Control"),
            (ActivityIcon::Remote, "Remote"),
            (ActivityIcon::RunDebug, "Run and Debug"),
            (ActivityIcon::Extensions, "Extensions"),
            (ActivityIcon::Testing, "Testing"),
            (ActivityIcon::Sponsor, "Sponsor croft"),
            (ActivityIcon::Settings, "Manage"),
        ],
        "CodeQL is not added by default, so it has no block"
    );
}

/// #2062: one count-badge type serves every activity-bar badge. It is built
/// again only when its count changes (or after the pictures were baked
/// again), it clears at zero, it only tracks the count where pictures are
/// off, and it sits on its icon's bottom-right cells, as wide as the count.
#[test]
fn an_activity_badge_is_built_again_only_when_its_count_changes() {
    use ratatui::layout::Rect;
    let mut badge = CountBadge::default();
    let builds = std::cell::Cell::new(0);
    let build = |n: usize| {
        builds.set(builds.get() + 1);
        Some(format!("BADGE{n}"))
    };
    assert!(
        badge.refresh(3, true, || build(3)),
        "a new count changes it"
    );
    assert!(
        !badge.refresh(3, true, || build(3)),
        "the same count does not"
    );
    assert_eq!(builds.get(), 1, "and is not built again");
    let icon = Rect::new(0, 4, 4, 2);
    let width = crate::iterm2_inline::count_badge_cells_w;
    assert_eq!(
        badge.placed(icon),
        Some((Rect::new(4 - width(3), 5, width(3), 1), "BADGE3")),
        "on the icon's bottom row, against its right edge"
    );
    assert!(badge.refresh(12, true, || build(12)));
    assert_eq!(
        badge.placed(icon),
        Some((Rect::new(4 - width(12), 5, width(12), 1), "BADGE12")),
        "as wide as the count needs"
    );
    badge.invalidate();
    assert!(
        badge.refresh(12, true, || build(12)),
        "new pictures rebuild it"
    );
    assert_eq!(builds.get(), 3);
    assert!(badge.refresh(0, true, || build(0)), "zero changes it");
    assert_eq!(badge.placed(icon), None, "and clears the picture");
    assert_eq!(builds.get(), 3, "without building one");
    assert!(
        badge.refresh(5, false, || build(5)),
        "without pictures the count still changes"
    );
    assert_eq!(badge.placed(icon), None, "but no picture is built");
    assert_eq!(builds.get(), 3);
}

/// #2062: a count badge goes out as a picture over its icon's bottom-right
/// cells, after every icon, so it is drawn on top. Here the Explorer's
/// unsaved-file badge, built as a Kitty picture with the badge's own id.
#[test]
fn the_explorer_badge_goes_out_over_its_icon_after_every_icon() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.txt");
    std::fs::write(&a, "aaa").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.auto_save = false;
    app.auto_save_on_focus_change = false;
    app.format_on_save = false;
    app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::Kitty;
    app.cell_pixel = Some((8, 16));
    app.overlays.activity.set_images(empty_activity_images());
    app.editor.open_pinned(&a).unwrap();
    app.focus_pane(Pane::Editor);
    app.handle_key(key(KeyCode::Char('X'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.unsaved_count(), 1);
    draw(&mut app, 120, 40);
    let sent = app.pending_activity_image_overlays();
    let explorer = app.sidebar_areas.activity_icons[ActivityIcon::Explorer];
    let width = crate::iterm2_inline::count_badge_cells_w(1);
    let corner = (
        explorer.x + explorer.width - width,
        explorer.y + explorer.height - 1,
    );
    let badge_at = sent
        .iter()
        .position(|(at, _)| *at == corner)
        .expect("the badge goes out at the Explorer icon's bottom-right");
    let shown_icons = ActivityIcon::ALL
        .into_iter()
        .filter(|&icon| app.sidebar_areas.activity_icons[icon].width > 0)
        .count();
    assert!(
        badge_at >= shown_icons,
        "after every icon: {badge_at} of {sent:?}"
    );
    let id = crate::iterm2_inline::KITTY_ID_EXPLORER_BADGE;
    assert!(
        sent[badge_at].1.contains(&format!("i={id}")),
        "built with the Explorer badge's own picture id"
    );
}