croft-software 0.2.82

VSCode-style TUI written in Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
use alacritty_terminal::Term;
use alacritty_terminal::event::{Event as AlacEvent, EventListener};
use alacritty_terminal::grid::{Dimensions, Scroll};
use alacritty_terminal::index::{Column, Line, Point, Side};
use alacritty_terminal::selection::{Selection as TracerSelection, SelectionType};
use alacritty_terminal::sync::FairMutex;
use alacritty_terminal::term::ClipboardType;
use alacritty_terminal::term::cell::Flags;
use alacritty_terminal::term::test::TermSize;
use alacritty_terminal::term::{Config, TermMode};
use alacritty_terminal::vte::ansi::{Color as AnsiColor, NamedColor, Processor, StdSyncHandler};
use anyhow::{Context, Result};
use portable_pty::{CommandBuilder, MasterPty, PtySize, native_pty_system};
use ratatui::{
    buffer::Buffer,
    layout::Rect,
    style::{Color, Modifier, Style},
    widgets::{Block, Borders, Widget},
};
use std::io::{Read, Write};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};

const SCROLLBACK_LINES: usize = 5000;

/// A mouse button (or wheel direction) to forward to the child program
/// when it has mouse tracking enabled. Encoded as an SGR (1006) report when
/// the child selected that encoding, otherwise as a legacy X10 report.
#[derive(Clone, Copy, PartialEq)]
pub enum MouseButtonKind {
    Left,
    Middle,
    Right,
    WheelUp,
    WheelDown,
}

/// What happened to the button: a press, a release, or motion while held.
#[derive(Clone, Copy, PartialEq)]
pub enum MouseAction {
    Press,
    Release,
    Motion,
}

/// Keyboard modifiers held during a mouse event, folded into the report's
/// button byte (Shift +4, Alt +8, Ctrl +16).
#[derive(Clone, Copy, Default)]
pub struct MouseMods {
    pub shift: bool,
    pub alt: bool,
    pub ctrl: bool,
}

/// A terminal text selection, anchored to *absolute* alacritty grid lines
/// rather than viewport rows. `line` is the grid `Line` index: `0..rows`
/// is the live screen, negative values are scrollback history. Storing
/// absolute lines (instead of `row - inner.y`) is what lets a selection
/// be taller than the visible pane and survive scrolling — the highlight
/// and the extracted text both track content, not screen position.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Selection {
    pub anchor: (i32, u16),
    pub head: (i32, u16),
    /// Rectangular (column-block) selection: the highlight and the copied
    /// text cover the same column slice on every row between the endpoints
    /// (copy mode's Ctrl+V), instead of running row-major to the ends.
    pub block: bool,
}

/// What an alternate-screen selection remembers about its content so the
/// highlight can follow text that the app moves by repainting (alt-screen
/// programs own scrolling: the grid never scrolls, cells just change).
/// After every repaint the selection re-finds these rows in the grid and
/// shifts itself to them; while they are nowhere in view it goes `dormant`
/// — hidden, coordinates frozen — and reappears when the app scrolls the
/// content back.
struct AltSelAnchor {
    /// Full row text of every selected grid line at last sight, top to
    /// bottom. Rows the shift math placed outside the grid stay remembered
    /// so the block can re-anchor when they scroll back in.
    rows: Vec<String>,
    /// Grid line `rows[0]` was last seen at. Drift is measured against
    /// THIS, never against the selection's own top: mid-drag the selection
    /// top is the pointer (the head), not the anchored content, and
    /// deriving drift from it walked the anchor one row per mouse event on
    /// upward drags.
    top: i32,
    /// The extracted selection text at last sight: what copy yields while
    /// the content is scrolled out of view.
    text: String,
    /// The rows are nowhere in the grid right now: paint nothing, keep the
    /// coordinates frozen until the content reappears.
    dormant: bool,
    /// The rows (and column spans) that actually survive on screen when
    /// the block is only partially visible — the rest is off the grid or
    /// overdrawn by app chrome (Claude Code's input box, its floating
    /// "Jump to bottom" pill). Each entry is `(grid line, first column,
    /// last column)`: a row half-covered by a pill keeps its surviving
    /// prefix/suffix highlighted. Painting clips to these; `None` while
    /// the whole block is visible.
    visible: Option<Vec<(i32, u16, u16)>>,
    /// Row text just above / below the block at capture time (`None` at a
    /// grid edge). Pure tie-breakers for re-anchoring: full-screen apps
    /// repeat rows verbatim (divider rules, continuation markers), so a
    /// selection whose own fingerprint matches several shifts equally —
    /// inevitably a one-row selection on such a row — follows the copy
    /// whose neighbours also match instead of the nearest lookalike.
    ctx_above: Option<String>,
    ctx_below: Option<String>,
}

impl Selection {
    pub fn new(line: i32, col: u16) -> Self {
        Self {
            anchor: (line, col),
            head: (line, col),
            block: false,
        }
    }
    pub fn normalised(&self) -> (i32, u16, i32, u16) {
        let (a_l, a_c) = self.anchor;
        let (b_l, b_c) = self.head;
        if (a_l, a_c) <= (b_l, b_c) {
            (a_l, a_c, b_l, b_c)
        } else {
            (b_l, b_c, a_l, a_c)
        }
    }
    /// Rectangle bounds with rows and columns min/maxed independently
    /// (row-major normalisation would pair the wrong corners when the head
    /// sits below-left of the anchor): (row_lo, col_lo, row_hi, col_hi).
    pub fn block_bounds(&self) -> (i32, u16, i32, u16) {
        let (a_l, a_c) = self.anchor;
        let (b_l, b_c) = self.head;
        (a_l.min(b_l), a_c.min(b_c), a_l.max(b_l), a_c.max(b_c))
    }
    pub fn has_area(&self) -> bool {
        self.anchor != self.head
    }
}

/// Listener for events the embedded `Term` emits. Most variants (title
/// changes, cursor-blink toggles, clipboard load, child exit, etc.)
/// are owned by the outer croft TUI and ignored here. A clipboard STORE
/// (OSC 52 copy) is latched for the app to deliver (#678). Two more
/// MUST be reflected back into the shell's stdin or interactive TUIs
/// running inside the embedded terminal hang waiting for replies:
///
///   * `PtyWrite(text)` — DSR (`ESC[6n`), DA1/DA2 (`ESC[c`, `ESC[>c`),
///     keyboard modifier reports, sixel/synchronised-output queries,
///     and OSC 52 read backs all surface here. atuin times out with
///     "The cursor position could not be read within a normal duration"
///     when the DSR reply never lands on the PTY; helix, fzf, btop and
///     other Rust/Go TUIs do the same.
///   * `TextAreaSizeRequest(cb)` — `CSI 14 t` / `CSI 18 t` pixel/cell
///     size queries from TUIs that scale glyph cells (e.g. helix's
///     terminal-size detection, sixel-aware viewers). The callback
///     builds the reply string from the supplied `WindowSize`.
///
/// In tests we use `VoidListener::default()` (both channels `None`) so
/// the listener silently drops every event — the test helpers exercise
/// the parser, not the round-trip.
#[derive(Clone, Default)]
pub struct VoidListener {
    pty_response_tx: Option<std::sync::mpsc::Sender<String>>,
    size: Option<Arc<std::sync::Mutex<(u16, u16)>>>,
    /// Latched when the child rings BEL (`\a`); the app drains it via
    /// [`PtyTerminal::take_bell`] to surface the bell in the UI.
    bell: Option<Arc<AtomicBool>>,
    /// The newest OSC 52 clipboard store from the child (#678); drained by
    /// [`PtyTerminal::take_clipboard_store`].
    clipboard: Option<Arc<std::sync::Mutex<Option<String>>>>,
}

impl EventListener for VoidListener {
    fn send_event(&self, event: AlacEvent) {
        match event {
            AlacEvent::Bell => {
                if let Some(bell) = self.bell.as_ref() {
                    bell.store(true, Ordering::Release);
                }
            }
            // A program copying through OSC 52: Claude Code, tmux, nvim.
            // Over SSH it is their ONLY way to copy (a remote box has no
            // clipboard tool), so dropping it broke copy on a remote while
            // the same program copied fine locally through pbcopy (#678).
            // Only the clipboard, never the primary selection: X's
            // select-to-copy buffer has no counterpart on the user's side,
            // and writing it into the clipboard would clobber real copies.
            AlacEvent::ClipboardStore(ClipboardType::Clipboard, text) => {
                if let Some(clip) = self.clipboard.as_ref() {
                    *clip.lock().unwrap() = Some(text);
                }
            }
            AlacEvent::PtyWrite(text) => {
                if let Some(tx) = self.pty_response_tx.as_ref() {
                    let _ = tx.send(text);
                }
            }
            AlacEvent::TextAreaSizeRequest(cb) => {
                let (Some(tx), Some(size)) = (self.pty_response_tx.as_ref(), self.size.as_ref())
                else {
                    return;
                };
                let (cols, rows) = *size.lock().unwrap();
                let ws = alacritty_terminal::event::WindowSize {
                    num_lines: rows,
                    num_cols: cols,
                    cell_width: 1,
                    cell_height: 1,
                };
                let _ = tx.send(cb(ws));
            }
            _ => {}
        }
    }
}

/// A row arriving this long after its predecessor is highlighted amber in
/// the timestamps gutter (the "where did the deploy stall" signal).
const STALL_GAP_MS: u64 = 60_000;

/// The pane's monotonic scroll clock: lines the primary screen has
/// scrolled since the pane spawned, read from a one-cell tracer selection's
/// drift. Immune to the `history_size` saturation that froze selections in
/// long-lived panes (scrollback full for ages, so a history-growth delta
/// was pinned at zero while content kept rotating through the ring). Alt
/// screen freezes the clock — output goes to the alternate grid while
/// primary content holds still. A dead tracer falls back to history growth
/// since the last tick: exact for the viewport-pushing clear that killed
/// it, zero for an alt-screen round trip.
///
/// Shared (behind a mutex) between the render thread — selection,
/// copy-mode, and annotation re-anchoring — and the PTY reader thread,
/// which keys arrival timestamps on it. Lock order everywhere:
/// term → clock → line_times; the term lock is held across the whole
/// sequence on both threads, and the inner two always nest in that order.
#[derive(Clone, Debug)]
struct ScrollClock {
    /// Monotonic reading, folded up to the last `tick`.
    base: i64,
    /// Grid line the tracer selection was planted at during the last tick;
    /// `None` before the first tick.
    planted: Option<i32>,
    /// `history_size` at the last tick: fallback delta source for the rare
    /// windows where the tracer died (screen clear, alt-screen round trip).
    hist: i64,
}

impl ScrollClock {
    fn new() -> Self {
        Self {
            base: 0,
            planted: None,
            hist: 0,
        }
    }

    /// Plant the one-cell tracer selection at `line` in alacritty's own
    /// `Term::selection` slot (croft paints selections itself, so the slot
    /// is otherwise unused). alacritty rotates it on every scroll —
    /// including ring rotation once the scrollback is full, where
    /// `history_size` saturates and stops counting — so its drift between
    /// ticks is the true lines-scrolled count.
    fn plant_tracer(term: &mut Term<VoidListener>, line: i32) {
        let point = Point::new(Line(line), Column(0));
        let mut tracer = TracerSelection::new(SelectionType::Simple, point, Side::Left);
        tracer.update(point, Side::Right);
        term.selection = Some(tracer);
    }

    /// Where the tracer sits now, when it survived since the last plant
    /// (screen clears, alt-screen swaps and content rotating fully off the
    /// scrollback kill it).
    fn tracer_line(term: &Term<VoidListener>) -> Option<i32> {
        let range = term.selection.as_ref()?.to_range(term)?;
        Some(range.start.line.0)
    }

    fn now(&self, term: &Term<VoidListener>) -> i64 {
        if term.mode().contains(TermMode::ALT_SCREEN) {
            return self.base;
        }
        match (self.planted, Self::tracer_line(term)) {
            (Some(planted), Some(cur)) => self.base + i64::from(planted - cur),
            _ => {
                let growth = term.grid().history_size() as i64 - self.hist;
                self.base + growth.max(0)
            }
        }
    }

    /// Fold the tracer's drift into the clock, re-plant it fresh and return
    /// the folded reading. The newest history line is the parking spot:
    /// application clears only touch live-screen rows, so nothing kills it
    /// there, and it sits a full scrollback's depth from rotating off the
    /// top before the next tick (every rendered frame ticks).
    fn tick(&mut self, term: &mut Term<VoidListener>) -> i64 {
        let now = self.now(term);
        if !term.mode().contains(TermMode::ALT_SCREEN) {
            self.base = now;
            self.hist = term.grid().history_size() as i64;
            let park = if self.hist > 0 { -1 } else { 0 };
            Self::plant_tracer(term, park);
            self.planted = Some(park);
        }
        now
    }
}

/// One PTY chunk's arrival stamps for the timestamps gutter: every row the
/// cursor advanced past gets the chunk's arrival time, keyed on the scroll
/// clock (`clock reading + cursor grid line` = a stable content id) — NOT
/// on `history_size`, which treated any upward cursor motion as a
/// scrollback wipe (a `docker pull` progress redraw erased every stamp, an
/// alt-screen round trip erased them and then re-stamped the whole
/// scrollback with the exit time) and which saturates once the ring fills,
/// freezing ids to screen positions. Alternate-screen output stamps
/// nothing: it isn't scrollback rows, and the gutter is normal-screen only.
/// Destructive-clear detector over the raw PTY byte stream: ED 2
/// (`\x1b[2J`, erases the live screen), ED 3 (`\x1b[3J`, erases the
/// scrollback) and RIS (`\x1bc`, both). Keyed on the bytes rather than on
/// `history_size` movement, which is 0 → 0 when nothing has scrolled into
/// history yet. The scan is POSITIONAL: it tracks alt-screen entry/exit
/// (DECSET/DECRST 47/1047/1049) through the stream, so a wipe counts only
/// where it landed — `clear && vim` wipes the primary screen even though
/// the same chunk ends inside the alt screen. An unterminated trailing
/// sequence (bounded) carries to the next read; consumed bytes are never
/// rescanned, which keeps the alt tracking single-shot.
#[derive(Default)]
struct WipeSniffer {
    carry: Vec<u8>,
}

/// Longest carried partial sequence; a real DECSET list or ED is far
/// shorter, and the bound stops a hostile unterminated CSI from growing.
const WIPE_CARRY_MAX: usize = 64;

/// One destructive clear [`WipeSniffer::scan`] found: the chunk offset just
/// past its last byte, and whether it erased the primary screen (ED 2),
/// the scrollback (ED 3) or both (RIS).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Wipe {
    end: usize,
    screen: bool,
    hist: bool,
}

impl WipeSniffer {
    /// Scan one chunk. `alt` is the terminal's alt-screen state where the
    /// chunk STARTS. Returns the primary-screen wipes in it, in order.
    fn scan(&mut self, chunk: &[u8], mut alt: bool) -> Vec<Wipe> {
        let mut data = std::mem::take(&mut self.carry);
        // Offsets into `data` are reported against `chunk`: a sequence
        // carried from the last read ends in this one, never before it.
        let carried = data.len();
        data.extend_from_slice(chunk);
        let mut wipes = Vec::new();
        let mut wipe = |end: usize, screen: bool, hist: bool| {
            let end = end.saturating_sub(carried);
            wipes.push(Wipe { end, screen, hist });
        };
        let mut i = 0;
        while i < data.len() {
            if data[i] != 0x1b {
                i += 1;
                continue;
            }
            let Some(&next) = data.get(i + 1) else {
                self.carry = data.split_off(i);
                return wipes;
            };
            match next {
                // RIS: full reset — everything is gone, back on primary.
                b'c' => {
                    wipe(i + 2, true, true);
                    alt = false;
                    i += 2;
                }
                b'[' => {
                    let mut j = i + 2;
                    while j < data.len()
                        && !(0x40..=0x7e).contains(&data[j])
                        && !matches!(data[j], 0x18 | 0x1a | 0x1b)
                    {
                        j += 1;
                    }
                    if j >= data.len() {
                        if data.len() - i <= WIPE_CARRY_MAX {
                            self.carry = data.split_off(i);
                        }
                        return wipes;
                    }
                    // CAN/SUB cancel the sequence and an ESC inside an
                    // incomplete CSI begins a NEW escape (VT100) — none may
                    // be swallowed as a parameter, or whatever follows a
                    // cancelled CSI goes unseen.
                    if matches!(data[j], 0x18 | 0x1a | 0x1b) {
                        i = if data[j] == 0x1b { j } else { j + 1 };
                        continue;
                    }
                    let params = &data[i + 2..j];
                    match data[j] {
                        b'J' if params == b"2" && !alt => wipe(j + 1, true, false),
                        b'J' if params == b"3" && !alt => wipe(j + 1, false, true),
                        fin @ (b'h' | b'l') if params.first() == Some(&b'?') => {
                            for p in params[1..].split(|&c| c == b';') {
                                if p == b"47" || p == b"1047" || p == b"1049" {
                                    alt = fin == b'h';
                                }
                            }
                        }
                        _ => {}
                    }
                    i = j + 1;
                }
                _ => i += 2,
            }
        }
        wipes
    }
}

fn stamp_chunk(
    term: &mut Term<VoidListener>,
    clock: &mut ScrollClock,
    lt: &mut std::collections::BTreeMap<i64, u64>,
    prev_id: &mut i64,
    now_ms: u64,
) {
    if term.mode().contains(TermMode::ALT_SCREEN) {
        return;
    }
    let now = clock.tick(term);
    let cur_id = now + i64::from(term.grid().cursor.point.line.0);
    // Stamp from the PREVIOUS cursor row inclusive (last touch wins: the
    // row content just landed on is re-stamped as it fills). A redraw that
    // moved the cursor UP re-arrives at existing rows: stamp only the
    // cursor row, never wipe.
    let from = (*prev_id).min(cur_id);
    for a in from..=cur_id {
        lt.insert(a, now_ms);
    }
    *prev_id = cur_id;
    // Bounded by the largest configurable scrollback plus a screen;
    // oldest stamps go first.
    while lt.len() > 210_000 {
        lt.pop_first();
    }
}

/// One user note pinned to a span of terminal output (iTerm2's
/// annotations), anchored like a mark so it rides the scrollback.
///
/// This doc had drifted onto `ScrollClock`, 200 lines up, when a `#[derive]`
/// was inserted beneath it. The derive originated here and is left where it
/// has effectively lived: neither struct uses `Clone` or `Debug` today (the
/// `clock.clone()` in the reader is `Arc::clone`), so moving it back would
/// only relocate dead code.
struct PaneAnnotation {
    /// Grid line the span sat on when recorded, paired with the scroll
    /// clock reading at that instant. Translated with clock movement — NOT
    /// `history_size` growth, which saturates once the scrollback fills and
    /// froze annotations in exactly the long-lived panes they target.
    line_rec: i32,
    clock_rec: i64,
    start: u16,
    len: u16,
    text: String,
}

/// The visible screen as `(plain, coloured, wraps)` rows plus the cursor's
/// `(row, col)` on it, `None` when hidden: [`PtyTerminal::screen_ansi_wrapped`].
pub type ScreenAnsi = (Vec<(String, String, bool)>, Option<(u16, u16)>);

pub struct PtyTerminal {
    term: Arc<FairMutex<Term<VoidListener>>>,
    /// Set by the PTY reader thread on every chunk and by `write_input`;
    /// cleared by `take_dirty`. The main loop only redraws when set.
    pty_dirty: Arc<AtomicBool>,
    /// Bytes the reader thread has advanced into the grid since the last
    /// redraw (reset by `take_dirty`). The main loop reads this to tell an
    /// interactive echo (a few bytes: a keystroke, a shell line-rewrite,
    /// an input-box update) from a bulk stream (cat / build logs / a
    /// full-pane scroll). Small updates bypass the PTY redraw cap so echo
    /// stays native; large ones stay capped so they can't saturate the
    /// ssh pipe and starve input.
    pty_pending_bytes: Arc<AtomicUsize>,
    /// Epoch millis of the last PTY output byte, stamped by the reader (#344):
    /// "no output for N seconds" is half of what tells an agent's waiting
    /// from its working.
    last_output_ms: Arc<std::sync::atomic::AtomicU64>,
    /// The coding agent seated in this pane, when the foreground process is
    /// one (#344), carried between samples so a transition can be told.
    agent: Option<crate::agents::AgentLane>,
    /// Listening loopback ports the reader thread scraped out of the output
    /// stream (`http://localhost:PORT` banners, `listening on :PORT` lines).
    /// The app drains this each tick to feed the PORTS panel and the toast.
    port_rx: std::sync::mpsc::Receiver<crate::port_detect::PortHit>,
    /// Who holds the pane's PTY: croft itself, or a pane host (#694).
    backend: PaneBackend,
    /// Bytes for the child's stdin, written by this pane's writer thread.
    /// The user-input path (`write_input`, `paste_*`, `cd_into`, mouse
    /// reports) and the responder that ships alacritty's replies both send
    /// here: portable-pty hands out one writer, and a blocking `write_all`
    /// on the UI thread froze all of croft when a large paste met a program
    /// that was not reading its stdin.
    input_tx: std::sync::mpsc::Sender<Vec<u8>>,
    /// The PTY reader thread's handle, joined in `Drop` after the child is
    /// killed so a dropped terminal never leaves a live shell + blocked
    /// reader behind. Across the test suite that leak piled up into resource
    /// pressure that broke timing-sensitive tests; production drops (closing
    /// a pane) leaked the same way.
    reader_thread: Option<std::thread::JoinHandle<()>>,
    /// Write end of the reader thread's shutdown pipe; `Drop` closes it,
    /// raising POLLHUP on the read end the reader polls alongside the pty.
    /// Without it the join above can hang forever: on Linux a background job
    /// keeps the pty slave open after the shell dies, so the reader's `read`
    /// never returns EOF (macOS revokes the tty instead).
    reader_shutdown: Option<std::io::PipeWriter>,
    /// The interactive shell's pid, captured at spawn. A shell at its
    /// prompt is its own foreground process-group leader, so this is the
    /// value `foreground_is_shell` compares `tcgetpgrp(master)` against.
    shell_pid: Option<i32>,
    /// The shell's exit once [`Self::poll_exit`] has reported it (#912):
    /// its exit code, or None when a pane host went away without one.
    exit: Option<Option<i32>>,
    /// When the shell was first found reaped with its output still open. A
    /// background job it left running can hold the pty open for good, so
    /// the exit is reported after [`EXIT_OUTPUT_GRACE`] all the same.
    reaped_at: Option<std::time::Instant>,
    /// Process-wide stable identity for this pane, assigned at spawn. Vec
    /// positions shift on close/insert/reorder; anything keying long-lived
    /// state to a pane (the build-diagnostic ownership, #119) uses this.
    uid: u64,
    /// Whether anything has ever been written toward the child's stdin
    /// (keystrokes, pastes, seeds, mouse reports). While false, no
    /// foreground application can have been launched in this pane, so a
    /// foreground group that differs from the shell can only be the
    /// shell's own rc startup — the state `cwd_seed_is_safe` treats as
    /// still seedable (#94).
    input_seen: bool,
    /// When input was last written, in the same clock as `last_output_ms`:
    /// until output newer than this arrives, the screen does not yet show
    /// what was typed (#614).
    last_input_ms: u64,
    /// True for a `new_running` pane: the child is a launched program
    /// (a task, run-active-file, a debug attach), not an interactive
    /// shell. Such a pane is doing work the user asked for even though
    /// no input byte was ever written to it, so `is_pristine` must
    /// never mistake it for a replaceable startup default.
    run_pane: bool,
    /// Latches true the first time a non-blank manual name is set and
    /// never clears: a pane the user named is user state even after the
    /// name is cleared back, so `is_pristine` reads this latch rather
    /// than the live `manual_name` (which a blank rename empties).
    manual_name_seen: bool,
    cols: u16,
    rows: u16,
    /// Shared with the `VoidListener` so `TextAreaSizeRequest` callbacks
    /// see the live geometry without us having to thread a fresh
    /// listener instance through every `resize` call.
    size_shared: Arc<std::sync::Mutex<(u16, u16)>>,
    pub focused: bool,
    /// While broadcast input is on, an excluded pane stops receiving the
    /// mirrored keystrokes (it still gets its own input when focused).
    /// Toggled per pane with Cmd+K Shift+I; session-scoped.
    pub broadcast_excluded: bool,
    /// Collapsed to a one-column strip (#313): the pane keeps running and
    /// keeps its place in the row, but yields its width to the panes still
    /// expanded.
    ///
    /// A flag on the PANE rather than a set of indices held by the app.
    /// Indices shift when a pane is closed or reordered, so a stored one
    /// comes to name a different terminal than it was set against - the
    /// same class of bug as #440, where a positional index named the wrong
    /// command after an eviction. A flag that travels with the pane cannot
    /// be pointed at the wrong one.
    ///
    /// Session-scoped, and deliberately not written to the terminal session
    /// store: collapse says "I am not looking at this right now", which is
    /// not a fact worth restoring a workspace into.
    pub collapsed: bool,
    /// When focused, draw the orange→green gradient border (Black theme)
    /// instead of the solid blue one. Set by the app's focus/theme sync.
    pub focus_gradient: bool,
    /// Active color theme; the pane's chrome (borders, pills, gauges) routes
    /// through `Theme::ui` so it follows light themes. Set by the same sync.
    pub theme: crate::theme::Theme,
    pub last_area: Rect,
    pub last_inner: Rect,
    selection: Option<Selection>,
    /// Copy-mode cursor cell (absolute grid line, grid column): painted as
    /// a green modal block over the glyph so keyboard selection has a
    /// visible caret. None whenever copy mode is off.
    copy_cursor: Option<(i32, u16)>,
    /// Scroll-clock reading (see `clock_now`) when the selection /
    /// copy-cursor coordinates were recorded. Grid lines are relative to
    /// the buffer bottom, so every row the pane scrolls afterwards shifts
    /// their content up by one; subtracting the clock movement since this
    /// stamp keeps them glued to their text while output streams.
    sel_scrolled: i64,
    /// The pane's monotonic scroll clock, shared with the PTY reader
    /// thread: the render side re-anchors selections/annotations with it,
    /// the reader keys arrival timestamps on it (both under the term lock,
    /// then this mutex — always in that order).
    clock: Arc<std::sync::Mutex<ScrollClock>>,
    /// Content anchor for a selection made on the alternate screen, where
    /// apps (Claude Code, vim) never scroll the grid — they repaint it in
    /// place, so no scroll clock can see the text move. `None` while the
    /// selection lives on the primary screen.
    alt_sel: Option<AltSelAnchor>,
    /// A mouse drag-selection is in progress (button still held). While
    /// dragging, the selection follows the pointer over whatever the grid
    /// shows — it must never hide itself because the content anchor lost
    /// its rows (the drag may have started on a blank row or on an app's
    /// animated status line). The definitive anchor is captured on
    /// release (`end_drag`).
    drag_selecting: bool,
    /// User-given pane name (via rename), overriding the auto label. `None`
    /// until the user renames the pane.
    manual_name: Option<String>,
    /// Live foreground-process label (`zsh`, `vim`, `node`…), refreshed off the
    /// event loop on a cadence. Empty until the first refresh resolves.
    auto_label: String,
    /// Terminal find state: the needle currently highlighted across the grid
    /// and the options it matches under. `None` when no find bar is open.
    /// Set by the app's terminal find bar; the render loop paints every
    /// occurrence on each visible row.
    search_needle: Option<String>,
    search_opts: crate::widgets::search::SearchOpts,
    /// The active match painted in the brighter accent, versus the muted
    /// highlight on every other occurrence (VS Code's current-vs-other match
    /// colours). Stored as `(clock_rec, line_rec, col, len)` — the line is
    /// anchored on the scroll clock like annotations and hints, so streaming
    /// output moves the bright cell with its text instead of leaving it
    /// parked on a viewport row.
    current_match: Option<(i64, i32, usize, usize)>,
    /// Latched by the event listener when the child rings BEL; drained by
    /// [`Self::take_bell`].
    bell: Arc<AtomicBool>,
    /// Latched by the event listener when the child copies through OSC 52
    /// (#678); drained by [`Self::take_clipboard_store`].
    clipboard_store: Arc<std::sync::Mutex<Option<String>>>,
    /// OSC 133 semantic prompt marks recorded by the reader thread, in
    /// arrival order. Positions are stored as `(grid line, history size)`
    /// at record time; [`Self::command_marks`] translates to current grid
    /// lines (content scrolls into history as output arrives, so a stored
    /// line drifts by exactly the history growth since recording).
    marks: Arc<std::sync::Mutex<Vec<StoredMark>>>,
    /// Latest OSC 7 cwd report from the shell, when integration is active.
    osc7_cwd: Arc<std::sync::Mutex<Option<std::path::PathBuf>>>,
    /// Latest OSC 7 reporting host (SSH inside the pane moves it to the
    /// remote's hostname); feeds the per-host accent rules.
    osc7_host: Arc<std::sync::Mutex<Option<String>>>,
    /// Host-accent dressing resolved by the app against the prefs rules:
    /// border / pill color and the watermark badge.
    pub accent: Option<(u8, u8, u8)>,
    pub accent_badge: Option<String>,
    /// OSC 9 notification payloads awaiting the app's drain.
    notifications: Arc<std::sync::Mutex<Vec<String>>>,
    /// Latest OSC 9;4 progress report `(state, percent)`: 1 normal,
    /// 2 error, 3 indeterminate, 4 warning. `None` when idle (state 0,
    /// command end, or never reported). Drives the bottom-border gauge.
    progress: Arc<std::sync::Mutex<Option<(u8, u8)>>>,
    /// Arrival time (epoch millis) per grid row, keyed by the row's stable
    /// absolute id (`current line + history size`, constant as content
    /// scrolls). Stamped by the reader thread at chunk granularity; cleared
    /// wholesale when the scrollback is wiped (the ids restart).
    line_times: Arc<std::sync::Mutex<std::collections::BTreeMap<i64, u64>>>,
    /// Paint the right-edge HH:MM:SS gutter (the "Terminal: Toggle
    /// Timestamps" palette command flips this on every pane).
    pub show_timestamps: bool,
    /// Paint redact-trigger matches as themselves for a moment ("Terminal:
    /// Reveal Redacted Secrets"); the app sets it on every pane per frame.
    pub reveal_redactions: bool,
    /// How many redact-trigger spans the last paint masked, for the
    /// status-bar chip. Zero while revealing or when nothing matched.
    pub redacted_on_screen: usize,
    /// User notes pinned to output spans (Cmd+K N on a selection).
    /// Session-scoped, like the scrollback they describe.
    annotations: Vec<PaneAnnotation>,
    /// Finished commands (exit, duration) from the reader thread, awaiting
    /// the app's drain for long-command notifications.
    finished_rx: std::sync::mpsc::Receiver<FinishedCommand>,
    /// Quick-select hint spans pushed down by the app while hint mode is
    /// active, paired with the scroll-clock reading their lines were
    /// captured at: the render loop re-bases each span every frame so the
    /// labels follow their matches through streaming output instead of
    /// squatting on fixed viewport rows. `None` when quick-select is off.
    hints: Option<(i64, Vec<HintSpan>)>,
    /// The user's trigger set, shared with the reader thread (which scans
    /// completed lines for notify/bell firings) and read by the render loop
    /// (which paints highlight-trigger matches). The inner Arc is swapped by
    /// [`Self::set_triggers`] on startup and config reload.
    triggers: Arc<std::sync::Mutex<std::sync::Arc<crate::triggers::TriggerSet>>>,
    /// Notify/bell trigger firings from the reader thread, awaiting the
    /// app's drain into the status bar.
    trigger_rx: std::sync::mpsc::Receiver<crate::triggers::TriggerHit>,
    /// Background problem matchers (#252): the global watch-capable set
    /// (from matchers.json, swapped whole like `triggers`) plus this pane's
    /// task-assigned matcher, both read by the reader thread's watch
    /// engine per chunk.
    watch_set: Arc<std::sync::Mutex<std::sync::Arc<crate::problem_matchers::WatchSet>>>,
    pane_watch:
        Arc<std::sync::Mutex<Option<std::sync::Arc<crate::problem_matchers::CompiledMatcher>>>>,
    /// Published watch batches (cwd at publish time + diagnostics),
    /// awaiting the app's drain into PROBLEMS.
    #[allow(clippy::type_complexity)]
    watch_rx: std::sync::mpsc::Receiver<(
        Option<std::path::PathBuf>,
        Vec<crate::build_matchers::BuildDiag>,
    )>,
    /// The theme's 16 ANSI colors; Named and Indexed 0-15 cell colors render
    /// through it so panes look the same on every host terminal (VS Code
    /// owns its terminal palette the same way). Synced by the app's theme
    /// pass via [`Self::set_palette`].
    palette: [(u8, u8, u8); 16],
    /// Inline images captured from the pane's output (iTerm2 OSC 1337
    /// `inline=1`, the imgcat protocol), anchored like marks. Capped at
    /// [`IMAGES_MAX`]; the app overlays the newest visible one.
    images: Arc<std::sync::Mutex<Vec<StoredImage>>>,
    /// The last few minutes of this pane's output, for Session: Rewind
    /// (#357). Written by the reader thread as chunks arrive; bounded by
    /// bytes, so a `yes`-style flood evicts rather than grows.
    rewind: Arc<std::sync::Mutex<crate::rewind::RewindBuffer>>,
    /// Test-only capture of every byte written toward the child's stdin.
    #[cfg(test)]
    written_for_test: Arc<std::sync::Mutex<Vec<u8>>>,
    /// Test-only sender into `finished_rx`, as the reader thread holds.
    #[cfg(test)]
    finished_tx_for_test: std::sync::mpsc::Sender<FinishedCommand>,
}

/// One captured inline image at its recording-time anchor, keyed on the
/// scroll clock like annotations (current line =
/// `line_rec - (clock_now - clock_rec)`), NOT on `history_size`, whose
/// saturation froze the picture onto a viewport row in long-lived panes.
struct StoredImage {
    seq: u64,
    data: std::sync::Arc<Vec<u8>>,
    line_rec: i32,
    clock_rec: i64,
}

/// A pane inline image surfaced to the app: its per-pane id, the raw image
/// bytes, and the anchor's CURRENT grid line (negative = scrolled into
/// history).
#[derive(Clone)]
pub struct PaneImage {
    pub seq: u64,
    pub data: std::sync::Arc<Vec<u8>>,
    pub line: i32,
}

/// Most inline images kept per pane; older ones scroll away like text.
const IMAGES_MAX: usize = 4;

/// One quick-select hint for the render loop: the match span on absolute
/// grid line `line` (char indices into the spacer-skipped row text; the
/// colmap translates back to grid columns), the label overlaid at its start,
/// and how many label chars the user has already typed (those are consumed,
/// only the remainder renders).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HintSpan {
    pub line: i32,
    pub start: usize,
    pub len: usize,
    pub label: String,
    pub typed: usize,
}

/// Source of [`StoredMark::id`], shared by every pane.
///
/// Process-wide rather than per-pane so an id is unambiguous wherever it
/// travels; `u64` so it cannot realistically wrap (at one mark per
/// microsecond it lasts half a million years), which matters because the
/// whole value of the id is that a stale one never matches a live command.
static NEXT_MARK_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);

/// Take the next mark id.
///
/// `Relaxed` is sufficient and is not a shortcut. Uniqueness needs no
/// ordering at all — `fetch_add` on a single atomic is totally ordered on
/// itself, so no two callers can take the same value. And the id's
/// PUBLICATION is ordered by something else entirely: it reaches a reader
/// only inside a `StoredMark` behind the `marks` mutex, whose unlock/lock
/// pair supplies the happens-before. There is no second variable whose
/// visibility this atomic would have to fence, which is the only thing a
/// stronger ordering would buy. Do not "upgrade" it to `SeqCst`.
fn next_mark_id() -> u64 {
    NEXT_MARK_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}

/// One OSC 133 mark at its recording-time anchor, keyed on the scroll
/// clock like annotations and images (current position =
/// `line_rec - (clock_now - clock_rec)`), NOT on `history_size`, whose
/// saturation froze surviving marks onto viewport rows and whose zeroing
/// on a scrollback wipe inverted the math outright. Marks past the
/// scrollback floor are GC'd in `marks_snapshot`.
struct StoredMark {
    /// Monotonic identity, assigned once when the mark is recorded and never
    /// renumbered (#440).
    ///
    /// Positions are not identity here. Three paths remove marks —
    /// `marks_snapshot` GCs those past the scrollback floor, the reader drops
    /// the oldest at `MARKS_MAX`, and a destructive screen wipe clears the
    /// list outright — and the first two shift every index below them down.
    /// A caller holding "index 3" is holding a slot, not a command, and after
    /// an eviction that slot silently names a different one. An id turns that into "command
    /// 41": if 41 is gone the caller learns it is gone instead of reading 42.
    ///
    /// The counter is never reset, including by the wipe, so an id is not
    /// reused after a pane is cleared either.
    id: u64,
    kind: crate::shell_integration::OscEvent,
    line_rec: i32,
    clock_rec: i64,
    /// Cursor column when the mark landed (`PromptEnd`'s column is where the
    /// typed command starts on its prompt line).
    col_rec: usize,
    /// For `CommandEnd` marks: how long the command ran (CommandStart →
    /// CommandEnd, measured in the reader thread). `None` elsewhere.
    dur: Option<std::time::Duration>,
}

/// A finished command as reported by the reader thread at its `133;D`
/// mark: exit + duration (for the long-command notice) plus the typed
/// command text (read off the B→C mark span at the C mark, before the
/// command can clear it) and the pane's OSC 7 cwd at finish time —
/// everything the durable command history records.
#[derive(Clone, Debug)]
pub struct FinishedCommand {
    pub exit: Option<i32>,
    pub dur: std::time::Duration,
    pub cmd: String,
    pub cwd: Option<std::path::PathBuf>,
    /// The OSC 7 reporting hostname AT COMPLETION time. Captured with the
    /// 133;D mark, not read later at drain: an in-pane `ssh`/`exit` between
    /// the two would attribute the command to the wrong machine.
    pub host: Option<String>,
    /// The command's output (the 133;C→133;D span), escape-free, captured at
    /// the D mark while the rows are guaranteed still present. Capped to the
    /// LAST [`FINISHED_OUTPUT_CAP_LINES`] lines — the tail keeps a compiler's
    /// error summary; a build long enough to overflow the cap loses its
    /// earliest lines. Feeds the build problem matchers (#119).
    pub output: String,
}

/// Tail cap on [`FinishedCommand::output`].
pub const FINISHED_OUTPUT_CAP_LINES: usize = 5000;

/// The command a pane is running, from its `133;C` mark to its `133;D`, as
/// the reader thread follows it. What its [`FinishedCommand`] reports is
/// pinned here when it starts rather than read back off the grid when it
/// ends: a command that clears the screen (`clear; make`) has erased the
/// rows its typed line and its first output sat on by then (#876).
struct RunningCommand {
    started: std::time::Instant,
    /// The typed line, read off the `133;B`→`133;C` span at the C mark.
    typed: String,
    /// The first output row, as the grid line and scroll clock reading it
    /// was recorded at, re-based through the clock when the command ends.
    /// The C mark's own row to begin with (`133;C` comes right after the
    /// command's newline, before the program prints anything), and the top
    /// of the screen once a wipe erases that row.
    out_line: i32,
    out_clock: i64,
}

impl RunningCommand {
    /// Follow a wipe that just landed, `now` being the clock read right
    /// after it. Once the first output row is erased, the output that
    /// survives starts at the top of the screen the wipe left: an ED 2
    /// erases that row only when it sat blank below the screen's last text
    /// (alacritty pushes the text into the scrollback), and an ED 3 only
    /// when it sat in the scrollback it empties.
    fn follow_wipe(&mut self, wipe: Wipe, now: i64) {
        let line = self.out_line - (now - self.out_clock) as i32;
        if (line >= 0 && wipe.screen) || (line < 0 && wipe.hist) {
            self.out_line = 0;
            self.out_clock = now;
        }
    }
}

/// Where the reader thread stops the parser inside one read: at a shell
/// mark, to sample the cursor where it landed, or at a wipe, to move the
/// running command's output start past it.
enum ReadStop {
    Mark(crate::shell_integration::OscEvent),
    Wipe(Wipe),
}

/// A finished command derived from the OSC 133 marks: the grid line of the
/// prompt it was typed at (current coords, negative = scrollback), its exit
/// code (`None` when the shell omitted it), how long it ran, where its typed
/// text starts (`PromptEnd` line + column), and its output span
/// (`CommandStart` line up to but excluding the `CommandEnd` line).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CommandDecoration {
    /// Identity of the command, stable across eviction (#440).
    ///
    /// Taken from the `CommandStart` mark, because that is the mark every
    /// finished command has exactly one of — the prompt marks before it are
    /// optional in the pairing below, so keying on one of those would leave
    /// some decorations without an id.
    ///
    /// **Only the identity is stable; the presentation fields are not.** The
    /// id, `exit` and the output span come from the `CommandStart`/`CommandEnd`
    /// pair, so they hold for as long as the decoration exists at all. But
    /// `line` and `input` come from the PROMPT marks, which sit on earlier
    /// grid rows and so cross the scrollback floor FIRST: the GC in
    /// `marks_snapshot` retains per mark, not per command, so a command can
    /// outlive its own prompt. When that happens `line` falls back to
    /// `output_start` and `input` becomes `None`, while the id keeps naming
    /// the same command throughout.
    ///
    /// So a consumer keyed on the id gets a durable answer to "which
    /// command", and a best-effort answer to "where on screen was it typed".
    /// That is the right split for the callers there are — the gutter wants
    /// a row and can use the fallback, and a re-run wants the text and must
    /// handle its absence — but it is a real limit, not an oversight, and
    /// worth knowing before keying anything else on the pair.
    pub id: u64,
    pub line: i32,
    pub exit: Option<i32>,
    pub duration: Option<std::time::Duration>,
    pub input: Option<(i32, usize)>,
    pub output_start: i32,
    pub output_end: i32,
}

/// One mark as a caller sees it: its identity, its CURRENT grid line, and
/// the fields the pairing needs.
///
/// A struct rather than the tuple this used to be. The tuple had reached four
/// positional fields and adding the id would have made five, at which point
/// `m.3` at a call site says nothing about what it holds — and the whole
/// change here is about not confusing a position with an identity.
#[derive(Clone, Debug)]
pub struct MarkView {
    /// Stable identity from [`StoredMark::id`] (#440).
    pub id: u64,
    pub kind: crate::shell_integration::OscEvent,
    /// Current grid line; negative means scrollback.
    pub line: i32,
    /// Cursor column when the mark landed.
    pub col: usize,
    /// For `CommandEnd`: how long the command ran.
    pub dur: Option<std::time::Duration>,
}

/// Pair the mark stream (oldest first, each with its current grid line and,
/// for `CommandEnd`, the measured duration) into one record per *finished*
/// command: the last `PromptStart` line before a `CommandStart` names the
/// row, the following `CommandEnd` supplies exit + duration. A `CommandEnd`
/// with no pending `CommandStart` is dropped — that's how a second
/// integration layer's duplicate marks (Ghostty's hooks chained behind
/// croft's) stay out of the record.
pub fn pair_decorations(marks: &[MarkView]) -> Vec<CommandDecoration> {
    use crate::shell_integration::OscEvent as E;
    let mut out = Vec::new();
    let mut prompt: Option<i32> = None;
    let mut input: Option<(i32, usize)> = None;
    // The id of the `CommandStart` currently open, carried alongside its
    // line so the decoration is keyed on the mark that actually defines the
    // command rather than on whichever prompt mark happened to precede it.
    let mut started: Option<(u64, i32)> = None;
    for m in marks {
        match &m.kind {
            E::PromptStart => {
                prompt = Some(m.line);
                input = None;
            }
            E::PromptEnd => input = Some((m.line, m.col)),
            E::CommandStart => started = Some((m.id, m.line)),
            E::CommandEnd(exit) => {
                if let Some((id, output_start)) = started.take() {
                    out.push(CommandDecoration {
                        id,
                        line: prompt.unwrap_or(output_start),
                        exit: *exit,
                        duration: m.dur,
                        input,
                        output_start,
                        output_end: m.line,
                    });
                }
            }
            _ => {}
        }
    }
    out
}

/// Compact human form of a command duration: "480ms", "3.4s", "2m 05s".
pub fn human_duration(d: std::time::Duration) -> String {
    let secs = d.as_secs_f64();
    if secs < 1.0 {
        format!("{}ms", d.as_millis())
    } else if secs < 60.0 {
        format!("{secs:.1}s")
    } else {
        format!("{}m {:02}s", d.as_secs() / 60, d.as_secs() % 60)
    }
}

/// Cap on retained marks per pane (a mark per prompt/command boundary;
/// thousands would mean a very long session — drop the oldest).
const MARKS_MAX: usize = 2000;

/// The nearest prompt line strictly above (`forward == false`) or below
/// (`forward == true`) the viewport-top grid line `current_top`. Feeds
/// Cmd+Up / Cmd+Down command navigation.
pub fn pick_prompt_jump(prompt_lines: &[i32], current_top: i32, forward: bool) -> Option<i32> {
    if forward {
        prompt_lines
            .iter()
            .copied()
            .filter(|&l| l > current_top)
            .min()
    } else {
        prompt_lines
            .iter()
            .copied()
            .filter(|&l| l < current_top)
            .max()
    }
}

/// Inject croft's shell-integration environment for supported shells, and
/// return the shell's argv: `args` (its login flag) with whatever the
/// integration adds. Long options go first, because bash only recognises
/// them (`--posix`) ahead of single-character ones (`-l`).
/// zsh: point `ZDOTDIR` at croft's shim. bash: the kitty/Ghostty trick —
/// `--posix` plus `ENV` pointing at croft's shim (posix-mode bash reads
/// only `$ENV`; the shim backs out and replays the real startup files).
/// Below 4.4 bash ignores that `$ENV`, so it reads the shim through
/// `--rcfile`, non-login, and the shim replays the login files itself.
/// fish: prepend a `vendor_conf.d` data dir to `XDG_DATA_DIRS`; the script
/// defers to fish 4's native marks. Every shim sources the user's real
/// dotfiles unchanged and emits OSC 133 prompt marks + the OSC 7 cwd
/// report. Opt out with `CROFT_SHELL_INTEGRATION=0`. Failures are
/// non-fatal — the shell still spawns, just without marks.
fn apply_shell_integration_env(
    cmd: &mut CommandBuilder,
    shell_path: &str,
    config_dir: &std::path::Path,
    args: Vec<String>,
) -> Vec<String> {
    if std::env::var("CROFT_SHELL_INTEGRATION").as_deref() == Ok("0") {
        return args;
    }
    let base = std::path::Path::new(shell_path)
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or("");
    match base {
        "zsh" => {
            let Ok(shim) = crate::shell_integration::ensure_zsh_shim(config_dir) else {
                return args;
            };
            // An inherited ZDOTDIR pointing at croft's own shim (croft
            // launched from a croft pane) is poisoned — the user's dotfiles
            // live in HOME.
            let inherited = std::env::var_os("ZDOTDIR").map(std::path::PathBuf::from);
            let home = std::env::var_os("HOME")
                .map(std::path::PathBuf::from)
                .unwrap_or_default();
            if home.as_os_str().is_empty() {
                return args;
            }
            let user_zdotdir = crate::shell_integration::resolve_user_zdotdir(
                inherited.as_deref(),
                &config_dir.join("shell-integration"),
                &home,
            );
            cmd.env("CROFT_USER_ZDOTDIR", user_zdotdir);
            cmd.env("ZDOTDIR", &shim);
            args
        }
        "bash" => {
            let Ok(shim) = crate::shell_integration::ensure_bash_shim(config_dir) else {
                return args;
            };
            // Preserve a user $ENV (rare for bash) for the shim to restore.
            if let Ok(env) = std::env::var("ENV") {
                cmd.env("CROFT_BASH_ENV", env);
            }
            cmd.env("CROFT_BASH_INJECT", "1");
            if !bash_env_injection_supported(shell_path) {
                // No `$ENV` in posix mode (macOS's 3.2), so the shim goes in
                // as the rcfile, as VS Code does it. A login bash ignores
                // `--rcfile`, so the shell starts non-login and the shim
                // replays the login files in its place.
                if args.iter().any(|a| a == "-l" || a == "--login") {
                    cmd.env("CROFT_BASH_LOGIN", "1");
                }
                return vec!["--rcfile".to_string(), shim.display().to_string()];
            }
            cmd.env("ENV", &shim);
            // Posix mode defaults HISTFILE to ~/.sh_history; pre-seed the
            // bash default and let the shim unexport it.
            if std::env::var_os("HISTFILE").is_none()
                && let Some(home) = std::env::var_os("HOME")
            {
                cmd.env(
                    "HISTFILE",
                    std::path::Path::new(&home).join(".bash_history"),
                );
                cmd.env("CROFT_BASH_UNEXPORT_HISTFILE", "1");
            }
            std::iter::once("--posix".to_string()).chain(args).collect()
        }
        "fish" => {
            let Ok(dir) = crate::shell_integration::ensure_fish_integration(config_dir) else {
                return args;
            };
            let inherited = std::env::var("XDG_DATA_DIRS").ok();
            cmd.env(
                "XDG_DATA_DIRS",
                crate::shell_integration::fish_xdg_data_dirs(&dir, inherited.as_deref()),
            );
            cmd.env("CROFT_FISH_XDG_DATA_DIR", &dir);
            args
        }
        _ => args,
    }
}

/// The command for an interactive pane shell: `shell_path` as a login
/// shell, with croft's shell integration.
fn interactive_shell_command(shell_path: &str, config_dir: &std::path::Path) -> CommandBuilder {
    let (program, args) = interactive_shell_invocation(shell_path);
    let mut cmd = CommandBuilder::new(&program);
    for a in apply_shell_integration_env(&mut cmd, shell_path, config_dir, args) {
        cmd.arg(a);
    }
    cmd
}

/// Whether this bash reads `$ENV` in posix mode, i.e. the injection works
/// at all. Verified empirically: macOS's system bash 3.2 never reads $ENV
/// under `--posix`, so injecting would strip its startup files for
/// nothing; Homebrew/Linux 5.x does. 4.4 is the ecosystem floor (kitty,
/// Ghostty). One short probe subprocess per pane spawn — pane creation
/// already forks a shell, so this is noise.
fn bash_env_injection_supported(shell_path: &str) -> bool {
    let Ok(out) = std::process::Command::new(shell_path)
        .args(["-c", "echo \"${BASH_VERSINFO[0]}.${BASH_VERSINFO[1]}\""])
        .output()
    else {
        return false;
    };
    parse_bash_version_supported(&String::from_utf8_lossy(&out.stdout))
}

/// `major.minor` >= 4.4, tolerant of anything a non-bash prints.
fn parse_bash_version_supported(s: &str) -> bool {
    let mut it = s.trim().split('.');
    let (Some(maj), Some(min)) = (
        it.next().and_then(|v| v.parse::<u32>().ok()),
        it.next().and_then(|v| v.parse::<u32>().ok()),
    ) else {
        return false;
    };
    maj > 4 || (maj == 4 && min >= 4)
}

/// Pick the program + args to spawn the user's interactive shell so it
/// behaves like the one iTerm2 / Terminal.app launches. Both run the
/// shell as a *login* shell (`Login shell` is iTerm2's default Command
/// setting), which sources `~/.zprofile` / `~/.profile` in addition to
/// the interactive rc file. Without that, anything the user puts in
/// `.zprofile` — PATH munging, framework loaders, plugin managers like
/// zinit/oh-my-zsh that install keybindings, vi-mode toggles — is
/// silently absent inside croft. For mainstream POSIX shells we pass
/// `-l`; for anything exotic we leave argv empty rather than risk
/// breaking the spawn with an unknown flag.
pub fn interactive_shell_invocation(shell_path: &str) -> (String, Vec<String>) {
    let basename = std::path::Path::new(shell_path)
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or(shell_path);
    let supports_login_flag = matches!(
        basename,
        "zsh" | "bash" | "fish" | "ksh" | "mksh" | "dash" | "tcsh" | "sh"
    );
    let args = if supports_login_flag {
        vec!["-l".to_string()]
    } else {
        Vec::new()
    };
    (shell_path.to_string(), args)
}

/// Parse `/etc/shells` into `(path, basename)` terminal profiles: skip comments
/// and blanks, keep absolute paths only, and dedupe by basename (first wins, so
/// `/bin/bash` shadows `/usr/local/bin/bash`). The basename is the label shown.
pub fn parse_shells(contents: &str) -> Vec<(String, String)> {
    let mut out: Vec<(String, String)> = Vec::new();
    for line in contents.lines() {
        let line = line.trim();
        if line.is_empty() || !line.starts_with('/') {
            continue;
        }
        let base = std::path::Path::new(line)
            .file_name()
            .and_then(|s| s.to_str())
            .unwrap_or(line)
            .to_string();
        if out.iter().any(|(_, b)| *b == base) {
            continue;
        }
        out.push((line.to_string(), base));
    }
    out
}

/// Resolve a pid to its command name (basename), cross-platform, via `sysinfo`
/// (no subprocess). Used to label a terminal pane with its foreground process.
/// Refreshes only the one pid, so it's cheap, but still runs off the event loop.
pub fn process_name(pid: i32) -> Option<String> {
    use sysinfo::{Pid, ProcessesToUpdate, System};
    if pid <= 0 {
        return None;
    }
    let p = Pid::from(pid as usize);
    let mut sys = System::new();
    sys.refresh_processes(ProcessesToUpdate::Some(&[p]), true);
    sys.process(p)
        .map(|pr| pr.name().to_string_lossy().to_string())
        .filter(|n| !n.is_empty())
}

/// The argv of a running process, or `None` when the platform will not say.
///
/// Separate from [`process_name`] because the two answer different questions
/// and cost differently: a name is what the label pill needs on every tick,
/// while argv is only wanted when the name says the process is worth asking
/// about (#364 wants it for `ssh` and nothing else).
pub fn process_cmdline(pid: i32) -> Option<Vec<String>> {
    use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System, UpdateKind};
    if pid <= 0 {
        return None;
    }
    let p = Pid::from(pid as usize);
    let mut sys = System::new();
    // The argv must be asked for by name (#1846): sysinfo's plain
    // `refresh_processes` reads memory, CPU, disk use and the executable,
    // never the command line, so `cmd()` was always empty. Every pane that
    // ran `ssh box` then read as "not an SSH session": the open-workspace
    // offer never appeared, and the user stayed in the remote shell.
    sys.refresh_processes_specifics(
        ProcessesToUpdate::Some(&[p]),
        true,
        ProcessRefreshKind::nothing().with_cmd(UpdateKind::Always),
    );
    let cmd: Vec<String> = sys
        .process(p)?
        .cmd()
        .iter()
        .map(|s| s.to_string_lossy().to_string())
        .collect();
    (!cmd.is_empty()).then_some(cmd)
}

/// Live cwd of a running process by PID, or None when the platform doesn't
/// expose one. Used by `split_terminal` so a new pane lands wherever the
/// user has `cd`'d the active shell, and by [`PtyTerminal::local_shell_cwd`]
/// as the ground truth an OSC 7 claim must match to be trusted.
#[cfg(target_os = "linux")]
pub fn cwd_of_pid(pid: u32) -> Option<std::path::PathBuf> {
    std::fs::read_link(format!("/proc/{pid}/cwd")).ok()
}

/// macOS: call `proc_pidinfo` with `PROC_PIDVNODEPATHINFO` directly via the
/// libSystem FFI instead of shelling out to `lsof -d cwd`. Two reasons:
///   1. `lsof` on Sonoma+ tickles the "App Management" / "App Data" TCC
///      privacy class (the OS sees the responsible parent process — iTerm
///      — inspecting another process's open files and prompts the user).
///      `proc_pidinfo` against our own child PID needs no TCC entitlement.
///   2. No fork/exec on the hot path of every terminal split.
///
/// Struct layout matches `<sys/proc_info.h>`. We read the path field of
/// `pvi_cdir` (the cwd vnode) at the documented offset.
#[cfg(target_os = "macos")]
pub fn cwd_of_pid(pid: u32) -> Option<std::path::PathBuf> {
    use std::ffi::OsString;
    use std::os::raw::{c_int, c_void};
    use std::os::unix::ffi::OsStringExt;

    const PROC_PIDVNODEPATHINFO: c_int = 9;
    const MAXPATHLEN: usize = 1024;

    #[repr(C)]
    #[derive(Default, Clone, Copy)]
    struct VinfoStat {
        vst_dev: u32,
        vst_mode: u16,
        vst_nlink: u16,
        vst_ino: u64,
        vst_uid: u32,
        vst_gid: u32,
        vst_atime: i64,
        vst_atimensec: i64,
        vst_mtime: i64,
        vst_mtimensec: i64,
        vst_ctime: i64,
        vst_ctimensec: i64,
        vst_birthtime: i64,
        vst_birthtimensec: i64,
        vst_size: i64,
        vst_blocks: i64,
        vst_blksize: i32,
        vst_flags: u32,
        vst_gen: u32,
        vst_rdev: u32,
        vst_qspare: [i64; 2],
    }

    #[repr(C)]
    #[derive(Clone, Copy)]
    struct VnodeInfo {
        vi_stat: VinfoStat,
        vi_type: i32,
        vi_pad: i32,
        vi_fsid: [i32; 2],
    }

    #[repr(C)]
    #[derive(Clone, Copy)]
    struct VnodeInfoPath {
        vip_vi: VnodeInfo,
        vip_path: [u8; MAXPATHLEN],
    }

    #[repr(C)]
    #[derive(Clone, Copy)]
    struct ProcVnodePathInfo {
        pvi_cdir: VnodeInfoPath,
        pvi_rdir: VnodeInfoPath,
    }

    unsafe extern "C" {
        fn proc_pidinfo(
            pid: c_int,
            flavor: c_int,
            arg: u64,
            buffer: *mut c_void,
            buffersize: c_int,
        ) -> c_int;
    }

    let mut info: ProcVnodePathInfo = unsafe { std::mem::zeroed() };
    let size = std::mem::size_of::<ProcVnodePathInfo>() as c_int;
    let ret = unsafe {
        proc_pidinfo(
            pid as c_int,
            PROC_PIDVNODEPATHINFO,
            0,
            &mut info as *mut _ as *mut c_void,
            size,
        )
    };
    if ret <= 0 {
        return None;
    }
    let path = &info.pvi_cdir.vip_path;
    let len = path.iter().position(|&b| b == 0).unwrap_or(0);
    if len == 0 {
        return None;
    }
    Some(std::path::PathBuf::from(OsString::from_vec(
        path[..len].to_vec(),
    )))
}

#[cfg(not(any(target_os = "linux", target_os = "macos")))]
pub fn cwd_of_pid(_pid: u32) -> Option<std::path::PathBuf> {
    None
}

/// Whether this platform can report a process's cwd AT ALL.
///
/// The distinction matters wherever a guard reads `cwd_of_pid`: on Android
/// — a separate `target_os` from `linux`, so it binds the stub above — the
/// answer is a permanent `None` rather than a per-pane one. A guard that
/// treats "cannot observe" as "observed something wrong" does not become
/// stricter there, it becomes unsatisfiable, and whatever it guards is
/// lost entirely for those users (#430).
pub const fn cwd_is_observable() -> bool {
    cfg!(any(target_os = "linux", target_os = "macos"))
}

/// A saved transcript rendered as bytes safe to feed a fresh parser.
///
/// Control characters are stripped rather than escaped: a transcript comes off
/// disk, and a grid should never have contained an escape in the first place,
/// so anything control-shaped here is either corruption or someone's idea of a
/// joke. TAB is the exception — it is legitimate output, and deleting it
/// silently collapses tab-aligned columns — so it becomes a space, which is
/// what the grid would have shown anyway.
fn transcript_bytes(lines: &[String]) -> Vec<u8> {
    let mut bytes = Vec::new();
    for l in lines {
        let cleaned: String = l
            .chars()
            .map(|c| if c == '\t' { ' ' } else { c })
            .filter(|c| !c.is_control())
            .collect();
        bytes.extend(cleaned.as_bytes());
        bytes.extend_from_slice(b"\r\n");
    }
    bytes
}

/// The label to show for a pane: a manual name wins, else the live foreground
/// process name.
pub fn pick_pane_label<'a>(manual: Option<&'a str>, auto: &'a str) -> &'a str {
    manual.unwrap_or(auto)
}

/// Croft's own environment for a pane's shell: the terminal identity every
/// pane needs, plus the `croft view` socket when one is bound (#362).
///
/// `view_sock` is passed IN rather than read from a global here, so this is a
/// pure function a test can assert against without touching process-wide
/// state; the spawn funnel supplies it from [`crate::view_ipc::SOCK_PATH`].
///
/// The socket travels this way rather than through the process environment
/// because it cannot travel that way at all. portable-pty snapshots
/// `std::env::vars_os()` inside `CommandBuilder::new` and then `env_clear()`s
/// before applying only that snapshot, so a `set_var` performed after a pane
/// was constructed never reaches its shell. The listener is bound while
/// `App::new` runs, which is after the FIRST pane exists, so publishing by
/// environment left `croft view` broken in the one pane most users type in
/// and working in every pane opened later: breakage that reads as
/// intermittent rather than as a bug.
///
/// A `OnceLock` read at spawn time has no ordering hazard to get wrong, and
/// no `unsafe` either: `std::env::set_var` is unsafe in edition 2024 precisely
/// because croft has threads running by then, which is the condition
/// `src/gui_path.rs` and `src/session.rs` both document for their own calls.
pub(crate) fn apply_pane_env(cmd: &mut CommandBuilder, view_sock: Option<&std::path::Path>) {
    cmd.env("TERM", "xterm-256color");
    cmd.env("COLORTERM", "truecolor");
    // The pane is croft's emulator, not the host's (#1453). A program that
    // read Ghostty's `TERM_PROGRAM` here wrote Kitty graphics the pane drops,
    // so `croft plot` printed blank rows. VS Code does the same with
    // `TERM_PROGRAM=vscode`.
    cmd.env("TERM_PROGRAM", crate::iterm2_inline::CROFT_TERM_PROGRAM);
    cmd.env("TERM_PROGRAM_VERSION", env!("CARGO_PKG_VERSION"));
    for host_only in HOST_TERMINAL_VARS {
        cmd.env_remove(host_only);
    }
    cmd.env(
        crate::iterm2_inline::CROFT_INLINE_IMAGES_ENV,
        if pane_images_shown() { "1" } else { "0" },
    );
    // A pane's shell must count characters the way the terminal draws them.
    // macOS forwards `LC_CTYPE=UTF-8` over ssh, which Linux does not know, so
    // a remote shell fell back to ASCII and counted a 3-byte prompt glyph
    // (`❯`, a Nerd Font icon) as 3 columns: every redraw landed 2 columns
    // off and left 2-character coloured tails behind (#537).
    if cfg!(target_os = "linux") {
        let var = |k: &str| std::env::var(k).ok();
        if let Some((key, value)) = utf8_ctype_fix(var("LC_ALL"), var("LC_CTYPE"), var("LANG")) {
            cmd.env(key, value);
        }
    }
    // `git rebase -i` opens its plan in this croft (#620), unless the user
    // chose their own sequence editor, which always wins: an exported
    // GIT_SEQUENCE_EDITOR here, or `sequence.editor` in git config, which
    // `croft edit --sequence-editor` looks up in the rebasing repo itself.
    if view_sock.is_some()
        && std::env::var_os("GIT_SEQUENCE_EDITOR").is_none()
        && let Some(exe) = std::env::current_exe().ok().and_then(live_exe)
    {
        cmd.env("GIT_SEQUENCE_EDITOR", sequence_editor_command(&exe));
    }
    match view_sock {
        Some(path) => cmd.env(crate::view_ipc::SOCK_ENV, path),
        // CLEARED, not merely not-added. `CommandBuilder::new` seeds itself
        // from `std::env::vars_os()`, so a croft launched from a croft pane
        // inherits the OUTER croft's socket. If this croft's own bind failed,
        // leaving that inherited value in place points its panes at the
        // parent: `croft view report.pdf` opens the file in the wrong window
        // and exits 0, which is worse than the honest refusal the field doc
        // promises ("panes then see no CROFT_VIEW_SOCK and the client says so
        // plainly").
        None => cmd.env_remove(crate::view_ipc::SOCK_ENV),
    }
}

/// Variables that name the HOST terminal (#1453). In a pane they would send
/// a program down a graphics or feature path croft's emulator does not relay.
const HOST_TERMINAL_VARS: &[&str] = &[
    "KITTY_WINDOW_ID",
    "KITTY_PID",
    "GHOSTTY_RESOURCES_DIR",
    "GHOSTTY_BIN_DIR",
    "ITERM_SESSION_ID",
    "LC_TERMINAL",
    "LC_TERMINAL_VERSION",
    "WEZTERM_PANE",
    "WEZTERM_EXECUTABLE",
    "VTE_VERSION",
];

/// Set once the DA1 probe finds a sixel host, which no variable advertises.
pub static SIXEL_HOST: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// Whether this croft draws a pane's captured images (#1453): the outer
/// terminal speaks some image protocol. A pane opened before the sixel probe
/// answers says no, which costs a picture, never a blank chart.
fn pane_images_shown() -> bool {
    crate::iterm2_inline::detect_inline_image_protocol()
        != crate::iterm2_inline::InlineImageProtocol::None
        || SIXEL_HOST.load(std::sync::atomic::Ordering::Relaxed)
}

/// The locale variable to set so a Linux shell reads its text as UTF-8, or
/// None when the inherited locale already does (or the user pinned another
/// with `LC_ALL`, which wins over anything set here). The bare name `UTF-8`
/// is what macOS sends and no Linux locale is called that.
fn utf8_ctype_fix(
    lc_all: Option<String>,
    lc_ctype: Option<String>,
    lang: Option<String>,
) -> Option<(&'static str, &'static str)> {
    let is_utf8 = |v: &str| {
        let codeset = v
            .split('@')
            .next()
            .unwrap_or(v)
            .rsplit('.')
            .next()
            .unwrap_or("");
        v.contains('.') && matches!(codeset.to_ascii_lowercase().as_str(), "utf-8" | "utf8")
    };
    let bare = |v: &str| v.eq_ignore_ascii_case("utf-8") || v.eq_ignore_ascii_case("utf8");
    match lc_all.filter(|v| !v.is_empty()) {
        Some(v) if bare(&v) => return Some(("LC_ALL", "C.UTF-8")),
        Some(_) => return None,
        None => {}
    }
    let effective = lc_ctype
        .filter(|v| !v.is_empty())
        .or(lang.filter(|v| !v.is_empty()));
    match effective {
        Some(v) if is_utf8(&v) => None,
        _ => Some(("LC_CTYPE", "C.UTF-8")),
    }
}

/// Milliseconds since the epoch, the clock `last_output_ms` keeps.
fn now_ms() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0)
}

/// `exe` as a path that still runs. Once an update renames a new binary
/// over the running one, Linux reports it as `.../croft (deleted)`, which
/// no shell can start; the new binary at the same path can, and `croft
/// edit` is the same command in both.
fn live_exe(exe: std::path::PathBuf) -> Option<std::path::PathBuf> {
    if exe.exists() {
        return Some(exe);
    }
    let replaced = std::path::PathBuf::from(exe.to_str()?.strip_suffix(" (deleted)")?);
    replaced.exists().then_some(replaced)
}

/// The `GIT_SEQUENCE_EDITOR` value naming this croft (#620). git runs it
/// through the shell, so the binary's path is single-quoted.
pub(crate) fn sequence_editor_command(exe: &std::path::Path) -> String {
    let quoted = exe.to_string_lossy().replace('\'', r"'\''");
    format!("'{quoted}' edit --wait --sequence-editor")
}

/// Put `bin` first on the pane's PATH, so `croft` in the pane is this croft
/// (#1854), and name it to the shell hooks. They put it first again once
/// the user's startup files have run, because those run after this: a
/// `.zprofile` running `brew shellenv` puts /opt/homebrew/bin, and a
/// Homebrew croft, back in front.
///
/// With no bin of its own, a pane drops the one it inherited. A croft
/// launched from a croft pane carries the OUTER croft's, and passing that
/// on would answer `croft` with a different croft than the window.
///
/// An unset PATH stays unset, for the shell to fill with its default: PATH
/// set to the bin alone would leave the pane without /usr/bin.
pub(crate) fn apply_pane_bin(cmd: &mut CommandBuilder, bin: Option<&std::path::Path>) {
    use crate::shell_integration::PANE_BIN_ENV;
    let inherited = cmd.get_env(PANE_BIN_ENV).map(std::path::PathBuf::from);
    let path = cmd.get_env("PATH").and_then(|path| {
        let rest = std::env::split_paths(path)
            .filter(|d| Some(d.as_path()) != bin && Some(d) != inherited.as_ref());
        std::env::join_paths(
            bin.map(std::path::Path::to_path_buf)
                .into_iter()
                .chain(rest),
        )
        .ok()
    });
    if let Some(path) = path {
        cmd.env("PATH", path);
    }
    match bin {
        Some(bin) => cmd.env(PANE_BIN_ENV, bin),
        None => cmd.env_remove(PANE_BIN_ENV),
    }
}

/// This croft's pane bin, made on first use. None when the running binary
/// is gone from disk (an upgrade removed it) or the cache cannot be
/// written; the pane then finds `croft` on the user's PATH, as before.
fn pane_bin_dir() -> Option<std::path::PathBuf> {
    let exe = live_exe(std::env::current_exe().ok()?)?;
    crate::shell_integration::ensure_pane_bin(&crate::app::croft_cache_dir(), &exe).ok()
}

impl PtyTerminal {
    pub fn new(cwd: &std::path::Path) -> Result<Self> {
        let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/bash".to_string());
        Self::new_shell(&shell, cwd)
    }

    /// Spawn a shell with `transcript` already painted into the grid, for a
    /// pane restored from a saved session (#249).
    ///
    /// The preamble is painted before the reader thread starts, not after the
    /// constructor returns. Replaying afterwards races the shell: both write
    /// the same `Term` behind the same lock, and a shell that reaches its
    /// first prompt before the replay wins, so the restored output lands
    /// below or through the prompt instead of above it.
    pub fn new_with_transcript(cwd: &std::path::Path, transcript: &[String]) -> Result<Self> {
        let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/bash".to_string());
        let mut cmd = interactive_shell_command(&shell, &crate::prefs::config_dir());
        cmd.cwd(cwd);
        Self::spawn_with_preamble(cmd, None, &transcript_bytes(transcript))
    }

    /// Spawn an interactive login session for a specific shell (a terminal
    /// profile), rather than `$SHELL`. The same login-flag handling as [`new`].
    pub fn new_shell(shell_path: &str, cwd: &std::path::Path) -> Result<Self> {
        let mut cmd = interactive_shell_command(shell_path, &crate::prefs::config_dir());
        cmd.cwd(cwd);
        Self::spawn_with(cmd, None)
    }

    pub fn new_running(program: &str, args: &[String], cwd: &std::path::Path) -> Result<Self> {
        let mut cmd = CommandBuilder::new(program);
        for a in args {
            cmd.arg(a);
        }
        cmd.cwd(cwd);
        let label = if args.is_empty() {
            program.to_string()
        } else {
            format!("{program} {}", args.join(" "))
        };
        Self::spawn_with(cmd, Some(label))
    }

    pub fn visible_text(&self) -> String {
        let term = self.term.lock();
        let rows = term.screen_lines();
        let cols = term.columns();
        if rows == 0 || cols == 0 {
            return String::new();
        }
        let off = term.grid().display_offset() as i32;
        extract_selection_text(&term, -off, 0, rows as i32 - 1 - off, cols - 1)
    }

    /// Every readable grid line as plain text — oldest scrollback first, then
    /// the live screen — paired with the absolute alacritty `Line` index of
    /// row 0. Terminal find searches these lines; `top + row` maps a hit's
    /// row back to its grid line so it can be scrolled into view and
    /// highlighted. Wide-char spacer cells are skipped (see
    /// [`row_text_and_cols`]), so match positions are char indices, not grid
    /// columns.
    pub fn grid_lines(&self) -> (Vec<String>, i32) {
        let (lines, _, top) = self.grid_lines_wrapped();
        (lines, top)
    }

    /// [`Self::grid_lines`] plus, per row, whether it soft-wraps into the
    /// next, read under the same lock: redaction joins wrapped rows, since a
    /// secret split across two rows matches neither on its own.
    pub fn grid_lines_wrapped(&self) -> (Vec<String>, Vec<bool>, i32) {
        grid_rows_wrapped(&self.term.lock())
    }

    /// The grid as find's logical lines: soft-wrapped rows joined, so a
    /// match the pane's width cut in two is found (#1275). See
    /// [`join_wrapped_rows`].
    pub fn find_lines(&self) -> Vec<FindLine> {
        let (lines, wraps, top) = self.grid_lines_wrapped();
        join_wrapped_rows(lines, &wraps, top)
    }

    /// [`Self::find_lines`] plus the scroll-clock reading, captured under
    /// ONE term lock. Terminal find stamps its match anchor with the clock;
    /// separate reads would let output land between them and mis-pair a
    /// line with a reading it wasn't captured at.
    pub fn find_lines_and_clock(&self) -> (Vec<FindLine>, i64) {
        let term = self.term.lock();
        let (lines, wraps, top) = grid_rows_wrapped(&term);
        (join_wrapped_rows(lines, &wraps, top), self.clock_now(&term))
    }

    /// Every readable grid row as `(plain, coloured)`: the plain text
    /// exactly as [`Self::grid_lines`] gives it, and the same row with the
    /// cells' colours and attributes written back as SGR, so the text can be
    /// re-rendered elsewhere with the colours the pane showed (#257: "open
    /// scrollback in an editor tab" through the rendered log view). Both
    /// forms come from ONE pass under ONE term lock, so a caller that masks
    /// the plain row and writes the coloured one can never pair a row with
    /// its neighbour after output landed between two reads. Wide-char
    /// spacers are skipped as in `grid_lines`; trailing default-styled
    /// blanks are trimmed (a row padded with a coloured background keeps
    /// those cells, which the plain twin drops, so the two forms can differ
    /// in length there); every row that set a style ends with a reset.
    pub fn grid_lines_ansi(&self) -> Vec<(String, String)> {
        self.grid_lines_ansi_wrapped()
            .into_iter()
            .map(|(plain, ansi, _)| (plain, ansi))
            .collect()
    }

    /// [`Self::grid_lines_ansi`] plus whether each row soft-wraps into the
    /// next (see [`Self::grid_lines_wrapped`]).
    pub fn grid_lines_ansi_wrapped(&self) -> Vec<(String, String, bool)> {
        let term = self.term.lock();
        if term.columns() == 0 {
            return Vec::new();
        }
        let top = term.grid().topmost_line().0;
        ansi_rows(&term, top)
    }

    /// The visible screen as [`Self::grid_lines_ansi_wrapped`] rows, with
    /// the shell cursor's cell on that screen, read under ONE term lock so
    /// the cursor belongs to the rows it is drawn over (#356: a recorded
    /// frame is the screen in colour, cursor included). The cursor is
    /// `None` when the program hid it; scrollback is never walked, so the
    /// cost is one screen however long the history is.
    pub fn screen_ansi_wrapped(&self) -> ScreenAnsi {
        let term = self.term.lock();
        if term.columns() == 0 {
            return (Vec::new(), None);
        }
        let rows = ansi_rows(&term, 0);
        let p = term.grid().cursor.point;
        let cursor = (term.mode().contains(TermMode::SHOW_CURSOR)
            && p.line.0 >= 0
            && (p.line.0 as usize) < rows.len())
        .then_some((p.line.0 as u16, p.column.0 as u16));
        (rows, cursor)
    }

    /// The OSC 8 hyperlink URI stored under viewport cell `(row, col)`, if
    /// any. Hyperlinked cells carry the URI invisibly; the app's
    /// Cmd/Ctrl+click handler checks this before the plain-text URL regex.
    pub fn hyperlink_at(&self, row: usize, col: usize) -> Option<String> {
        let term = self.term.lock();
        if col >= term.columns() {
            return None;
        }
        let line_idx = row as i32 - term.grid().display_offset() as i32;
        if line_idx < term.grid().topmost_line().0 || line_idx >= term.screen_lines() as i32 {
            return None;
        }
        term.grid()[Point::new(Line(line_idx), Column(col))]
            .hyperlink()
            .map(|h| h.uri().to_string())
    }

    /// Set (or clear) the find highlight. Every occurrence of `needle` is
    /// painted across the visible grid on the next render.
    pub fn set_search(&mut self, needle: Option<String>, opts: crate::widgets::search::SearchOpts) {
        self.search_needle = needle.filter(|s| !s.is_empty());
        self.search_opts = opts;
        self.pty_dirty.store(true, Ordering::Release);
    }

    /// Mark which occurrence is the active match `(abs_line, col, len)` so the
    /// render loop paints it in the brighter accent. `abs_line` is the first
    /// row of the match's logical line and `col` a char index into it (see
    /// [`FindLine`]). `clock` is the
    /// scroll-clock reading the line was captured against (the
    /// [`Self::find_lines_and_clock`] snapshot); the render re-bases per
    /// frame so the highlight follows its text through streaming output.
    pub fn set_current_match(&mut self, m: Option<(i32, usize, usize)>, clock: i64) {
        self.current_match = m.map(|(line, col, len)| (clock, line, col, len));
        self.pty_dirty.store(true, Ordering::Release);
    }

    /// Set (or clear) the quick-select hint overlay. The app owns hint-mode
    /// state and re-pushes the filtered set as the user types label chars;
    /// `clock` is the scroll-clock reading the span lines were captured at
    /// (from [`Self::visible_lines_and_clock`]), reused verbatim on every
    /// re-push so the render-time translation stays anchored to the open.
    pub fn set_hints(&mut self, hints: Option<Vec<HintSpan>>, clock: i64) {
        self.hints = hints.map(|h| (clock, h));
        self.pty_dirty.store(true, Ordering::Release);
    }

    /// The visible viewport rows as spacer-skipped plain text, paired with
    /// the absolute grid line of the first row (`-display_offset`).
    /// Quick-select scans exactly what is on screen — labels the user cannot
    /// see cannot be typed.
    pub fn visible_lines(&self) -> (Vec<String>, i32) {
        let term = self.term.lock();
        if term.columns() == 0 {
            return (Vec::new(), 0);
        }
        let off = term.grid().display_offset() as i32;
        let rows = term.screen_lines() as i32;
        let mut lines = Vec::new();
        for l in -off..rows - off {
            let (s, _cols) = row_text_and_cols(&term, l);
            lines.push(s.trim_end().to_string());
        }
        (lines, -off)
    }

    /// [`Self::visible_lines`] plus per-row soft-wrap flags and the scroll
    /// clock, all from ONE term lock: coordinates and clock captured
    /// together so output landing between two separate reads can never
    /// mis-pair them (quick-select anchors its labels on this snapshot).
    /// `wraps[i]` says row `i` continues into row `i + 1` (WRAPLINE on its
    /// last cell); a wrapping row keeps its trailing spaces — they are real
    /// cells mid-line, and trimming them would glue the next row's first
    /// word onto this one when the rows are stitched for scanning (#64).
    pub fn visible_lines_and_clock(&mut self) -> (Vec<String>, Vec<bool>, i32, i64) {
        let mut term = self.term.lock();
        let clock = self.clock.lock().unwrap().tick(&mut term);
        if term.columns() == 0 {
            return (Vec::new(), Vec::new(), 0, clock);
        }
        let off = term.grid().display_offset() as i32;
        let rows = term.screen_lines() as i32;
        let cols = term.columns();
        let mut lines = Vec::new();
        let mut wraps = Vec::new();
        for l in -off..rows - off {
            let (s, _cols) = row_text_and_cols(&term, l);
            let wrapped = term.grid()[Point::new(Line(l), Column(cols - 1))]
                .flags
                .contains(Flags::WRAPLINE);
            lines.push(if wrapped { s } else { s.trim_end().to_string() });
            wraps.push(wrapped);
        }
        (lines, wraps, -off, clock)
    }

    /// Swap in a new trigger set. The app calls this for every pane on every
    /// drain tick (so a pane is covered no matter where it was created); the
    /// ptr-eq check makes the steady state a cheap no-op that never dirties
    /// the pane. The reader thread picks a new set up on its next chunk; the
    /// render loop on its next frame.
    pub fn set_triggers(&self, set: std::sync::Arc<crate::triggers::TriggerSet>) {
        let mut cur = self.triggers.lock().unwrap();
        if std::sync::Arc::ptr_eq(&cur, &set) {
            return;
        }
        *cur = set;
        drop(cur);
        self.pty_dirty.store(true, Ordering::Release);
    }

    /// Notify/bell trigger firings recorded by the reader thread since the
    /// last drain.
    pub fn drain_trigger_hits(&self) -> Vec<crate::triggers::TriggerHit> {
        self.trigger_rx.try_iter().collect()
    }

    /// Swap in the global background-matcher set (#252), same steady-state
    /// no-op contract as [`Self::set_triggers`].
    pub fn set_watch_set(&self, set: std::sync::Arc<crate::problem_matchers::WatchSet>) {
        let mut cur = self.watch_set.lock().unwrap();
        if std::sync::Arc::ptr_eq(&cur, &set) {
            return;
        }
        *cur = set;
    }

    /// Assign (or clear) the task-specific background matcher for this
    /// pane — the `problemMatcher` of the task running here.
    pub fn set_pane_watch(
        &self,
        matcher: Option<std::sync::Arc<crate::problem_matchers::CompiledMatcher>>,
    ) {
        *self.pane_watch.lock().unwrap() = matcher;
    }

    /// Watch batches published by the reader thread since the last drain:
    /// the pane cwd at publish time plus the cycle's diagnostics (possibly
    /// empty — an empty batch is what clears fixed errors).
    #[allow(clippy::type_complexity)]
    pub fn drain_watch_batches(
        &self,
    ) -> Vec<(
        Option<std::path::PathBuf>,
        Vec<crate::build_matchers::BuildDiag>,
    )> {
        self.watch_rx.try_iter().collect()
    }

    /// Swap the ANSI palette the render loop maps Named/Indexed 0-15 cell
    /// colors through (the theme sync calls this every pass; unchanged
    /// palettes are a no-op so the pane never dirties spuriously).
    pub fn set_palette(&mut self, palette: [(u8, u8, u8); 16]) {
        if self.palette != palette {
            self.palette = palette;
            self.pty_dirty.store(true, Ordering::Release);
        }
    }

    /// Inline images captured from the pane's output, oldest first, each
    /// with its anchor's CURRENT grid line (drift model identical to command
    /// marks). Images whose anchor scrolled past the scrollback floor are
    /// garbage-collected here.
    pub fn pane_images(&self) -> Vec<PaneImage> {
        let mut term = self.term.lock();
        let now = self.clock.lock().unwrap().tick(&mut term);
        let floor = term.grid().topmost_line().0;
        drop(term);
        let mut imgs = self.images.lock().unwrap();
        imgs.retain(|m| m.line_rec - (now - m.clock_rec) as i32 >= floor);
        imgs.iter()
            .map(|m| PaneImage {
                seq: m.seq,
                data: m.data.clone(),
                line: m.line_rec - (now - m.clock_rec) as i32,
            })
            .collect()
    }

    /// Whether the pane is in the alternate screen (a full-screen app owns
    /// the viewport; anchored overlays make no sense there).
    pub fn alt_screen(&self) -> bool {
        self.term.lock().mode().contains(TermMode::ALT_SCREEN)
    }

    /// Whether the child enabled application cursor keys (DECCKM, `\e[?1h`).
    /// Arrows and Home/End must then arrive as SS3 (`\eOA`…) — the form
    /// terminfo advertises, and the only one apps that bind keys from
    /// terminfo (Python's REPL, less) recognize.
    pub fn app_cursor_keys(&self) -> bool {
        self.term.lock().mode().contains(TermMode::APP_CURSOR)
    }

    /// The viewport's scroll offset into history (0 = live bottom). Public
    /// so the app can map an anchor's grid line to a viewport row.
    pub fn scroll_display_offset(&self) -> i32 {
        self.display_offset()
    }

    /// Scroll the viewport so absolute grid line `abs_line` sits near the
    /// middle of the pane, clamped to the scrollback range. No-op in
    /// alternate screen, where there is no scrollback to move through and the
    /// whole grid is already on screen.
    pub fn scroll_to_line(&mut self, abs_line: i32) {
        let mut term = self.term.lock();
        if term.mode().contains(TermMode::ALT_SCREEN) {
            return;
        }
        let rows = term.screen_lines() as i32;
        let max_off = (-term.grid().topmost_line().0).max(0);
        let cur = term.grid().display_offset() as i32;
        let desired = scroll_offset_for_line(rows, max_off, abs_line);
        let delta = desired - cur;
        if delta != 0 {
            term.scroll_display(Scroll::Delta(delta));
        }
        drop(term);
        self.pty_dirty.store(true, Ordering::Release);
    }

    fn spawn_with(cmd: CommandBuilder, run_label: Option<String>) -> Result<Self> {
        Self::spawn_with_preamble(cmd, run_label, &[])
    }

    /// As [`Self::spawn_with`], but paints `preamble` into the grid before the
    /// reader thread starts, so restored output cannot interleave with the new
    /// shell's first prompt.
    fn spawn_with_preamble(
        mut cmd: CommandBuilder,
        run_label: Option<String>,
        preamble: &[u8],
    ) -> Result<Self> {
        apply_pane_env(
            &mut cmd,
            crate::view_ipc::SOCK_PATH.get().map(|p| p.as_path()),
        );
        // Not under test: the running binary there is the test harness, and
        // its link would land in the developer's real cache dir.
        if !cfg!(test) {
            apply_pane_bin(&mut cmd, pane_bin_dir().as_deref());
        }
        // An interactive shell may live in a pane host (#694); a task or
        // run pane is croft's own.
        let hosted = run_label.is_none() && persistent_panes_enabled();
        Self::spawn_from(PaneSource::Spawn { cmd, hosted }, run_label, preamble)
    }

    /// Reattach to the pane host at `socket` (#694): a pane whose shell
    /// outlived the croft that opened it. The host redraws the screen.
    pub fn attach_hosted(socket: &std::path::Path) -> Result<Self> {
        Self::spawn_from(PaneSource::Attach(socket.to_path_buf()), None, &[])
    }

    fn spawn_from(source: PaneSource, run_label: Option<String>, preamble: &[u8]) -> Result<Self> {
        let cols = 80u16;
        let rows = 24u16;
        let PaneLink {
            mut writer,
            mut reader,
            poll_fd: pty_fd,
            shell_pid,
            backend,
        } = PaneLink::open(source, cols, rows)?;
        let (input_tx, input_rx) = std::sync::mpsc::channel::<Vec<u8>>();
        // Ends once every sender is gone (the pane and its responder), or
        // when the child stops taking input.
        std::thread::spawn(move || {
            while let Ok(bytes) = input_rx.recv() {
                if writer.write_all(&bytes).is_err() || writer.flush().is_err() {
                    break;
                }
            }
        });

        let term_size = TermSize::new(cols as usize, rows as usize);
        let cfg = Config {
            // The user's `terminal_scrollback` (config.json) when set,
            // else the built-in default. Read per spawn so a settings edit
            // applies to the next pane without a relaunch.
            scrolling_history: crate::prefs::terminal_scrollback_lines(
                crate::prefs::Prefs::load_or_default().terminal_scrollback,
                SCROLLBACK_LINES,
            ),
            ..Config::default()
        };
        let size_shared = Arc::new(std::sync::Mutex::new((cols, rows)));
        let (response_tx, response_rx) = std::sync::mpsc::channel::<String>();
        let bell = Arc::new(AtomicBool::new(false));
        let clipboard_store = Arc::new(std::sync::Mutex::new(None));
        let listener = VoidListener {
            pty_response_tx: Some(response_tx),
            size: Some(size_shared.clone()),
            bell: Some(bell.clone()),
            clipboard: Some(clipboard_store.clone()),
        };
        let mut term = Term::new(cfg, &term_size, listener);
        // Before the reader thread exists, so nothing the child writes can
        // land ahead of the restored output (#249).
        if !preamble.is_empty() {
            Processor::<StdSyncHandler>::new().advance(&mut term, preamble);
        }
        let term = Arc::new(FairMutex::new(term));
        let term_for_thread = term.clone();
        let input_for_responder = input_tx.clone();

        std::thread::spawn(move || {
            while let Ok(text) = response_rx.recv() {
                if input_for_responder.send(text.into_bytes()).is_err() {
                    break;
                }
            }
        });

        let pty_dirty = Arc::new(AtomicBool::new(true));
        let pty_dirty_for_thread = pty_dirty.clone();
        let pty_pending_bytes = Arc::new(AtomicUsize::new(0));
        let pty_pending_bytes_for_thread = pty_pending_bytes.clone();
        // Seeded with the spawn time, not zero: a pane that has not output
        // yet is quiet since it STARTED, so a just-launched agent reads as
        // working for its first seconds rather than as idle since 1970.
        let last_output_ms = Arc::new(std::sync::atomic::AtomicU64::new(
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_millis() as u64)
                .unwrap_or(0),
        ));
        let last_output_ms_for_thread = last_output_ms.clone();
        let (port_tx, port_rx) = std::sync::mpsc::channel::<crate::port_detect::PortHit>();

        if let Some(label) = run_label.as_deref() {
            let header = format!("\x1b[2m▶ {label}\x1b[22m\r\n");
            let mut p = Processor::<StdSyncHandler>::new();
            let mut t = term.lock();
            p.advance(&mut *t, header.as_bytes());
        }

        let script_mode = run_label.is_some();

        let marks = Arc::new(std::sync::Mutex::new(Vec::<StoredMark>::new()));
        let marks_for_thread = marks.clone();
        let images = Arc::new(std::sync::Mutex::new(Vec::<StoredImage>::new()));
        let images_for_thread = images.clone();
        // Shutdown pipe + master fd for the reader's poll gate: the reader
        // must be wakeable without depending on the pty ever reaching EOF.
        let (shutdown_r, shutdown_w) = std::io::pipe().context("shutdown pipe")?;
        // Taken BEFORE the rewind registration below, which has no `?` after
        // it: an early return past a registered buffer would leave every
        // other pane trimmed to a share nobody is using.
        // One budget shared by every pane (#694), re-read per spawn like the
        // scrollback so a settings edit applies without a relaunch. Setting
        // it re-splits the budget over the panes already open; registering
        // then trims them to the smaller share before this pane records.
        let rewind_budget = crate::rewind::budget();
        let rewind_mb = crate::prefs::Prefs::load_or_default().terminal_rewind_mb;
        // Off by default until it can be replayed (#1342), but the recorder's
        // own tests drive it through real panes, and every spawn sets the one
        // shared total: test panes all record under the same explicit figure
        // rather than one turning it off under another.
        #[cfg(test)]
        let rewind_mb = rewind_mb.or(Some(128));
        rewind_budget.set_total(crate::rewind::configured_budget_bytes(rewind_mb));
        let rewind = rewind_budget.register();
        let rewind_for_thread = rewind.clone();
        // MONOTONIC, not the wall clock. Every read the buffer offers —
        // `span_ms`, `replay_from`, the orphan-keyframe sweep — assumes the
        // frames are ordered by `at_ms`, and `SystemTime` can step backwards
        // across an NTP correction or a manual set. A frame recorded during
        // such a step lands before its predecessors and becomes unreachable
        // through the only read API there is, which is a silent loss rather
        // than a visible fault. `Instant` cannot go backwards.
        let rewind_epoch = std::time::Instant::now();
        let (finished_tx, finished_rx) = std::sync::mpsc::channel::<FinishedCommand>();
        #[cfg(test)]
        let finished_tx_for_test = finished_tx.clone();
        let osc7_cwd = Arc::new(std::sync::Mutex::new(Option::<std::path::PathBuf>::None));
        let osc7_for_thread = osc7_cwd.clone();
        let notifications = Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
        let notifications_for_thread = notifications.clone();
        let progress = Arc::new(std::sync::Mutex::new(None::<(u8, u8)>));
        let progress_for_thread = progress.clone();
        let line_times = Arc::new(std::sync::Mutex::new(
            std::collections::BTreeMap::<i64, u64>::new(),
        ));
        let line_times_for_thread = line_times.clone();
        let clock = Arc::new(std::sync::Mutex::new(ScrollClock::new()));
        let clock_for_thread = clock.clone();
        let osc7_host = Arc::new(std::sync::Mutex::new(None::<String>));
        let osc7_host_for_thread = osc7_host.clone();
        // Trigger set shared with the reader thread; the inner Arc is swapped
        // by `set_triggers` on startup / config reload, picked up per chunk.
        let triggers = Arc::new(std::sync::Mutex::new(std::sync::Arc::new(
            crate::triggers::TriggerSet::default(),
        )));
        let triggers_for_thread = triggers.clone();
        let (trigger_tx, trigger_rx) = std::sync::mpsc::channel::<crate::triggers::TriggerHit>();
        let watch_set = Arc::new(std::sync::Mutex::new(std::sync::Arc::new(
            crate::problem_matchers::WatchSet::default(),
        )));
        let watch_set_for_thread = watch_set.clone();
        let pane_watch = Arc::new(std::sync::Mutex::new(
            None::<std::sync::Arc<crate::problem_matchers::CompiledMatcher>>,
        ));
        let pane_watch_for_thread = pane_watch.clone();
        let (watch_tx, watch_rx) = std::sync::mpsc::channel::<(
            Option<std::path::PathBuf>,
            Vec<crate::build_matchers::BuildDiag>,
        )>();

        let reader_thread = std::thread::spawn(move || {
            let mut processor = Processor::<StdSyncHandler>::new();
            let mut port_sniffer = crate::port_detect::PortSniffer::new();
            let mut osc_sniffer = crate::shell_integration::OscSniffer::default();
            let mut wipe_sniffer = WipeSniffer::default();
            let mut trigger_scanner = crate::triggers::TriggerScanner::new();
            let mut trigger_hits = Vec::new();
            let mut watch_engine = crate::problem_matchers::WatchEngine::default();
            let mut watch_lines: Vec<String> = Vec::new();
            // Last-seen matcher sources, for detecting a swap mid-window
            // (Arc identity — the app only ever replaces them wholesale).
            let mut last_wset = watch_set_for_thread.lock().unwrap().clone();
            // The engine starts with no task matcher, whatever the slot
            // holds by the time this thread runs: a task assigned to a new
            // pane before its first read must still count as an assignment,
            // or its matcher is never armed (#1541).
            let mut last_pwatch: Option<Arc<crate::problem_matchers::CompiledMatcher>> = None;
            // Per-pane monotonic id for captured inline images; the overlay
            // layout key uses it to tell a new picture from a moved one.
            let mut image_seq = 0u64;
            // Content id of the cursor row after the previous chunk: the
            // rows this chunk touched run from there to the cursor's new
            // id, and each takes the chunk's arrival time (last touch wins,
            // so a row is stamped when its content actually landed, not
            // when the cursor first parked on it).
            let mut prev_stamp_id: i64 = 0;
            // Started by 133;C, finished by the next 133;D.
            let mut running: Option<RunningCommand> = None;
            let mut buf = [0u8; 65536];
            loop {
                // A dev-server URL that ended the last read is held back in
                // case the next read extends it; when the output goes quiet
                // instead, it is sent as it stands (#1449).
                let ready = if port_sniffer.has_pending() {
                    match poll_pty(pty_fd, &shutdown_r, PORT_URL_SETTLE_MS) {
                        PtyWait::Ready => true,
                        PtyWait::Closed => false,
                        PtyWait::Idle => {
                            port_sniffer.flush(&port_tx);
                            continue;
                        }
                    }
                } else {
                    match wait_pty_readable(pty_fd, &shutdown_r, watch_engine.deadline()) {
                        PtyWait::Ready => true,
                        PtyWait::Closed => false,
                        PtyWait::Idle => {
                            // A task matcher's grace ran out with no shell
                            // mark (#1541): its held lines are output after
                            // all.
                            let wset = watch_set_for_thread.lock().unwrap().clone();
                            let pwatch = pane_watch_for_thread.lock().unwrap().clone();
                            let batches = watch_engine.expire(
                                std::time::Instant::now(),
                                &wset,
                                pwatch.as_ref(),
                            );
                            for batch in batches {
                                let cwd = osc7_for_thread.lock().unwrap().clone();
                                let _ = watch_tx.send((cwd, batch));
                            }
                            continue;
                        }
                    }
                };
                if !ready {
                    break;
                }
                match reader.read(&mut buf) {
                    Ok(0) => break,
                    Ok(n) => {
                        port_sniffer.sniff(&buf[..n], &port_tx);
                        // Shell-integration marks: split the advance at each
                        // OSC 133 so the cursor can be sampled exactly where
                        // the mark landed (alacritty drops the sequences
                        // themselves as unknown OSC).
                        let osc_events = osc_sniffer.scan(&buf[..n]);
                        // Where the shell's prompt and command marks fall in
                        // the chunk, for the watch engine below (#1541): the
                        // lines before a task's `133;C` are the shell echoing
                        // its command line, not its output.
                        let watch_marks: Vec<(usize, bool)> = osc_events
                            .iter()
                            .filter_map(|(end, ev)| {
                                use crate::shell_integration::OscEvent as E;
                                match ev {
                                    E::CommandStart => Some((*end, true)),
                                    E::PromptStart | E::PromptEnd | E::CommandEnd(_) => {
                                        Some((*end, false))
                                    }
                                    _ => None,
                                }
                            })
                            .collect();
                        let mut t = term_for_thread.lock();
                        let wipes =
                            wipe_sniffer.scan(&buf[..n], t.mode().contains(TermMode::ALT_SCREEN));
                        let screen_wiped = wipes.iter().any(|w| w.screen);
                        let hist_wiped = wipes.iter().any(|w| w.hist);
                        // The parser also stops at each wipe, so the running
                        // command's output start is moved right where a
                        // wipe erased its row, before the scroll clock
                        // loses count of what scrolls after it (#876).
                        let mut stops: Vec<(usize, ReadStop)> = osc_events
                            .into_iter()
                            .map(|(end, ev)| (end, ReadStop::Mark(ev)))
                            .chain(wipes.into_iter().map(|w| (w.end, ReadStop::Wipe(w))))
                            .collect();
                        stops.sort_by_key(|(end, _)| *end);
                        // Record the WHOLE read, before the OSC split below.
                        // The loop advances the parser per segment and leaves
                        // `done` at the LAST mark, so recording `buf[done..n]`
                        // afterwards kept only the tail — with shell
                        // integration on, marks arrive around every prompt and
                        // command, so most of the session was parsed to the
                        // screen and never recorded. That is the one thing
                        // this buffer exists to prevent, and the pty test
                        // covering it could not see the bug because its script
                        // emitted no marks (fixed: the OSC variant alongside
                        // it fails without this).
                        //
                        // Still recorded BEFORE the advance, so the buffer
                        // holds the bytes that PRODUCED the state a keyframe
                        // would capture. Takes only its own lock: the pane's
                        // order is term -> clock -> line_times and `t` is held
                        // here, so anything reaching back for `term` would
                        // deadlock — `push` returns a keyframe request rather
                        // than rendering one for exactly that reason.
                        // Poisons independently of `term` (std Mutex vs
                        // alacritty's FairMutex): a panic taken under this
                        // lock disables recording for the pane's life, and the
                        // `if let Ok` degrades to silence rather than
                        // propagating. Acceptable for a cache, but not the
                        // same failure mode as `term`'s.
                        if let Ok(mut rb) = rewind_for_thread.lock() {
                            let at = rewind_epoch.elapsed().as_millis() as u64;
                            // The keyframe request is dropped for now: this is
                            // the recording half, and nothing replays yet. The
                            // overlay that does will honour it here, taking the
                            // screen while it holds `t` rather than reaching
                            // back for the lock. Until then the buffer replays
                            // from the start, which is correct but unbounded.
                            let _wants_keyframe = rb.push(at, &buf[..n]);
                        }
                        let mut done = 0usize;
                        for (end, stop) in stops {
                            processor.advance(&mut *t, &buf[done..end]);
                            done = end;
                            let ev = match stop {
                                ReadStop::Mark(ev) => ev,
                                ReadStop::Wipe(w) => {
                                    if let Some(run) = running.as_mut() {
                                        let now = clock_for_thread.lock().unwrap().tick(&mut t);
                                        run.follow_wipe(w, now);
                                    }
                                    continue;
                                }
                            };
                            use crate::shell_integration::OscEvent as E;
                            match ev {
                                E::Cwd(p, host) => {
                                    *osc7_for_thread.lock().unwrap() = Some(p);
                                    *osc7_host_for_thread.lock().unwrap() = host;
                                }
                                E::Notify(msg) => {
                                    notifications_for_thread.lock().unwrap().push(msg);
                                }
                                E::Progress(state, pct) => {
                                    // State 0 clears; the rest hold the latest
                                    // (state, percent) for the border gauge.
                                    *progress_for_thread.lock().unwrap() =
                                        (state != 0).then_some((state, pct));
                                }
                                E::InlineImage(data) => {
                                    // Anchor the picture at the cursor's grid
                                    // position, keyed on the scroll clock like
                                    // an annotation (lock order term → clock).
                                    let line_rec = t.grid().cursor.point.line.0;
                                    let clock_rec = clock_for_thread.lock().unwrap().tick(&mut t);
                                    let mut imgs = images_for_thread.lock().unwrap();
                                    if imgs.len() >= IMAGES_MAX {
                                        let drop_n = imgs.len() + 1 - IMAGES_MAX;
                                        imgs.drain(..drop_n);
                                    }
                                    image_seq += 1;
                                    imgs.push(StoredImage {
                                        seq: image_seq,
                                        data: std::sync::Arc::new(data),
                                        line_rec,
                                        clock_rec,
                                    });
                                }
                                kind @ (E::PromptStart
                                | E::PromptEnd
                                | E::CommandStart
                                | E::CommandEnd(_)) => {
                                    let dur = match &kind {
                                        E::CommandEnd(exit) => {
                                            // A finished command's gauge is
                                            // stale even if the program never
                                            // sent the state-0 clear.
                                            *progress_for_thread.lock().unwrap() = None;
                                            running.take().map(|run| {
                                                let dur = run.started.elapsed();
                                                // The typed command text and the
                                                // shell's cwd travel with the
                                                // completion so the durable
                                                // history records context.
                                                let now =
                                                    clock_for_thread.lock().unwrap().tick(&mut t);
                                                let start =
                                                    run.out_line - (now - run.out_clock) as i32;
                                                let output = command_output_text(&t, start);
                                                let cwd = osc7_for_thread.lock().unwrap().clone();
                                                let host =
                                                    osc7_host_for_thread.lock().unwrap().clone();
                                                let _ = finished_tx.send(FinishedCommand {
                                                    exit: *exit,
                                                    dur,
                                                    cmd: run.typed,
                                                    cwd,
                                                    host,
                                                    output,
                                                });
                                                dur
                                            })
                                        }
                                        _ => None,
                                    };
                                    let line_rec = t.grid().cursor.point.line.0;
                                    let clock_rec = clock_for_thread.lock().unwrap().tick(&mut t);
                                    let col_rec = t.grid().cursor.point.column.0;
                                    let started = matches!(kind, E::CommandStart);
                                    let mut ms = marks_for_thread.lock().unwrap();
                                    if ms.len() >= MARKS_MAX {
                                        let drop_n = ms.len() + 1 - MARKS_MAX;
                                        ms.drain(..drop_n);
                                    }
                                    ms.push(StoredMark {
                                        id: next_mark_id(),
                                        kind,
                                        line_rec,
                                        clock_rec,
                                        col_rec,
                                        dur,
                                    });
                                    // Read the typed line now, while it is
                                    // still on screen: the command may clear
                                    // it before its 133;D (#876).
                                    if started {
                                        running = Some(RunningCommand {
                                            started: std::time::Instant::now(),
                                            typed: last_command_input_text(&t, &ms, clock_rec),
                                            out_line: line_rec,
                                            out_clock: clock_rec,
                                        });
                                    }
                                }
                            }
                        }
                        processor.advance(&mut *t, &buf[done..n]);
                        // A destructive clear erases the content the pane's
                        // captured images anchored to: ED 2 the live screen
                        // rows, ED 3 the scrollback ones, RIS both. The
                        // sniffer already excluded wipes that landed inside
                        // the alt screen (positional tracking), so no mode
                        // check here — the chunk's FINAL mode says nothing
                        // about where a wipe fell (`clear && vim`).
                        if screen_wiped || hist_wiped {
                            let now = clock_for_thread.lock().unwrap().tick(&mut t);
                            let erased = |line_rec: i32, clock_rec: i64| {
                                let line = line_rec - (now - clock_rec) as i32;
                                if line >= 0 { screen_wiped } else { hist_wiped }
                            };
                            images_for_thread
                                .lock()
                                .unwrap()
                                .retain(|m| !erased(m.line_rec, m.clock_rec));
                            // Marks anchored to erased content go the same
                            // way: a stale decoration dot's menu copies or
                            // re-runs whatever later lands on its row.
                            marks_for_thread
                                .lock()
                                .unwrap()
                                .retain(|m| !erased(m.line_rec, m.clock_rec));
                        }
                        // Stamp newly-arrived rows for the timestamps gutter:
                        // every row the cursor moved past in this chunk gets
                        // the chunk's arrival time (one read of output is
                        // sub-millisecond, so chunk granularity is honest).
                        {
                            let now_ms = std::time::SystemTime::now()
                                .duration_since(std::time::UNIX_EPOCH)
                                .map(|d| d.as_millis() as u64)
                                .unwrap_or(0);
                            let mut clock = clock_for_thread.lock().unwrap();
                            let mut lt = line_times_for_thread.lock().unwrap();
                            stamp_chunk(&mut t, &mut clock, &mut lt, &mut prev_stamp_id, now_ms);
                        }
                        // Notify/bell triggers match completed output lines,
                        // never inside a full-screen app (the alt screen owns
                        // the bytes; iTerm2 skips those too). The scanner
                        // tracks the alt boundary POSITIONALLY from the
                        // stream — the chunk's final mode says nothing about
                        // where a line fell — so it must see EVERY chunk, or
                        // its alt tracking and string state machine desync
                        // and skipped-gap output splices into phantom lines.
                        let trig = triggers_for_thread.lock().unwrap().clone();
                        // Watch problem matchers (#252) ride the same
                        // scanner: when any are configured, the completed
                        // lines it already produces feed the per-pane watch
                        // engine (no second byte scan over the stream).
                        let wset = watch_set_for_thread.lock().unwrap().clone();
                        let pwatch = pane_watch_for_thread.lock().unwrap().clone();
                        // Matcher ownership changed since the last chunk
                        // (matchers.json reload, task (re)assignment):
                        // drop any half-open window, or its next `ends`
                        // would scan stale lines with the OLD matcher and
                        // publish a stale batch.
                        let pwatch_same = match (&pwatch, &last_pwatch) {
                            (Some(a), Some(b)) => Arc::ptr_eq(a, b),
                            (None, None) => true,
                            _ => false,
                        };
                        // A newly assigned task matcher waits for its
                        // command's output to start (#1541). A swapped
                        // global set only matters to a pane with no task
                        // matcher: the task's matcher owns its pane's
                        // windows, and dropping one here lost the task's
                        // first cycle whenever the app's first sync of the
                        // global set landed mid-build.
                        if !pwatch_same {
                            watch_engine.assign(pwatch.as_ref(), std::time::Instant::now());
                        } else if !Arc::ptr_eq(&wset, &last_wset) && pwatch.is_none() {
                            watch_engine.reset();
                        }
                        last_wset = wset.clone();
                        last_pwatch = pwatch.clone();
                        if wset.matchers.is_empty() && pwatch.is_none() {
                            trigger_scanner.scan(&buf[..n], &trig, &mut trigger_hits);
                        } else {
                            // Scanned up to each mark, then the mark, so the
                            // engine sees them in stream order.
                            let mut from = 0usize;
                            let ends = watch_marks.iter().map(|&(end, c)| (end, Some(c)));
                            for (end, mark) in ends.chain(std::iter::once((n, None))) {
                                watch_lines.clear();
                                trigger_scanner.scan_collect(
                                    &buf[from..end],
                                    &trig,
                                    &mut trigger_hits,
                                    Some(&mut watch_lines),
                                );
                                from = end;
                                for line in watch_lines.drain(..) {
                                    if let Some(batch) =
                                        watch_engine.feed(&line, &wset, pwatch.as_ref())
                                    {
                                        let cwd = osc7_for_thread.lock().unwrap().clone();
                                        let _ = watch_tx.send((cwd, batch));
                                    }
                                }
                                if let Some(command_start) = mark {
                                    watch_engine.mark(command_start, pwatch.as_ref());
                                }
                            }
                        }
                        for h in trigger_hits.drain(..) {
                            let _ = trigger_tx.send(h);
                        }
                        drop(t);
                        pty_pending_bytes_for_thread.fetch_add(n, Ordering::Relaxed);
                        last_output_ms_for_thread.store(
                            std::time::SystemTime::now()
                                .duration_since(std::time::UNIX_EPOCH)
                                .map(|d| d.as_millis() as u64)
                                .unwrap_or(0),
                            Ordering::Relaxed,
                        );
                        pty_dirty_for_thread.store(true, Ordering::Release);
                    }
                    Err(_) => break,
                }
            }
            if script_mode {
                let footer = b"\r\n\x1b[2m[Process exited]\x1b[22m\r\n";
                let mut t = term_for_thread.lock();
                processor.advance(&mut *t, footer);
                drop(t);
                pty_dirty_for_thread.store(true, Ordering::Release);
            }
        });

        Ok(Self {
            term,
            pty_dirty,
            pty_pending_bytes,
            last_output_ms,
            agent: None,
            port_rx,
            backend,
            input_tx,
            reader_thread: Some(reader_thread),
            reader_shutdown: Some(shutdown_w),
            shell_pid,
            exit: None,
            reaped_at: None,
            uid: {
                static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
                NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
            },
            input_seen: false,
            last_input_ms: 0,
            run_pane: script_mode,
            manual_name_seen: false,
            cols,
            rows,
            size_shared,
            focused: false,
            broadcast_excluded: false,
            collapsed: false,
            focus_gradient: false,
            theme: crate::theme::Theme::default(),
            last_area: Rect::default(),
            last_inner: Rect::default(),
            selection: None,
            copy_cursor: None,
            sel_scrolled: 0,
            clock,
            alt_sel: None,
            drag_selecting: false,
            manual_name: None,
            auto_label: String::new(),
            search_needle: None,
            search_opts: crate::widgets::search::SearchOpts::default(),
            current_match: None,
            bell,
            clipboard_store,
            marks,
            osc7_cwd,
            osc7_host,
            accent: None,
            accent_badge: None,
            notifications,
            progress,
            line_times,
            show_timestamps: false,
            reveal_redactions: false,
            redacted_on_screen: 0,
            annotations: Vec::new(),
            finished_rx,
            hints: None,
            triggers,
            trigger_rx,
            watch_set,
            pane_watch,
            watch_rx,
            palette: crate::theme::VSCODE_ANSI,
            images,
            rewind,
            #[cfg(test)]
            written_for_test: Arc::new(std::sync::Mutex::new(Vec::new())),
            #[cfg(test)]
            finished_tx_for_test,
        })
    }

    /// OSC 133 marks with their *current* grid line (negative = scrollback),
    /// oldest first. Marks whose content scrolled past the scrollback floor
    /// are garbage-collected here.
    pub fn command_marks(&self) -> Vec<(crate::shell_integration::OscEvent, i32)> {
        self.marks_snapshot()
            .into_iter()
            .map(|m| (m.kind, m.line))
            .collect()
    }

    /// The marks with current grid lines and, for `CommandEnd`, the measured
    /// command duration. GC + drift adjustment as in [`Self::command_marks`].
    fn marks_snapshot(&self) -> Vec<MarkView> {
        let mut term = self.term.lock();
        let now = self.clock.lock().unwrap().tick(&mut term);
        let floor = term.grid().topmost_line().0;
        drop(term);
        let mut marks = self.marks.lock().unwrap();
        marks.retain(|m| m.line_rec - (now - m.clock_rec) as i32 >= floor);
        marks
            .iter()
            .map(|m| MarkView {
                id: m.id,
                kind: m.kind.clone(),
                line: m.line_rec - (now - m.clock_rec) as i32,
                col: m.col_rec,
                dur: m.dur,
            })
            .collect()
    }

    /// One record per finished command, for the gutter decorations: prompt
    /// line (current grid coords), exit code, duration.
    pub fn command_decorations(&self) -> Vec<CommandDecoration> {
        pair_decorations(&self.marks_snapshot())
    }

    /// Finished commands since the last drain: (exit code, duration). Feeds
    /// the status-bar notification for long commands in unfocused panes.
    pub fn drain_finished_commands(&self) -> Vec<FinishedCommand> {
        self.finished_rx.try_iter().collect()
    }

    /// The text a finished command printed: its output span (`output_start`
    /// up to but excluding `output_end`), trailing blank lines dropped.
    pub fn command_output_text(&self, d: &CommandDecoration) -> String {
        if d.output_end <= d.output_start {
            return String::new();
        }
        let term = self.term.lock();
        extract_selection_text(
            &term,
            d.output_start,
            0,
            d.output_end - 1,
            term.columns().saturating_sub(1),
        )
    }

    /// The command as it was typed at its prompt: from the `PromptEnd`
    /// mark's cell to the end of the input rows (the row before the output
    /// starts), soft-wrapped rows joined.
    pub fn command_input_text(&self, d: &CommandDecoration) -> String {
        let Some((line, col)) = d.input else {
            return String::new();
        };
        if d.output_start <= line {
            return String::new();
        }
        let term = self.term.lock();
        without_continuation_prompts(&extract_selection_text(
            &term,
            line,
            col,
            d.output_start - 1,
            term.columns().saturating_sub(1),
        ))
    }

    /// Select the command's output span (and snap the view to it), so the
    /// user sees exactly what Copy Output grabbed. No-op for empty output.
    pub fn select_command_output(&mut self, d: &CommandDecoration) {
        if d.output_end <= d.output_start {
            return;
        }
        self.selection = Some(Selection {
            anchor: (d.output_start, 0),
            head: (d.output_end - 1, self.cols.saturating_sub(1)),
            block: false,
        });
        self.stamp_selection_clock();
        self.scroll_to_line(d.output_start);
    }

    /// The decoration whose gutter dot sits at screen cell (col, row), if
    /// any: col must be the pane's left border column and row a viewport
    /// row whose grid line carries a finished command.
    pub fn decoration_at_screen(&self, col: u16, row: u16) -> Option<CommandDecoration> {
        let inner = self.last_inner;
        if col != self.last_area.x || row < inner.y || row >= inner.y + inner.height {
            return None;
        }
        let term = self.term.lock();
        if term.mode().contains(TermMode::ALT_SCREEN) {
            return None;
        }
        let display_offset = term.grid().display_offset() as i32;
        drop(term);
        let line = i32::from(row - inner.y) - display_offset;
        self.command_decorations()
            .into_iter()
            .find(|d| d.line == line)
    }

    /// Current grid lines of the PromptStart marks — the Cmd+Up/Cmd+Down
    /// navigation targets.
    pub fn prompt_lines(&self) -> Vec<i32> {
        self.command_marks()
            .into_iter()
            .filter(|(kind, _)| *kind == crate::shell_integration::OscEvent::PromptStart)
            .map(|(_, line)| line)
            .collect()
    }

    /// The shell's live cwd per its latest OSC 7 report, when shell
    /// integration is active. Fresher than sampling `cwd_of_pid`.
    pub fn shell_cwd(&self) -> Option<std::path::PathBuf> {
        self.osc7_cwd.lock().unwrap().clone()
    }

    /// The kernel-reported cwd of the pane's shell process. Unlike
    /// [`Self::shell_cwd`] it needs no shell integration, so it answers for
    /// any local pane; `None` when the pid or the kernel query is
    /// unavailable (android, a dead shell, a remote pane's ssh process).
    pub fn kernel_shell_cwd(&self) -> Option<std::path::PathBuf> {
        cwd_of_pid(u32::try_from(self.shell_pid?).ok()?)
    }

    /// OSC 9 notification payloads since the last drain.
    pub fn drain_notifications(&self) -> Vec<String> {
        std::mem::take(&mut *self.notifications.lock().unwrap())
    }

    /// The viewport-top grid line: what `pick_prompt_jump` navigates from.
    pub fn viewport_top_line(&self) -> i32 {
        -(self.term.lock().grid().display_offset() as i32)
    }

    /// Scroll so absolute grid line `abs_line` sits at the top of the pane
    /// (VS Code parks the jumped-to command at the top). No-op in alternate
    /// screen, like the other scrollback moves.
    pub fn scroll_line_to_top(&mut self, abs_line: i32) {
        let mut term = self.term.lock();
        if term.mode().contains(TermMode::ALT_SCREEN) {
            return;
        }
        let max_off = (-term.grid().topmost_line().0).max(0);
        let desired = (-abs_line).clamp(0, max_off);
        let delta = desired - term.grid().display_offset() as i32;
        if delta != 0 {
            term.scroll_display(Scroll::Delta(delta));
        }
        drop(term);
        self.pty_dirty.store(true, Ordering::Release);
    }

    /// True once if the child rang BEL since the last call (drains the latch).
    pub fn take_bell(&self) -> bool {
        self.bell.swap(false, Ordering::AcqRel)
    }

    /// The text the child last copied through OSC 52 since the previous
    /// call, if any (drains the latch). Only the newest copy survives a
    /// tick: the clipboard holds one value, so older ones were overwritten
    /// anyway.
    pub fn take_clipboard_store(&self) -> Option<String> {
        self.clipboard_store.lock().unwrap().take()
    }

    /// The pane's foreground process group leader pid (what owns the tty now):
    /// the shell at a prompt, or a running command. `None` if unavailable.
    pub fn foreground_pid(&self) -> Option<i32> {
        self.backend.process_group_leader()
    }

    /// The shell's own pid, stable for this pane's lifetime (the key the app
    /// uses to match async label lookups back to the right pane).
    pub fn shell_pid(&self) -> Option<i32> {
        self.shell_pid
    }

    /// The label to show for this pane: manual name if set, else the live
    /// foreground-process label.
    pub fn label(&self) -> &str {
        pick_pane_label(self.manual_name.as_deref(), &self.auto_label)
    }

    /// Set the foreground-process label (from the off-loop refresh).
    pub fn set_auto_label(&mut self, label: String) {
        self.auto_label = label;
    }

    /// Whether input was written that the shell has not echoed yet, so the
    /// prompt line on screen lags what was typed.
    pub fn awaiting_echo(&self) -> bool {
        self.last_input_ms > self.last_output_ms.load(Ordering::Relaxed)
    }

    /// How long since the PTY last produced output; a pane that never has is
    /// quiet since it was spawned.
    pub fn quiet_for(&self) -> std::time::Duration {
        let last = self.last_output_ms.load(Ordering::Relaxed);
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_millis() as u64)
            .unwrap_or(0);
        std::time::Duration::from_millis(now.saturating_sub(last))
    }

    /// The agent seated in this pane, if the last sample found one (#344).
    pub fn agent(&self) -> Option<&crate::agents::AgentLane> {
        self.agent.as_ref()
    }

    pub fn set_agent(&mut self, lane: Option<crate::agents::AgentLane>) {
        self.agent = lane;
    }

    /// The last `n` non-empty VISIBLE rows, oldest first, for prompt
    /// matching. Reads the viewport only: the whole scrollback is what
    /// `grid_lines` walks, and a prompt is on screen or it is not there.
    pub fn tail_rows(&self, n: usize) -> Vec<String> {
        let text = self.visible_text();
        let mut rows: Vec<String> = text
            .lines()
            .rev()
            .filter(|l| !l.trim().is_empty())
            .take(n)
            .map(|l| l.trim_end().to_string())
            .collect();
        rows.reverse();
        rows
    }

    /// The user's manual pane name, when one was set via rename (what the
    /// session snapshot persists; `label()` mixes in the auto label).
    pub fn manual_name(&self) -> Option<&str> {
        self.manual_name.as_deref()
    }

    /// Set or clear the user's manual pane name (a blank name clears it).
    pub fn set_manual_name(&mut self, name: Option<String>) {
        self.manual_name = name.filter(|n| !n.trim().is_empty());
        if self.manual_name.is_some() {
            self.manual_name_seen = true;
        }
    }

    pub fn take_dirty(&self) -> bool {
        self.pty_pending_bytes.store(0, Ordering::Relaxed);
        self.pty_dirty.swap(false, Ordering::AcqRel)
    }

    /// The pane's live OSC 9;4 progress `(state, percent)`, if a program is
    /// reporting one.
    pub fn progress(&self) -> Option<(u8, u8)> {
        *self.progress.lock().unwrap()
    }

    /// What has been typed at the shell prompt, when the cursor sits at its
    /// end (#614): `(typed, cursor screen x, cursor screen y, pane right
    /// edge)`. `None` unless the newest shell-integration mark is the prompt
    /// end on the cursor's own row, the view is live (not scrolled back, not
    /// a full-screen program), and nothing is drawn right of the cursor.
    /// That last rule is what keeps croft out of the way of a shell drawing
    /// its own suggestion (fish, zsh-autosuggestions), which lands there.
    pub fn prompt_tail(&self) -> Option<(String, u16, u16, u16)> {
        let term = self.term.lock();
        if term.mode().contains(TermMode::ALT_SCREEN) || term.grid().display_offset() != 0 {
            return None;
        }
        let cursor = term.grid().cursor.point;
        let line = cursor.line.0;
        let now = self.clock_now(&term);
        let ms = self.marks.lock().unwrap();
        let last = ms.last()?;
        if !matches!(last.kind, crate::shell_integration::OscEvent::PromptEnd)
            || last.line_rec - (now - last.clock_rec) as i32 != line
        {
            return None;
        }
        let (text, colmap) = row_text_and_cols(&term, line);
        let cur = cursor.column.0;
        let b_col = last.col_rec;
        // Characters at or right of the cursor: must be none.
        if colmap
            .iter()
            .zip(text.chars())
            .any(|(&c, ch)| c >= cur && !ch.is_whitespace())
        {
            return None;
        }
        let typed: String = colmap
            .iter()
            .zip(text.chars())
            .filter(|(c, _)| **c >= b_col && **c < cur)
            .map(|(_, ch)| ch)
            .collect();
        let inner = self.last_inner;
        if inner.width == 0 || line < 0 || line as u16 >= inner.height {
            return None;
        }
        Some((
            typed,
            inner.x + cur as u16,
            inner.y + line as u16,
            inner.x + inner.width,
        ))
    }

    /// The shell cursor's screen cell, when it is on screen and the program
    /// hasn't hidden it (#621: screen reader mode parks the cursor here).
    pub fn screen_cursor(&self) -> Option<(u16, u16)> {
        let term = self.term.lock();
        if !term.mode().contains(TermMode::SHOW_CURSOR) || term.grid().display_offset() != 0 {
            return None;
        }
        let p = term.grid().cursor.point;
        let inner = self.last_inner;
        let (line, col) = (p.line.0, p.column.0 as u16);
        if inner.width == 0 || line < 0 || line as u16 >= inner.height || col >= inner.width {
            return None;
        }
        Some((inner.x + col, inner.y + line as u16))
    }

    /// The arrow-key bytes a plain click at screen cell (col, row) should
    /// send to walk the shell cursor to the clicked column (Ghostty's
    /// click-to-move-cursor). `Some` only when the shell is sitting at a
    /// prompt (the newest OSC 133 mark is B, on this same row), the click
    /// lands on the cursor's own row, and the target cell differs from the
    /// cursor. The target clamps to the typed span: never left of where
    /// input starts, never past one cell after the row's last glyph. The
    /// line itself is untouched — only cursor motion is synthesized, so it
    /// works identically in zsh, bash, and fish line editors.
    pub fn prompt_click_arrows(&self, col: u16, row: u16) -> Option<Vec<u8>> {
        let (vr, vc) = self.cell_at(col, row)?;
        let term = self.term.lock();
        if term.mode().contains(TermMode::ALT_SCREEN) {
            return None;
        }
        let off = term.grid().display_offset() as i32;
        let line = vr as i32 - off;
        let cursor = term.grid().cursor.point;
        if line != cursor.line.0 {
            return None;
        }
        let now = self.clock_now(&term);
        let ms = self.marks.lock().unwrap();
        let last = ms.last()?;
        if !matches!(last.kind, crate::shell_integration::OscEvent::PromptEnd) {
            return None;
        }
        if last.line_rec - (now - last.clock_rec) as i32 != line {
            return None;
        }
        let b_col = last.col_rec as u16;
        let (text, colmap) = row_text_and_cols(&term, line);
        let chars = text.trim_end().chars().count();
        let end_col = if chars == 0 {
            b_col
        } else {
            colmap
                .get(chars - 1)
                .map(|&c| c as u16 + 1)
                .unwrap_or(b_col)
        };
        let cur = cursor.column.0 as u16;
        // The row may have been rewritten SHORTER than the recorded 133;B
        // column (a backgrounded progress writer, a shrunk pane): the live
        // bounds then sit left of `b_col`, and `clamp` with min > max
        // panics. Bound the lower edge by the upper so the gesture
        // degrades instead of taking the app down.
        let hi = end_col.max(cur);
        let target = vc.clamp(b_col.min(hi), hi);
        if target == cur {
            return None;
        }
        let (seq, n) = if target > cur {
            (b"\x1b[C".as_slice(), target - cur)
        } else {
            (b"\x1b[D".as_slice(), cur - target)
        };
        Some(seq.repeat(n as usize))
    }

    /// The hostname the shell last reported over OSC 7 (an in-pane SSH
    /// session with integration moves it to the remote host).
    pub fn shell_host(&self) -> Option<String> {
        self.osc7_host.lock().unwrap().clone()
    }

    /// [`Self::shell_cwd`], trusted only when the report provably applies
    /// to the LOCAL shell: the reporting host must be this machine (empty,
    /// "localhost", or the local hostname — RFC 8089 semantics via the
    /// command history's canonicalizer) AND the claimed path must name the
    /// directory the kernel says the shell is in ([`cwd_of_pid`]). PTY
    /// bytes carry no author — any foreground job can print a
    /// local-looking claim and die before the bytes are even parsed — so
    /// no tty-ownership sample at any moment establishes provenance.
    /// Matching the kernel's ground truth does: a forged claim equal to
    /// the truth grants nothing, and one that differs is rejected. The
    /// cost is that platforms without [`cwd_of_pid`] never trust a claim.
    pub fn local_shell_cwd(&self) -> Option<std::path::PathBuf> {
        let host = self.shell_host().unwrap_or_default();
        if !crate::command_history::is_local_host(&host) {
            return None;
        }
        let claim = self.shell_cwd()?;
        let real = cwd_of_pid(self.pid()?)?;
        // Symlink-tolerant equality (macOS reports /private/tmp for a
        // shell sitting in /tmp): equal canonical paths name the same
        // directory, so a claim passing this check cannot mislead.
        (claim.canonicalize().ok()? == real.canonicalize().ok()?).then_some(claim)
    }

    /// The pane's monotonic scroll-clock reading (see `clock_now`): the
    /// content anchor the app pairs with grid coordinates it captures now
    /// (annotation prompts, copy mode), so the pair survives streaming
    /// output and scrollback saturation alike.
    pub fn scroll_clock(&mut self) -> i64 {
        self.tick_clock()
    }

    /// Pin a note to the span starting at grid `line`, columns
    /// `start..start+len` (Cmd+K N's commit). `clock` is the scroll-clock
    /// reading `line` was captured against ([`Self::scroll_clock`] at the
    /// prompt's OPEN) — sampling it here instead would mis-anchor the note
    /// by every row that streamed while the user typed it.
    pub fn add_annotation(&mut self, line: i32, clock: i64, start: u16, len: u16, text: String) {
        self.annotations.push(PaneAnnotation {
            line_rec: line,
            clock_rec: clock,
            start,
            len: len.max(1),
            text,
        });
        self.pty_dirty.store(true, Ordering::Release);
    }

    /// Every annotation with its span translated to current grid lines:
    /// `(line, start, len, text)`. Spans whose content fell off the
    /// scrollback are dropped for good.
    pub fn annotations_current(&mut self) -> Vec<(i32, u16, u16, String)> {
        let now = self.tick_clock();
        let top = self.term.lock().grid().topmost_line().0;
        self.annotations
            .retain(|a| a.line_rec - (now - a.clock_rec) as i32 >= top);
        self.annotations
            .iter()
            .map(|a| {
                (
                    a.line_rec - (now - a.clock_rec) as i32,
                    a.start,
                    a.len,
                    a.text.clone(),
                )
            })
            .collect()
    }

    /// The newest grid line where a captured line starts, or `None`. The
    /// straight case is a row carrying `needle` as a prefix; a pane
    /// narrower than the needle instead shows the line's FIRST WRAPPED ROW,
    /// whose text is a prefix OF the needle. That reverse arm is gated on
    /// real wrap metadata, not row length: the row must itself soft-wrap
    /// (WRAPLINE on its last cell) — otherwise any short unrelated row
    /// sharing the prefix would win — and continuation rows (the PREVIOUS
    /// row wraps) never match either arm, or a later continuation sharing
    /// the prefix would beat the true start under the newest-first scan.
    pub fn find_captured_line(&self, needle: &str) -> Option<i32> {
        if needle.is_empty() {
            return None;
        }
        let term = self.term.lock();
        let cols = term.columns();
        let wraps = |line: i32| {
            cols > 0
                && term.grid()[Point::new(Line(line), Column(cols - 1))]
                    .flags
                    .contains(Flags::WRAPLINE)
        };
        let top = term.grid().topmost_line().0;
        let bottom = term.screen_lines() as i32 - 1;
        for line in (top..=bottom).rev() {
            if line > top && wraps(line - 1) {
                continue;
            }
            let (text, _) = row_text_and_cols(&term, line);
            let t = text.trim_end();
            if t.is_empty() {
                continue;
            }
            if t.starts_with(needle) || (wraps(line) && needle.starts_with(t)) {
                return Some(line);
            }
        }
        None
    }

    /// Every annotation translated against an EXPLICIT clock reading — the
    /// caller's own snapshot — as `(line, start, len, text)`. The
    /// existing-note lookup in the annotate prompt compares these lines
    /// against a selection captured WITH that reading; translating with a
    /// fresh (later) clock instead let output that scrolled in between
    /// shift the annotations away from the still-fixed selection line, so
    /// annotating the same span opened an empty prompt and duplicated the
    /// note. Pure translation: the scrolled-off GC stays in
    /// [`Self::annotations_current`].
    pub fn annotations_at_clock(&self, clock: i64) -> Vec<(i32, u16, u16, String)> {
        self.annotations
            .iter()
            .map(|a| {
                (
                    a.line_rec - (clock - a.clock_rec) as i32,
                    a.start,
                    a.len,
                    a.text.clone(),
                )
            })
            .collect()
    }

    /// The real text under a masked (redacted) cell at screen `(col, row)`,
    /// for the click-to-reveal popup (#360). None off the pane, off a
    /// mask, or while an alt-screen app owns the viewport.
    pub fn redacted_at(&self, col: u16, row: u16) -> Option<String> {
        let (vr, vc) = self.cell_at(col, row)?;
        let set = self.triggers.lock().unwrap().clone();
        if !set.has_redactions() {
            return None;
        }
        let term = self.term.lock();
        if term.mode().contains(TermMode::ALT_SCREEN) {
            return None;
        }
        let line = vr as i32 - term.grid().display_offset() as i32;
        let (_, colmap) = row_text_and_cols(&term, line);
        // Matched over the logical line, as the painter masks it: a secret
        // a soft wrap cut in two is found from a click on either half.
        let (text, offset) = logical_row_text(&term, line);
        drop(term);
        // The clicked column as a char index: a wide char's spacer column
        // resolves to the wide char itself (the `line_text_at` rule).
        let vc = vc as usize;
        // `row_text_and_cols` maps every non-spacer column, blanks
        // included, so a click on a blank cell resolves to that blank's own
        // char index - never back into a token. The `rposition` only ever
        // steps back for a wide char's spacer column, which is the wide
        // char itself.
        let ci = offset + colmap.iter().rposition(|&gc| gc <= vc)?;
        crate::triggers::redact_spans(&text, &set)
            .into_iter()
            .find(|s| ci >= s.start && ci < s.start + s.len)
            .map(|s| text.chars().skip(s.start).take(s.len).collect())
    }

    /// The annotation index + note under screen cell (col, row), if any.
    /// Annotations live on the primary screen; while an alt-screen app owns
    /// the viewport their lines describe rows the user cannot see, so no
    /// cell resolves.
    pub fn annotation_at(&self, col: u16, row: u16) -> Option<(usize, String)> {
        let (vr, vc) = self.cell_at(col, row)?;
        let term = self.term.lock();
        if term.mode().contains(TermMode::ALT_SCREEN) {
            return None;
        }
        let off = term.grid().display_offset() as i32;
        let now = self.clock_now(&term);
        drop(term);
        let line = vr as i32 - off;
        self.annotations
            .iter()
            .enumerate()
            .find(|(_, a)| {
                a.line_rec - (now - a.clock_rec) as i32 == line
                    && vc >= a.start
                    && vc < a.start + a.len
            })
            .map(|(i, a)| (i, a.text.clone()))
    }

    pub fn remove_annotation(&mut self, idx: usize) {
        if idx < self.annotations.len() {
            self.annotations.remove(idx);
            self.pty_dirty.store(true, Ordering::Release);
        }
    }

    pub fn set_annotation_text(&mut self, idx: usize, text: String) {
        if let Some(a) = self.annotations.get_mut(idx) {
            a.text = text;
            self.pty_dirty.store(true, Ordering::Release);
        }
    }

    /// When the row at current grid `line` arrived (epoch millis), if the
    /// reader thread stamped it.
    pub fn row_time(&self, line: i32) -> Option<u64> {
        let term = self.term.lock();
        let now = self.clock_now(&term);
        drop(term);
        self.line_times
            .lock()
            .unwrap()
            .get(&(i64::from(line) + now))
            .copied()
    }

    /// Drain the loopback ports the reader thread scraped since the last call.
    /// Each port is reported at most once over the terminal's lifetime, so this
    /// is empty on most ticks.
    pub fn drain_ports(&self) -> Vec<crate::port_detect::PortHit> {
        self.port_rx.try_iter().collect()
    }

    /// Bytes advanced into the grid since the last redraw, without
    /// clearing. The main loop uses this to classify a PTY-only redraw as
    /// interactive echo (small, redraw now) or bulk stream (large, stay
    /// capped). Reset on the next `take_dirty`.
    pub fn peek_pending_bytes(&self) -> usize {
        self.pty_pending_bytes.load(Ordering::Relaxed)
    }

    /// Process ID of the shell running inside this terminal, when the
    /// platform exposes one. Used to look up the live cwd so a new split
    /// inherits the directory the user has `cd`'d into. None once the shell
    /// has exited: a reaped pid may already name another process.
    pub fn pid(&self) -> Option<u32> {
        self.backend.pid().filter(|_| self.exit.is_none())
    }

    /// Notice that the pane's shell has exited (#912): `exit`, Ctrl+D, a
    /// task that ran `exit 3`. The shell is reaped (it stayed a zombie for
    /// as long as the pane lived), and once the reader has painted all it
    /// wrote, the exit goes under its output and the pane is marked
    /// exited. Returns the exit code the first time only.
    pub fn poll_exit(&mut self) -> Option<Option<i32>> {
        if self.exit.is_some() {
            return None;
        }
        let output_closed = self.reader_thread.as_ref().is_none_or(|h| h.is_finished());
        let code = self.backend.try_exit(output_closed)?;
        if !output_closed {
            let since = *self.reaped_at.get_or_insert_with(std::time::Instant::now);
            if since.elapsed() < EXIT_OUTPUT_GRACE {
                return None;
            }
        }
        self.exit = Some(code);
        // A run pane's reader paints its own footer.
        if !self.run_pane {
            let footer = match code {
                Some(c) => format!("\r\n\x1b[2m[Process exited with code {c}]\x1b[22m\r\n"),
                None => String::from("\r\n\x1b[2m[Process exited]\x1b[22m\r\n"),
            };
            Processor::<StdSyncHandler>::new().advance(&mut *self.term.lock(), footer.as_bytes());
            self.pty_dirty.store(true, Ordering::Release);
        }
        Some(code)
    }

    /// Whether [`Self::poll_exit`] has found the shell exited: the pane
    /// then takes no input.
    pub fn has_exited(&self) -> bool {
        self.exit.is_some()
    }

    /// Whether this is a `new_running` program pane rather than a shell.
    pub fn is_run_pane(&self) -> bool {
        self.run_pane
    }

    /// The pane host holding this pane's shell, when one does (#694): what
    /// a saved session records so the next croft can reattach.
    pub fn host_socket(&self) -> Option<&std::path::Path> {
        match &self.backend {
            PaneBackend::Hosted { socket, .. } => Some(socket),
            PaneBackend::Local { .. } => None,
        }
    }

    /// Read the dirty flag without clearing it. Lets the main loop decide
    /// whether to redraw now or coalesce, without losing the signal if we
    /// choose to skip this iteration.
    pub fn peek_dirty(&self) -> bool {
        self.pty_dirty.load(Ordering::Acquire)
    }

    pub fn cell_at(&self, col: u16, row: u16) -> Option<(u16, u16)> {
        let inner = self.last_inner;
        if inner.width == 0 || inner.height == 0 {
            return None;
        }
        if col < inner.x || col >= inner.x + inner.width {
            return None;
        }
        if row < inner.y || row >= inner.y + inner.height {
            return None;
        }
        Some((row - inner.y, col - inner.x))
    }

    /// The host-screen cell nearest `(col, row)` that is still inside the
    /// pane's grid. A forwarded drag or release that leaves the pane is
    /// delivered at the edge cell it crossed, as xterm does with a grabbed
    /// pointer, rather than dropped: a child that got the press must also
    /// get the release, or it keeps a button held that the user let go.
    /// Returns the input unchanged when the pane has no grid yet.
    pub fn clamp_to_grid(&self, col: u16, row: u16) -> (u16, u16) {
        let inner = self.last_inner;
        if inner.width == 0 || inner.height == 0 {
            return (col, row);
        }
        (
            col.clamp(inner.x, inner.x + inner.width - 1),
            row.clamp(inner.y, inner.y + inner.height - 1),
        )
    }

    /// Current scrollback offset: how many rows the viewport is scrolled
    /// up from the live bottom. Viewport row `r` maps to absolute grid
    /// line `r - display_offset`.
    fn display_offset(&self) -> i32 {
        self.term.lock().grid().display_offset() as i32
    }

    /// Text of the logical line under screen cell `(col, row)`, plus the
    /// 0-based char index within that text the click landed on. Drives
    /// Cmd/Ctrl+click URL and `path:line` detection. A line the terminal
    /// soft-wrapped (WRAPLINE) is stitched back together from all its rows,
    /// so a long URL resolves whole from any of them (#1355). `None` when
    /// the cell is outside the content area.
    pub fn line_text_at(&self, col: u16, row: u16) -> Option<(String, usize)> {
        let (r, c) = self.cell_at(col, row)?;
        let term = self.term.lock();
        let line = r as i32 - term.grid().display_offset() as i32;
        let (row_text, cols_map) = row_text_and_cols(&term, line);
        // Grid column → char index in the spacer-skipped text: the last
        // produced char at-or-before the clicked column, so clicking a wide
        // char's spacer cell resolves to the wide char itself.
        let idx = cols_map.iter().rposition(|&gc| gc <= c as usize)?;
        let top = -(term.grid().history_size() as i32);
        let bottom = term.screen_lines() as i32 - 1;
        let mut first = line;
        while first > top && row_wraps(&term, first - 1) {
            first -= 1;
        }
        let mut last = line;
        while last < bottom && row_wraps(&term, last) {
            last += 1;
        }
        if first == line && last == line {
            return Some((row_text, idx));
        }
        let mut text = String::new();
        let mut offset = 0;
        for l in first..=last {
            let part = if l == line {
                offset = text.chars().count();
                row_text.clone()
            } else {
                row_text_and_cols(&term, l).0
            };
            text.push_str(&part);
        }
        Some((text, offset + idx))
    }

    /// The OSC 8 hyperlink under a screen position (host cell coords), if
    /// any — the screen-coord twin of [`Self::hyperlink_at`].
    pub fn hyperlink_at_screen(&self, col: u16, row: u16) -> Option<String> {
        let (r, c) = self.cell_at(col, row)?;
        self.hyperlink_at(r as usize, c as usize)
    }

    /// The current scroll-clock reading against an already-locked term.
    fn clock_now(&self, term: &Term<VoidListener>) -> i64 {
        self.clock.lock().unwrap().now(term)
    }

    /// Fold the tracer's drift into the clock, re-plant it fresh and return
    /// the folded reading (see [`ScrollClock::tick`]).
    fn tick_clock(&mut self) -> i64 {
        let mut term = self.term.lock();
        self.clock.lock().unwrap().tick(&mut term)
    }

    /// Stamp freshly-set selection / copy-cursor coordinates against a
    /// fresh clock tick; a selection set on the alternate screen also
    /// captures its content anchor (see `AltSelAnchor`).
    fn stamp_selection_clock(&mut self) {
        self.sel_scrolled = self.tick_clock();
        let term = self.term.lock();
        self.alt_sel = if term.mode().contains(TermMode::ALT_SCREEN) {
            self.selection.and_then(|s| capture_alt_anchor(&term, s))
        } else {
            None
        };
    }

    /// Re-anchor an alternate-screen selection to its content after the
    /// app repainted (see `AltSelAnchor`). Finds the vertical shift whose
    /// on-grid rows all match the remembered ones — requiring at least one
    /// non-blank matched row so a blank fingerprint can't latch anywhere —
    /// preferring the smallest movement; no qualifying shift parks the
    /// selection dormant until its content scrolls back into view. A
    /// selection created on the primary screen has no anchor and simply
    /// stays frozen for the duration of the alt-screen trip.
    fn rebase_alt_selection(&mut self) {
        if self.selection.is_none() {
            self.alt_sel = None;
            return;
        }
        let Some(mut anchor) = self.alt_sel.take() else {
            return;
        };
        let term = self.term.lock();
        let rows_vis = term.screen_lines() as i32;
        let old_top = anchor.top;
        let k = anchor.rows.len() as i32;
        // One grid snapshot up front (text + char→column maps): the
        // matcher probes every candidate shift, so per-candidate row reads
        // would re-extract (and re-allocate) the same rows dozens of times
        // a frame.
        let grid_rows: Vec<(String, Vec<usize>)> =
            (0..rows_vis).map(|l| row_text_and_cols(&term, l)).collect();
        // Per candidate shift, how many block rows the grid matches
        // exactly at that offset. Rows can go missing not just off-grid:
        // app chrome (Claude Code's input box, its floating pills, an
        // animated status row) overdraws rows anywhere in the block, so
        // partial survival anchors by however many exact rows remain — at
        // least two (when the block has two) including a non-blank one,
        // so a lone repeated divider row can't latch the highlight onto an
        // unrelated copy of itself. More exact rows win; ties go to the
        // shift whose captured neighbour rows also match (a ONE-row block
        // has a one-row fingerprint, and full-screen apps repeat rows
        // verbatim — the neighbours tell its copy from the lookalikes),
        // then to the smallest movement.
        let k_rows = anchor.rows.len();
        let min_exact = k_rows.min(2);
        // (top, exact-row count, matched-neighbour count)
        let mut best: Option<(i32, usize, usize)> = None;
        for top in 1 - k..rows_vis {
            let (mut exact, mut nonblank) = (0usize, false);
            for (i, want) in anchor.rows.iter().enumerate() {
                let line = top + i as i32;
                if (0..rows_vis).contains(&line) && grid_rows[line as usize].0 == *want {
                    exact += 1;
                    nonblank |= !want.trim().is_empty();
                }
            }
            let mut ctx = 0usize;
            for (want, line) in [
                (anchor.ctx_above.as_ref(), top - 1),
                (anchor.ctx_below.as_ref(), top + k),
            ] {
                if let Some(want) = want
                    && (0..rows_vis).contains(&line)
                    && grid_rows[line as usize].0 == *want
                {
                    ctx += 1;
                }
            }
            if exact >= min_exact
                && nonblank
                && best.is_none_or(|(btop, bexact, bctx)| {
                    exact > bexact
                        || (exact == bexact && ctx > bctx)
                        || (exact == bexact
                            && ctx == bctx
                            && (top - old_top).abs() < (btop - old_top).abs())
                })
            {
                best = Some((top, exact, ctx));
            }
        }
        match best {
            Some((top, _, _)) => {
                let d = top - old_top;
                anchor.top = top;
                if d != 0
                    && let Some(s) = self.selection.as_mut()
                {
                    s.anchor.0 += d;
                    s.head.0 += d;
                }
                anchor.dormant = false;
                // The clip: every block row still on screen, whole when its
                // text matches exactly, or just the surviving prefix/suffix
                // columns when app chrome (a floating pill) overdraws part
                // of it. The shift is already pinned by the exact run, so
                // partial credit here can't drag the highlight elsewhere.
                let mut clips: Vec<(i32, u16, u16)> = Vec::new();
                let mut all_exact = true;
                for (i, want) in anchor.rows.iter().enumerate() {
                    let line = top + i as i32;
                    if !(0..rows_vis).contains(&line) {
                        all_exact = false;
                        continue;
                    }
                    let (got, colmap) = &grid_rows[line as usize];
                    if got == want {
                        clips.push((line, 0, u16::MAX));
                    } else {
                        all_exact = false;
                        for (lo, hi) in partial_overlap_cols(want, got, colmap) {
                            clips.push((line, lo, hi));
                        }
                    }
                }
                anchor.visible = (!all_exact).then_some(clips);
                // Refresh the anchor — this is also what folds in a user
                // extension of the selection — but only when every row is
                // in view and intact, so the remembered block never loses
                // a covered or off-screen part mid-scroll.
                if all_exact && let Some(fresh) = capture_alt_anchor(&term, self.selection.unwrap())
                {
                    anchor = fresh;
                }
            }
            // Nothing matched anywhere. Mid-drag that must NOT hide the
            // selection — the drag may have started on a blank row or an
            // animated status line, and the user is pointing at what they
            // see right now; the real anchor is captured on release.
            None if self.drag_selecting => {
                anchor.dormant = false;
                anchor.visible = None;
                if let Some(fresh) = capture_alt_anchor(&term, self.selection.unwrap()) {
                    anchor = fresh;
                }
            }
            None => anchor.dormant = true,
        }
        drop(term);
        self.alt_sel = Some(anchor);
    }

    /// Shift the stored selection and copy-cursor down-anchored coordinates
    /// by the scroll-clock movement since they were recorded, so they keep
    /// naming the same content while output streams. Endpoints whose
    /// content fell off the scrollback pin to the oldest line; a selection
    /// entirely off the buffer is dropped for good. No-op (and no lock)
    /// when neither exists — setters stamp `sel_scrolled` themselves.
    fn rebase_selection(&mut self) {
        if self.selection.is_none() && self.copy_cursor.is_none() {
            return;
        }
        if self.term.lock().mode().contains(TermMode::ALT_SCREEN) {
            self.rebase_alt_selection();
            return;
        }
        if self.alt_sel.take().is_some() {
            // The selection was made on the alternate screen and the app
            // has left it: the alternate grid — and the content the
            // coordinates named — is gone with it.
            self.selection = None;
            self.copy_cursor = None;
            return;
        }
        let now = self.tick_clock();
        let top = self.term.lock().grid().topmost_line().0;
        let delta = (now - self.sel_scrolled) as i32;
        self.sel_scrolled = now;
        if delta != 0 {
            if let Some(sel) = self.selection.as_mut() {
                sel.anchor.0 -= delta;
                sel.head.0 -= delta;
            }
            if let Some(cur) = self.copy_cursor.as_mut() {
                cur.0 -= delta;
            }
        }
        if self
            .selection
            .is_some_and(|s| s.anchor.0 < top && s.head.0 < top)
        {
            self.selection = None;
        } else if let Some(sel) = self.selection.as_mut() {
            sel.anchor.0 = sel.anchor.0.max(top);
            sel.head.0 = sel.head.0.max(top);
        }
        if let Some(cur) = self.copy_cursor.as_mut() {
            cur.0 = cur.0.max(top);
        }
    }

    pub fn start_selection_at(&mut self, col: u16, row: u16) {
        if let Some((r, c)) = self.cell_at(col, row) {
            let line = r as i32 - self.display_offset();
            self.selection = Some(Selection::new(line, c));
            self.drag_selecting = true;
            self.stamp_selection_clock();
        }
    }

    /// Replay a saved transcript into this pane's grid so a restored pane
    /// shows the output it had before a restart (#249), above the fresh
    /// prompt the new shell prints.
    ///
    /// Each line is written literally with CRLF and NO escape sequences:
    /// the transcript is plain text precisely so a replay cannot re-run a
    /// cursor move, a screen clear, or a title change that the original
    /// output contained. The shell is untouched — this only paints the
    /// grid, so the prompt sits below the restored text.
    pub fn replay_transcript(&self, lines: &[String]) {
        let bytes = transcript_bytes(lines);
        if bytes.is_empty() {
            return;
        }
        let mut p = Processor::<StdSyncHandler>::new();
        let mut term = self.term.lock();
        p.advance(&mut *term, &bytes);
    }

    /// Scrollback rows held, the live screen's rows, and the grid's width,
    /// for the memory report (#694).
    pub fn grid_extent(&self) -> (usize, usize, usize) {
        let term = self.term.lock();
        (
            term.grid().history_size(),
            term.screen_lines(),
            term.columns(),
        )
    }

    /// The pane's rewind buffer (#357), for the scrubber to replay from.
    ///
    /// Handed out as the shared handle rather than a copy: the buffer is
    /// megabytes by design, and the reader thread is writing to it while the
    /// overlay reads, so a snapshot would be both expensive and immediately
    /// stale.
    pub fn rewind(&self) -> &Arc<std::sync::Mutex<crate::rewind::RewindBuffer>> {
        &self.rewind
    }

    /// Test-only: parse `bytes` straight into this pane's grid, as if the
    /// child had printed them — app-level tests drive alt-screen repaint
    /// scenarios deterministically through this.
    #[cfg(test)]
    pub fn feed_bytes_for_test(&self, bytes: &[u8]) {
        // Deliberately does NOT record into the rewind buffer, though the
        // reader thread does (#357). Recording here too would be a SECOND
        // implementation of that wiring, and a test driving this helper
        // would then pass with the reader thread recording nothing at all —
        // measured: deleting the reader's `rb.push` left the app-level test
        // green. The recording is proven through a real pty instead, by
        // `the_reader_thread_records_shell_output_for_rewind`.
        let mut p = Processor::<StdSyncHandler>::new();
        let mut term = self.term.lock();
        p.advance(&mut *term, bytes);
    }

    /// Test-only: the pane's grid lock, for tests that must observe what
    /// `resize` does WHILE the grid is held (#473).
    #[cfg(test)]
    pub fn grid_lock_for_test(&self) -> Arc<FairMutex<Term<VoidListener>>> {
        self.term.clone()
    }

    /// Test-only: run one reader-thread timestamp pass over the current
    /// grid, exactly as a real chunk arrival would.
    #[cfg(test)]
    pub fn stamp_chunk_for_test(&self, prev_id: &mut i64, now_ms: u64) {
        let mut term = self.term.lock();
        let mut clock = self.clock.lock().unwrap();
        let mut lt = self.line_times.lock().unwrap();
        stamp_chunk(&mut term, &mut clock, &mut lt, prev_id, now_ms);
    }

    /// Test-only: the stamped (content id, arrival ms) pairs.
    #[cfg(test)]
    pub fn line_time_entries_for_test(&self) -> Vec<(i64, u64)> {
        self.line_times
            .lock()
            .unwrap()
            .iter()
            .map(|(&k, &v)| (k, v))
            .collect()
    }

    /// Test-only: record an OSC 133 mark as the reader thread would,
    /// stamped against the grid's CURRENT cursor/history state, so tests
    /// can stage prompt-dependent gestures without a live shell.
    #[cfg(test)]
    pub fn push_mark_for_test(&self, kind: crate::shell_integration::OscEvent, col_rec: usize) {
        let mut term = self.term.lock();
        let line_rec = term.grid().cursor.point.line.0;
        let clock_rec = self.clock.lock().unwrap().tick(&mut term);
        drop(term);
        self.marks.lock().unwrap().push(StoredMark {
            id: next_mark_id(),
            kind,
            line_rec,
            clock_rec,
            col_rec,
            dur: None,
        });
    }

    /// Test-only: record an inline image as the reader thread would,
    /// anchored at the grid's CURRENT cursor row.
    #[cfg(test)]
    pub fn push_image_for_test(&self, data: Vec<u8>) {
        let mut term = self.term.lock();
        let line_rec = term.grid().cursor.point.line.0;
        let clock_rec = self.clock.lock().unwrap().tick(&mut term);
        drop(term);
        let mut imgs = self.images.lock().unwrap();
        let seq = imgs.last().map_or(0, |m| m.seq) + 1;
        imgs.push(StoredImage {
            seq,
            data: std::sync::Arc::new(data),
            line_rec,
            clock_rec,
        });
    }

    /// Test-only: whether a quick-select hint overlay is currently set.
    #[cfg(test)]
    pub fn has_hints_for_test(&self) -> bool {
        self.hints.is_some()
    }

    /// Test-only: whether a find highlight needle is currently set.
    #[cfg(test)]
    pub fn has_search_for_test(&self) -> bool {
        self.search_needle.is_some()
    }

    /// Test-only: the raw state behind the corrected selection accessors —
    /// (stored selection, sel_scrolled, clock_base, alt anchor top, alt
    /// mode) — for diagnosing drift math from app-level tests.
    #[cfg(test)]
    pub fn debug_sel_state(&self) -> (Option<Selection>, i64, i64, Option<i32>, bool) {
        (
            self.selection,
            self.sel_scrolled,
            self.clock.lock().unwrap().base,
            self.alt_sel.as_ref().map(|a| a.top),
            self.term.lock().mode().contains(TermMode::ALT_SCREEN),
        )
    }

    /// The mouse button came up: the drag-selection is final. Capture the
    /// definitive content anchor now — during the drag the selection
    /// followed the pointer over whatever the grid showed.
    pub fn end_drag(&mut self) {
        if self.drag_selecting {
            self.drag_selecting = false;
            self.stamp_selection_clock();
        }
    }

    pub fn extend_selection_to(&mut self, col: u16, row: u16) {
        self.drag_selecting = true;
        self.rebase_selection();
        let cell = self.cell_at(col, row);
        let off = self.display_offset();
        if let (Some(sel), Some((r, c))) = (self.selection.as_mut(), cell) {
            sel.head = (r as i32 - off, c);
        }
    }

    /// Extend a drag-selection toward a pointer that may have left the
    /// pane. Columns and rows are clamped to the inner content rect; the
    /// returned value is the auto-scroll direction the caller should keep
    /// applying while the pointer stays past an edge: `-1` (pointer above
    /// the top, scroll into history), `+1` (below the bottom, scroll
    /// toward live), or `0` (inside the pane, no auto-scroll). Mirrors
    /// the click-drag-past-the-edge selection growth in iTerm2/VS Code.
    pub fn drag_select_to(&mut self, col: u16, row: u16) -> i32 {
        let inner = self.last_inner;
        if inner.width == 0 || inner.height == 0 {
            return 0;
        }
        self.drag_selecting = true;
        let top = inner.y;
        let bottom = inner.y + inner.height - 1;
        let (vp_row, dir) = if row < top {
            (0u16, -1)
        } else if row > bottom {
            (inner.height - 1, 1)
        } else {
            (row - inner.y, 0)
        };
        let max_x = inner.x + inner.width - 1;
        let c = col.clamp(inner.x, max_x) - inner.x;
        self.rebase_selection();
        let off = self.display_offset();
        if let Some(sel) = self.selection.as_mut() {
            sel.head = (vp_row as i32 - off, c);
        }
        dir
    }

    /// One step of edge auto-scroll while a drag-selection is held past
    /// the top (`dir < 0`) or bottom (`dir > 0`) edge. Scrolls the
    /// viewport by one row and re-pins the selection head to the new edge
    /// line at the last-known drag column. On the alternate screen the
    /// inner program owns scrolling, so a mouse-tracking app (Claude Code,
    /// a pager) gets a wheel report at the edge cell instead — it scrolls
    /// its own content, the content anchor drags the selection along, and
    /// the head re-pins each tick.
    pub fn autoscroll_select(&mut self, dir: i32, col: u16) {
        if dir == 0 {
            return;
        }
        if self.term.lock().mode().contains(TermMode::ALT_SCREEN) {
            let inner = self.last_inner;
            if inner.width == 0 || inner.height == 0 || !self.mouse_reporting() {
                return;
            }
            let edge_row = if dir < 0 {
                inner.y
            } else {
                inner.y + inner.height - 1
            };
            let ccol = col.clamp(inner.x, inner.x + inner.width - 1);
            let button = if dir < 0 {
                MouseButtonKind::WheelUp
            } else {
                MouseButtonKind::WheelDown
            };
            self.report_mouse(
                button,
                MouseAction::Press,
                ccol,
                edge_row,
                MouseMods::default(),
            );
            self.rebase_selection();
            if let Some(sel) = self.selection.as_mut() {
                sel.head = (i32::from(edge_row - inner.y), ccol - inner.x);
            }
            return;
        }
        let scrolled = if dir < 0 {
            self.scroll_up(1)
        } else {
            self.scroll_down(1)
        };
        if !scrolled {
            return;
        }
        let inner = self.last_inner;
        if inner.width == 0 || inner.height == 0 {
            return;
        }
        let max_x = inner.x + inner.width - 1;
        let c = col.clamp(inner.x, max_x) - inner.x;
        let vp_row = if dir < 0 { 0u16 } else { inner.height - 1 };
        self.rebase_selection();
        let off = self.display_offset();
        if let Some(sel) = self.selection.as_mut() {
            sel.head = (vp_row as i32 - off, c);
        }
    }

    pub fn clear_selection(&mut self) {
        self.selection = None;
        self.alt_sel = None;
    }

    /// Double-click word-select: expand the selection to cover the word
    /// under the screen coordinate `(col, row)`. No-op when the click
    /// lands on whitespace / punctuation or outside the live area.
    pub fn select_word_at(&mut self, col: u16, row: u16) {
        let Some((r, c)) = self.cell_at(col, row) else {
            return;
        };
        let term = self.term.lock();
        let display_offset = term.grid().display_offset();
        let Some((anchor, head)) =
            select_word_at_in_term(&term, display_offset, r as usize, c as usize)
        else {
            return;
        };
        drop(term);
        // `select_word_at_in_term` reports viewport rows; anchor them to
        // absolute grid lines so the selection stays put when scrolled.
        let off = display_offset as i32;
        let to_abs = |(vr, vc): (u16, u16)| (vr as i32 - off, vc);
        self.selection = Some(Selection {
            anchor: to_abs(anchor),
            head: to_abs(head),
            block: false,
        });
        self.stamp_selection_clock();
    }

    /// The selection with its endpoints corrected for the scroll-clock
    /// movement since they were recorded, so callers always see coordinates
    /// that name the content the user selected (see `rebase_selection`).
    pub fn selection(&self) -> Option<Selection> {
        let mut sel = self.selection?;
        let delta = (self.clock_now(&self.term.lock()) - self.sel_scrolled) as i32;
        sel.anchor.0 -= delta;
        sel.head.0 -= delta;
        Some(sel)
    }

    /// Replace (or clear) the selection wholesale. Copy mode drives the
    /// selection from the keyboard through this, bypassing the mouse path.
    pub fn set_selection(&mut self, sel: Option<Selection>) {
        self.rebase_selection();
        self.selection = sel;
        self.stamp_selection_clock();
        self.pty_dirty.store(true, Ordering::Release);
    }

    /// Show / move / hide the copy-mode cursor block.
    pub fn set_copy_cursor(&mut self, cur: Option<(i32, u16)>) {
        self.rebase_selection();
        self.copy_cursor = cur;
        self.stamp_selection_clock();
        self.pty_dirty.store(true, Ordering::Release);
    }

    /// The shell cursor's cell in absolute grid coords (line can be
    /// negative only transiently; the live screen is 0-based): where copy
    /// mode starts.
    pub fn cursor_line_col(&self) -> (i32, u16) {
        let term = self.term.lock();
        let p = term.grid().cursor.point;
        (p.line.0, p.column.0 as u16)
    }

    /// The drift-corrected selection together with the scroll-clock reading
    /// it is valid against, from ONE terminal snapshot. Callers that pair a
    /// grid coordinate with a clock (the annotation prompt) must use this:
    /// reading them through separate locks lets PTY output land in between,
    /// pairing a pre-output line with a post-output clock and anchoring to
    /// the wrong content row.
    pub fn selection_and_clock(&mut self) -> (Option<Selection>, i64) {
        let mut term = self.term.lock();
        let now = self.clock.lock().unwrap().tick(&mut term);
        let sel = self.selection.map(|mut s| {
            let delta = (now - self.sel_scrolled) as i32;
            s.anchor.0 -= delta;
            s.head.0 -= delta;
            s
        });
        (sel, now)
    }

    /// Cursor cell, grid bounds, and the scroll-clock reading from ONE
    /// terminal snapshot (copy mode's open — same atomicity argument as
    /// [`Self::selection_and_clock`]).
    #[allow(clippy::type_complexity)]
    pub fn cursor_bounds_and_clock(&mut self) -> ((i32, u16), (i32, i32, u16, u16), i64) {
        let mut term = self.term.lock();
        let now = self.clock.lock().unwrap().tick(&mut term);
        let p = term.grid().cursor.point;
        let top = term.grid().topmost_line().0;
        let bottom = term.screen_lines() as i32 - 1;
        (
            (p.line.0, p.column.0 as u16),
            (top, bottom, self.cols, self.rows),
            now,
        )
    }

    /// One grid row as spacer-skipped text plus its char-index → grid-column
    /// map (the free `row_text_and_cols` behind the term lock).
    pub fn row_text(&self, line: i32) -> (String, Vec<usize>) {
        let term = self.term.lock();
        row_text_and_cols(&term, line)
    }

    /// The readable grid range and viewport size for keyboard navigation:
    /// (oldest line, newest line, columns, viewport rows).
    pub fn grid_bounds(&self) -> (i32, i32, u16, u16) {
        let term = self.term.lock();
        let top = term.grid().topmost_line().0;
        let bottom = term.screen_lines() as i32 - 1;
        (top, bottom, self.cols, self.rows)
    }

    pub fn selection_text(&self) -> String {
        // An alt-screen selection scrolled (partly) out of the app's view
        // names content the grid no longer fully holds — dormant, or
        // clipped by app chrome. The anchor remembered the text, so copy
        // still yields the whole highlighted block.
        if let Some(anchor) = self
            .alt_sel
            .as_ref()
            .filter(|a| a.dormant || a.visible.is_some())
        {
            return anchor.text.clone();
        }
        let Some(mut sel) = self.selection else {
            return String::new();
        };
        let term = self.term.lock();
        // Same scroll-clock correction as `selection()`, computed under
        // the lock already held for extraction.
        let delta = (self.clock_now(&term) - self.sel_scrolled) as i32;
        sel.anchor.0 -= delta;
        sel.head.0 -= delta;
        if sel.block {
            let (rl, cl, rh, ch) = sel.block_bounds();
            return block_selection_text(&term, rl, cl as usize, rh, ch as usize);
        }
        let (sr, sc, er, ec) = sel.normalised();
        extract_selection_text(&term, sr, sc as usize, er, ec as usize)
    }

    /// The pane's stable identity (see the `uid` field).
    pub fn uid(&self) -> u64 {
        self.uid
    }

    pub fn write_input(&mut self, data: &[u8]) {
        self.reset_scrollback();
        self.input_seen = true;
        self.last_input_ms = now_ms();
        #[cfg(test)]
        self.written_for_test
            .lock()
            .unwrap()
            .extend_from_slice(data);
        let _ = self.input_tx.send(data.to_vec());
        self.pty_dirty.store(true, Ordering::Release);
    }

    /// Test-only: every byte the app has written toward the child's stdin.
    #[cfg(test)]
    pub fn written_bytes_for_test(&self) -> Vec<u8> {
        self.written_for_test.lock().unwrap().clone()
    }

    /// Test-only: report a finished command as the reader thread does at
    /// its `133;D` mark, so app tests can end a pane's command without a
    /// shell that speaks OSC 133.
    #[cfg(test)]
    pub fn finish_command_for_test(&self, exit: Option<i32>, dur: std::time::Duration) {
        let _ = self.finished_tx_for_test.send(FinishedCommand {
            exit,
            dur,
            cmd: String::new(),
            cwd: None,
            host: None,
            output: String::new(),
        });
    }

    /// True when the child program has enabled any mouse-tracking mode
    /// (DECSET 1000 click / 1002 button-drag / 1003 any-motion). When it has,
    /// wheel events should be forwarded to it via `report_mouse` so it scrolls
    /// its own buffer rather than croft synthesising arrow keys.
    pub fn mouse_reporting(&self) -> bool {
        self.term.lock().mode().intersects(TermMode::MOUSE_MODE)
    }

    /// True when the child asked for button-held MOTION too (DECSET 1002
    /// button-drag or 1003 any-motion), not just clicks (1000). Decides who
    /// a left-button drag belongs to: a child that only asked for clicks
    /// cannot use the drag, so croft keeps it as a text selection (#474).
    pub fn mouse_motion_reporting(&self) -> bool {
        self.term
            .lock()
            .mode()
            .intersects(TermMode::MOUSE_DRAG | TermMode::MOUSE_MOTION)
    }

    /// Encode a mouse gesture at host-screen cell `(col, row)` as a mouse
    /// report and send it to the child. Returns false without writing when
    /// the cell is outside the pane, the child isn't tracking the mouse, or
    /// the event is motion the child didn't ask for (no 1002/1003). The report
    /// is SGR (1006) when the child selected it, otherwise legacy X10.
    pub fn report_mouse(
        &mut self,
        button: MouseButtonKind,
        action: MouseAction,
        col: u16,
        row: u16,
        mods: MouseMods,
    ) -> bool {
        let Some((r, c)) = self.cell_at(col, row) else {
            return false;
        };
        let mode = *self.term.lock().mode();
        if !mode.intersects(TermMode::MOUSE_MODE) {
            return false;
        }
        // Motion (a held-button drag) is only wanted under 1002/1003.
        if action == MouseAction::Motion
            && !mode.intersects(TermMode::MOUSE_DRAG | TermMode::MOUSE_MOTION)
        {
            return false;
        }
        let report = encode_mouse_report(
            mode.contains(TermMode::SGR_MOUSE),
            button,
            action,
            c,
            r,
            mods,
        );
        #[cfg(test)]
        self.written_for_test
            .lock()
            .unwrap()
            .extend_from_slice(&report);
        let _ = self.input_tx.send(report);
        self.input_seen = true;
        self.pty_dirty.store(true, Ordering::Release);
        true
    }

    /// Seed a `cd <path>` into the embedded shell so the terminal
    /// follows an Explorer-side workspace-root change. Sent verbatim to
    /// the PTY input - the shell parses it like a typed command. See
    /// `format_cd_command` for the line-clearing prefix and the path
    /// quoting strategy.
    pub fn change_cwd(&mut self, path: &std::path::Path) {
        self.write_input(&format_cd_command(path));
    }

    /// Whether the program in the pane turned on bracketed paste, so a
    /// pasted line break waits for Enter instead of running the line (#1274).
    pub fn bracketed_paste(&self) -> bool {
        self.term.lock().mode().contains(TermMode::BRACKETED_PASTE)
    }

    /// Paste a payload into the embedded shell. Bracketed-paste markers
    /// are added only if the inner program asked for them; otherwise the
    /// payload is sent raw so simple shells don't see literal `\e[200~`.
    pub fn paste_input(&mut self, payload: &[u8]) {
        // The terminal's own mode, as its parser tracked it: the byte
        // sniffer missed a `\e[?2004h` split across two reads, a combined
        // `\e[?1049;2004h` and a reset, and pasted line by line into a shell
        // that had asked for bracketed paste.
        let bracketed = self.term.lock().mode().contains(TermMode::BRACKETED_PASTE);
        if bracketed {
            self.write_input(b"\x1b[200~");
            // No ESC inside the brackets, as xterm and VS Code do: pasted
            // text holding `\e[201~` would close the paste early, and the
            // shell would run what follows it (`ls\e[201~rm -rf ~\r`). Any
            // program in a pane can plant that on the clipboard via OSC 52.
            let clean: Vec<u8> = payload.iter().copied().filter(|&b| b != 0x1b).collect();
            self.write_input(&clean);
            self.write_input(b"\x1b[201~");
        } else {
            self.write_input(payload);
        }
    }

    /// True when the embedded shell is sitting at its prompt rather than
    /// running a foreground application (an editor, a pager, or an agent
    /// like Claude Code). Compares the PTY's foreground process group
    /// against the shell's own pid: a shell at its prompt is its own
    /// process-group leader, so `tcgetpgrp(master) == shell_pid`. Once
    /// the shell forks a command, that command owns a new foreground
    /// group and the two diverge. The only case that must suppress a
    /// `cd` seed is a foreground group that exists AND is not the shell,
    /// because that is an app reading the tty in raw mode; a missing
    /// foreground group (the brief window after spawn, before the shell
    /// claims the tty) means nothing has grabbed input, so a `cd` is
    /// still safe. `tcgetpgrp` is identical on macOS and Linux. A shell
    /// that has exited (#912) owns nothing.
    pub fn foreground_is_shell(&self) -> bool {
        if self.exit.is_some() {
            return false;
        }
        match (self.backend.process_group_leader(), self.shell_pid) {
            (Some(fg), Some(pid)) => fg == pid,
            _ if self.input_seen => {
                // A pane that has received input CAN be running a launched
                // app, so an UNRESOLVABLE sample (failed tcgetpgrp, or a
                // spawn that never reported a shell pid) must not read as
                // "shell owns it" — under scheduler load the sample
                // transiently fails while a foreground command runs, and
                // the old blanket `true` let a cd seed reach that app
                // (#155). Retry once (the failure window is brief), then
                // answer FALSE: every consumer fails safe on false (seed
                // suppressed, task pane not reused, no prompt arrows).
                std::thread::sleep(std::time::Duration::from_millis(5));
                match (self.backend.process_group_leader(), self.shell_pid) {
                    (Some(fg), Some(pid)) => fg == pid,
                    _ => false,
                }
            }
            // Startup window: no input has ever been written, so nothing
            // user-facing can own the tty yet — a missing group is the
            // shell's own rc still claiming it, and a seed queues as
            // type-ahead (#94).
            _ => true,
        }
    }

    /// True when seeding a `cd` into the PTY cannot reach a user-facing
    /// foreground application. Either the shell owns the foreground group
    /// (`foreground_is_shell`), or the pane is still in its startup
    /// window: nothing has ever been written toward the child's stdin and
    /// shell integration has recorded no prompt mark, so a foreground
    /// group that differs from the shell can only be the shell's own rc
    /// startup. A seed written then is ordinary type-ahead — the bytes
    /// wait in the tty input queue for the first prompt — because a pane
    /// that has never received input cannot be running a launched app.
    /// Without the carve-out, a Make Root landing inside that window
    /// silently skipped the seed and left the shell behind the Explorer
    /// (#94; under full-suite load the window stretches past the call).
    pub fn cwd_seed_is_safe(&self) -> bool {
        self.foreground_is_shell() || (!self.input_seen && self.marks.lock().unwrap().is_empty())
    }

    /// Test-only: the RESOLVED foreground sample — `Some(fg == shell)`
    /// when both sides are known, `None` otherwise. `foreground_is_shell`
    /// folds policy fallbacks (the startup carve-out, the fail-closed
    /// retry) into its answer, so a test precondition polling it can be
    /// satisfied by a fallback and race the state it believes it proved
    /// (#186); gate preconditions on `Some(..)` instead.
    #[cfg(test)]
    pub fn foreground_resolved_for_test(&self) -> Option<bool> {
        match (self.backend.process_group_leader(), self.shell_pid) {
            (Some(fg), Some(pid)) => Some(fg == pid),
            _ => None,
        }
    }

    /// True while the pane is exactly as croft created it: an interactive
    /// shell (never a `new_running` program pane, whose child is doing
    /// launched work with no input byte ever written) that has received
    /// no input and carries no manual name — nothing the user could miss
    /// if the pane were replaced. The re-root restore (#137) may swap
    /// only such panes for the incoming workspace's saved layout; any
    /// input (a keystroke, a paste, a seeded `cd`) or a rename clears
    /// this permanently.
    pub fn is_pristine(&self) -> bool {
        !self.run_pane && !self.input_seen && !self.manual_name_seen
    }

    /// Scroll the visible viewport up by `n` rows into scrollback.
    /// Returns false if the inner program is in alternate-screen mode
    /// (apps like vim/htop/less manage their own scrolling).
    pub fn scroll_up(&mut self, n: usize) -> bool {
        let mut term = self.term.lock();
        if term.mode().contains(TermMode::ALT_SCREEN) {
            return false;
        }
        term.scroll_display(Scroll::Delta(n as i32));
        self.pty_dirty.store(true, Ordering::Release);
        true
    }

    pub fn scroll_down(&mut self, n: usize) -> bool {
        let mut term = self.term.lock();
        if term.mode().contains(TermMode::ALT_SCREEN) {
            return false;
        }
        term.scroll_display(Scroll::Delta(-(n as i32)));
        self.pty_dirty.store(true, Ordering::Release);
        true
    }

    /// Jump the viewport to the oldest scrollback line (Shift+Home). No-op
    /// in the alternate screen, which has no scrollback.
    pub fn scroll_to_top(&mut self) -> bool {
        let mut term = self.term.lock();
        if term.mode().contains(TermMode::ALT_SCREEN) {
            return false;
        }
        term.scroll_display(Scroll::Top);
        drop(term);
        self.pty_dirty.store(true, Ordering::Release);
        true
    }

    /// Jump the viewport back to the live bottom (Shift+End). Returns false
    /// in the alternate screen — no scrollback there, so the chord belongs
    /// to the program, exactly like its three scrolling siblings.
    pub fn reset_scrollback(&mut self) -> bool {
        let mut term = self.term.lock();
        if term.mode().contains(TermMode::ALT_SCREEN) {
            return false;
        }
        term.scroll_display(Scroll::Bottom);
        self.pty_dirty.store(true, Ordering::Release);
        true
    }

    /// Clear the visible screen and scrollback history (VS Code's terminal
    /// "Clear"), homing the cursor. Feeds the standard erase sequences into the
    /// grid (`ED 3` wipes scrollback, `ED 2` the screen); the shell redraws its
    /// prompt on the next keystroke. Does not touch the running program.
    pub fn clear_screen_and_scrollback(&mut self) {
        let mut processor = Processor::<StdSyncHandler>::new();
        {
            let mut term = self.term.lock();
            // ED 2 BEFORE ED 3 (xterm.js / VS Code's clear() order):
            // alacritty's primary-screen ED 2 scrolls the viewport INTO
            // history rather than blanking in place, so erasing history
            // first would leave the "cleared" rows alive in scrollback.
            processor.advance(&mut *term, b"\x1b[2J\x1b[3J\x1b[H");
            term.scroll_display(Scroll::Bottom);
        }
        // The content the images and OSC 133 marks anchored to is gone;
        // keeping either leaves overlays (a floating picture, phantom
        // decoration dots whose menus copy or re-run the wrong rows) over
        // the fresh prompt.
        self.images.lock().unwrap().clear();
        self.marks.lock().unwrap().clear();
        self.pty_dirty.store(true, Ordering::Release);
    }

    /// The PTY grid's current column count.
    ///
    /// Test-only, and the point of it is #313: a collapsed pane must not be
    /// reflowed into its one-column strip. `resize` clamps to two columns, so
    /// a collapsed pane that got rendered would not crash - it would quietly
    /// rewrap the running shell to a two-column grid and lose everything on
    /// its screen. Reading the real grid width is what tells that apart from
    /// a pane that was simply left alone.
    #[cfg(test)]
    pub fn grid_cols(&self) -> u16 {
        self.cols
    }

    pub fn resize(&mut self, cols: u16, rows: u16) {
        // A degenerate pane (a host window shrunk to a sliver leaves the
        // layout no room) must not reach alacritty: Term::resize panics on
        // a zero/one-cell grid mid-reflow. Keep the last sane size; the
        // grid simply clips until the window grows back.
        let (cols, rows) = (cols.max(2), rows.max(2));
        if cols == self.cols && rows == self.rows {
            return;
        }
        self.cols = cols;
        self.rows = rows;
        *self.size_shared.lock().unwrap() = (cols, rows);
        // Grid first, pty second, under one hold of the grid lock (#473).
        // The pty ioctl delivers SIGWINCH, and a full-screen child answers
        // it with a complete repaint sized to the NEW dimensions. If that
        // repaint reaches the reader before the grid has been resized, it
        // is parsed into the old grid: rows land on the wrong lines, wide
        // lines wrap, and once the grid does grow those cells sit where a
        // diff-based renderer (Claude Code, and anything else that only
        // redraws what it believes changed) considers them already blank.
        // Nothing ever repaints them, and the stale text stays on screen.
        // Resizing the grid while holding the lock across the ioctl means
        // every byte the child emits in reply meets a grid of the right
        // size.
        let mut term = self.term.lock();
        let size = TermSize::new(cols as usize, rows as usize);
        term.resize(size);
        self.backend.resize(cols, rows);
        drop(term);
        self.pty_dirty.store(true, Ordering::Release);
    }
}

/// Where a pane's shell comes from.
enum PaneSource {
    /// Start `cmd`: on a PTY croft holds, or in a new pane host.
    Spawn { cmd: CommandBuilder, hosted: bool },
    /// Reattach to the pane host at this socket (#694).
    Attach(std::path::PathBuf),
}

/// Who holds a pane's PTY.
enum PaneBackend {
    /// croft: the PTY dies with croft.
    Local {
        master: Box<dyn MasterPty + Send>,
        child: Box<dyn portable_pty::Child + Send + Sync>,
    },
    /// A pane host (#694): the shell outlives croft. `conn` carries input,
    /// resizes and the kill; the pid comes from the host's greeting, and
    /// `exit` from its notice that the shell ended.
    Hosted {
        conn: Arc<std::sync::Mutex<std::os::unix::net::UnixStream>>,
        socket: std::path::PathBuf,
        pid: Option<u32>,
        exit: Arc<std::sync::Mutex<Option<i32>>>,
    },
}

impl PaneBackend {
    fn pid(&self) -> Option<u32> {
        match self {
            PaneBackend::Local { child, .. } => child.process_id(),
            PaneBackend::Hosted { pid, .. } => *pid,
        }
    }

    /// The terminal's foreground process group: `tcgetpgrp` on a PTY croft
    /// holds, the shell's `tpgid` from the process table for a hosted one
    /// (the same value, read without the master).
    fn process_group_leader(&self) -> Option<i32> {
        match self {
            PaneBackend::Local { master, .. } => master.process_group_leader(),
            PaneBackend::Hosted { pid, .. } => pid.and_then(|p| foreground_group_of(p as i32)),
        }
    }

    fn resize(&self, cols: u16, rows: u16) {
        match self {
            PaneBackend::Local { master, .. } => {
                let _ = master.resize(PtySize {
                    cols,
                    rows,
                    pixel_width: 0,
                    pixel_height: 0,
                });
            }
            PaneBackend::Hosted { conn, .. } => {
                let frame = crate::session_host::encode_control_frame(
                    &crate::session_host::Control::Resize { cols, rows },
                );
                let _ = conn.lock().unwrap().write_all(&frame);
            }
        }
    }

    /// The shell's exit code once it has ended, reaping it on a PTY croft
    /// holds (#912). A pane host reaps its own shell and sends the code
    /// before the pane's output closes, so it is read once
    /// `output_closed`; a host gone without sending one gives `Some(None)`.
    fn try_exit(&mut self, output_closed: bool) -> Option<Option<i32>> {
        match self {
            PaneBackend::Local { child, .. } => {
                let status = child.try_wait().ok()??;
                Some(Some(status.exit_code() as i32))
            }
            PaneBackend::Hosted { exit, .. } => output_closed.then(|| *exit.lock().unwrap()),
        }
    }

    /// End the shell: kill and reap it, or ask its host to (which ends the
    /// host too), then drop the connection so the demux thread ends.
    fn end(&mut self) {
        match self {
            PaneBackend::Local { child, .. } => {
                // A shell already reaped is never signalled: its pid may
                // name another process by now.
                if matches!(child.try_wait(), Ok(Some(_))) {
                    return;
                }
                let _ = child.kill();
                let _ = child.wait();
            }
            PaneBackend::Hosted { conn, .. } => {
                let frame =
                    crate::session_host::encode_control_frame(&crate::session_host::Control::Kill);
                let conn = conn.lock().unwrap();
                let _ = (&*conn).write_all(&frame);
                let _ = conn.shutdown(std::net::Shutdown::Both);
            }
        }
    }
}

/// The foreground process group of the terminal `pid` (a session leader)
/// controls: field 8 (`tpgid`) of `/proc/<pid>/stat` on Linux, the BSD
/// info's `e_tpgid` from `proc_pidinfo` on macOS. Hosted panes run only
/// where one of these answers.
#[cfg(target_os = "linux")]
fn foreground_group_of(pid: i32) -> Option<i32> {
    let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
    parse_tpgid(&stat)
}

#[cfg(target_os = "macos")]
fn foreground_group_of(pid: i32) -> Option<i32> {
    let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
    let size = std::mem::size_of::<libc::proc_bsdinfo>() as libc::c_int;
    // Our own child's info needs no entitlement, as for its cwd above.
    let got = unsafe {
        libc::proc_pidinfo(
            pid,
            libc::PROC_PIDTBSDINFO,
            0,
            (&mut info as *mut libc::proc_bsdinfo).cast(),
            size,
        )
    };
    if got != size {
        return None;
    }
    let tpgid = info.e_tpgid as i32;
    (tpgid > 0).then_some(tpgid)
}

#[cfg(not(any(target_os = "linux", target_os = "macos")))]
fn foreground_group_of(_pid: i32) -> Option<i32> {
    None
}

/// `tpgid` from a `/proc/<pid>/stat` line. The command name is in
/// parentheses and may hold spaces or parentheses itself, so the fields
/// are counted from the LAST `)`.
#[cfg(any(target_os = "linux", test))]
fn parse_tpgid(stat: &str) -> Option<i32> {
    let rest = &stat[stat.rfind(')')? + 1..];
    // state ppid pgrp session tty_nr tpgid
    let tpgid: i32 = rest.split_whitespace().nth(5)?.parse().ok()?;
    (tpgid > 0).then_some(tpgid)
}

/// Whether new shell panes go in pane hosts (#694): the
/// `terminal_persistent_panes` setting, on Linux and macOS, where a hosted
/// pane can still read its foreground process group.
fn persistent_panes_enabled() -> bool {
    cfg!(any(target_os = "linux", target_os = "macos"))
        && crate::prefs::Prefs::load_or_default().terminal_persistent_panes
}

/// What a pane needs from wherever its shell runs: bytes to it, bytes from
/// it with an fd to poll for them, and the shell's pid.
struct PaneLink {
    writer: Box<dyn Write + Send>,
    reader: Box<dyn Read + Send>,
    poll_fd: std::os::fd::RawFd,
    shell_pid: Option<i32>,
    backend: PaneBackend,
}

/// Input for a hosted pane: each write is one bytes frame.
struct HostInput(Arc<std::sync::Mutex<std::os::unix::net::UnixStream>>);

impl Write for HostInput {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        let frame = crate::session_host::encode_bytes_frame(buf);
        (&*self.0.lock().unwrap()).write_all(&frame)?;
        Ok(buf.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

impl PaneLink {
    fn open(source: PaneSource, cols: u16, rows: u16) -> Result<Self> {
        match source {
            PaneSource::Spawn { cmd, hosted: true } => {
                let spec = crate::pane_host::PaneSpec {
                    socket: crate::pane_host::socket_for(&crate::pane_host::new_pane_id()),
                    cwd: cmd.get_cwd().map(std::path::PathBuf::from),
                    env: cmd
                        .iter_full_env_as_str()
                        .map(|(k, v)| (k.to_string(), v.to_string()))
                        .collect(),
                    cols,
                    rows,
                    argv: cmd
                        .get_argv()
                        .iter()
                        .map(|a| a.to_string_lossy().into_owned())
                        .collect(),
                };
                // A host that cannot start (no socket dir, a sandbox) must
                // not cost the user a terminal: the pane is croft's instead.
                match crate::pane_host::spawn(&spec)
                    .and_then(|()| Self::attach(&spec.socket, cols, rows))
                {
                    Ok(link) => Ok(link),
                    // Nothing to print from here: a write to stderr would
                    // land on croft's own screen (#537).
                    Err(_) => Self::local(cmd, cols, rows),
                }
            }
            PaneSource::Spawn { cmd, hosted: false } => Self::local(cmd, cols, rows),
            PaneSource::Attach(socket) => Self::attach(&socket, cols, rows),
        }
    }

    fn local(cmd: CommandBuilder, cols: u16, rows: u16) -> Result<Self> {
        let pair = native_pty_system()
            .openpty(PtySize {
                cols,
                rows,
                pixel_width: 0,
                pixel_height: 0,
            })
            .context("openpty")?;
        let child = pair.slave.spawn_command(cmd).context("spawn child")?;
        let shell_pid = child.process_id().map(|p| p as i32);
        drop(pair.slave);
        let writer = pair.master.take_writer().context("take writer")?;
        let reader = pair.master.try_clone_reader().context("clone reader")?;
        let poll_fd = pair
            .master
            .as_raw_fd()
            .context("pty master has no raw fd")?;
        Ok(Self {
            writer,
            reader,
            poll_fd,
            shell_pid,
            backend: PaneBackend::Local {
                master: pair.master,
                child,
            },
        })
    }

    /// Attach to a pane host: read its greeting for the shell's pid, then
    /// hand the pane a pipe a demux thread fills with the shell's bytes
    /// (the redraw first), so the reader reads it exactly as it reads a
    /// PTY. The pipe closes when the host says the shell exited or the
    /// connection ends, which the reader sees as the PTY's EOF.
    fn attach(socket: &std::path::Path, cols: u16, rows: u16) -> Result<Self> {
        use crate::session_host::{Control, Frame, FrameReader};
        use std::os::fd::AsRawFd;
        let stream = crate::pane_host::PaneClient::connect(socket, cols, rows)?.into_stream();
        let mut rd = stream
            .try_clone()
            .context("cloning the pane host connection")?;
        rd.set_read_timeout(Some(std::time::Duration::from_secs(5)))?;
        let mut frames = FrameReader::new();
        let mut pending: Vec<u8> = Vec::new();
        let mut pid = None;
        // A shell that exits while it attaches can have its exit arrive in
        // the same read as the greeting (#912): kept, not dropped with the
        // frames the greeting has no use for.
        let mut greeting_exit = None;
        let mut buf = [0u8; 65536];
        while pid.is_none() {
            let n = rd
                .read(&mut buf)
                .context("reading the pane host's greeting")?;
            anyhow::ensure!(n > 0, "the pane host at {} closed", socket.display());
            for frame in frames.push(&buf[..n]) {
                match frame {
                    Frame::Control(Control::PaneInfo { pid: p }) => pid = Some(p),
                    Frame::Bytes(b) => pending.extend_from_slice(&b),
                    Frame::Control(Control::Exit { code }) => greeting_exit = Some(code),
                    _ => {}
                }
            }
        }
        rd.set_read_timeout(None)?;
        let (pipe_r, mut pipe_w) = std::io::pipe().context("pane host pipe")?;
        let exited = greeting_exit.is_some();
        let exit = Arc::new(std::sync::Mutex::new(greeting_exit));
        let exit_for_demux = exit.clone();
        std::thread::spawn(move || {
            if pipe_w.write_all(&pending).is_err() || exited {
                return;
            }
            let mut buf = [0u8; 65536];
            loop {
                let n = match rd.read(&mut buf) {
                    Ok(0) | Err(_) => return,
                    Ok(n) => n,
                };
                for frame in frames.push(&buf[..n]) {
                    match frame {
                        Frame::Bytes(b) => {
                            if pipe_w.write_all(&b).is_err() {
                                return;
                            }
                        }
                        Frame::Control(Control::Exit { code }) => {
                            *exit_for_demux.lock().unwrap() = Some(code);
                            return;
                        }
                        _ => {}
                    }
                }
            }
        });
        let conn = Arc::new(std::sync::Mutex::new(stream));
        Ok(Self {
            writer: Box::new(HostInput(conn.clone())),
            poll_fd: pipe_r.as_raw_fd(),
            reader: Box::new(pipe_r),
            shell_pid: pid.map(|p| p as i32),
            backend: PaneBackend::Hosted {
                conn,
                socket: socket.to_path_buf(),
                pid,
                exit,
            },
        })
    }
}

/// Block until the pty has data (or EOF/error — the following `read` then
/// observes it), until the shutdown pipe signals (its write end closed in
/// `Drop`), or until `deadline`, when there is one, passes (#1541). A bare
/// blocking `read` is not enough to ever exit: on Linux a background job
/// keeps the pty slave open after the shell dies, so the read never returns
/// and joining the reader would freeze the UI for as long as the job runs.
fn wait_pty_readable(
    pty_fd: std::os::fd::RawFd,
    shutdown: &std::io::PipeReader,
    deadline: Option<std::time::Instant>,
) -> PtyWait {
    loop {
        let timeout = match deadline {
            None => -1,
            Some(d) => {
                let left = d.saturating_duration_since(std::time::Instant::now());
                // Rounded up, so the wake is never early.
                left.as_micros().div_ceil(1000).min(i32::MAX as u128) as i32
            }
        };
        match poll_pty(pty_fd, shutdown, timeout) {
            // Woken before `deadline` all the same: wait out the rest.
            PtyWait::Idle if deadline.is_some_and(|d| std::time::Instant::now() < d) => {}
            wait => return wait,
        }
    }
}

/// How long the reader waits for more output before sending a held-back
/// dev-server URL as it stands.
const PORT_URL_SETTLE_MS: i32 = 150;

/// How long a pane whose shell was reaped waits for its output to close
/// before reporting the exit anyway: on Linux a background job the shell
/// left running keeps the pty open (see [`wait_pty_readable`]).
const EXIT_OUTPUT_GRACE: std::time::Duration = std::time::Duration::from_millis(500);

/// What [`poll_pty`] saw.
#[derive(Debug, PartialEq, Eq)]
enum PtyWait {
    /// The pty has output.
    Ready,
    /// Shutdown was signalled, or polling failed.
    Closed,
    /// `timeout_ms` passed with neither.
    Idle,
}

/// [`wait_pty_readable`] with a timeout in milliseconds (`-1` waits forever).
fn poll_pty(
    pty_fd: std::os::fd::RawFd,
    shutdown: &std::io::PipeReader,
    timeout_ms: i32,
) -> PtyWait {
    use std::os::fd::AsRawFd;
    let mut fds = [
        libc::pollfd {
            fd: pty_fd,
            events: libc::POLLIN,
            revents: 0,
        },
        libc::pollfd {
            fd: shutdown.as_raw_fd(),
            events: libc::POLLIN,
            revents: 0,
        },
    ];
    loop {
        let n = unsafe { libc::poll(fds.as_mut_ptr(), 2, timeout_ms) };
        if n < 0 {
            if std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted {
                continue;
            }
            return PtyWait::Closed;
        }
        if n == 0 {
            return PtyWait::Idle;
        }
        if fds[1].revents != 0 {
            return PtyWait::Closed;
        }
        if fds[0].revents != 0 {
            return PtyWait::Ready;
        }
    }
}

impl Drop for PtyTerminal {
    fn drop(&mut self) {
        // Kill the shell AND reap it: `kill()` reaps only when the shell dies
        // inside its SIGHUP grace loop; the SIGKILL escalation (a shell that
        // traps HUP) never waits, and `Child`'s own drop doesn't either, so
        // without the `wait` every such closed pane left a zombie for the
        // life of the process. The responder thread ends on its own once
        // `self.term` (holding its channel sender) drops with this struct.
        //
        // A hosted pane (#694) asks its host to end the shell the same way:
        // closing a pane or quitting ends it, and only a croft that dies
        // without dropping its panes leaves hosts to reattach to.
        self.backend.end();
        // Free the rewind buffer now and hand its share of the budget back
        // to the other panes (#694). Not left to the Arc: the reader thread
        // holds a clone until it is joined below.
        crate::rewind::budget().release(&self.rewind);
        // Wake the reader (POLLHUP on its shutdown fd) and join it. EOF alone
        // is not a reliable wake: see `wait_pty_readable`.
        drop(self.reader_shutdown.take());
        if let Some(handle) = self.reader_thread.take() {
            let _ = handle.join();
        }
    }
}

/// The logical line grid row `line_idx` belongs to (its soft-wrapped
/// neighbours joined, at most 64 rows either way) and the char offset of
/// that row's text within it, both in `row_text_and_cols` terms.
pub fn logical_row_text(term: &Term<VoidListener>, line_idx: i32) -> (String, usize) {
    let (joined, offset, _start) = logical_row_span(term, line_idx);
    (joined, offset)
}

/// [`logical_row_text`] plus the absolute grid line the logical line starts
/// on, which names a find match (see [`FindLine::start`]).
pub fn logical_row_span(term: &Term<VoidListener>, line_idx: i32) -> (String, usize, i32) {
    const REACH: i32 = 64;
    let top = term.grid().topmost_line().0;
    let bottom = term.screen_lines() as i32 - 1;
    let mut start = line_idx;
    while start > top && line_idx - start < REACH && row_wraps(term, start - 1) {
        start -= 1;
    }
    let mut end = line_idx;
    while end < bottom && end - line_idx < REACH && row_wraps(term, end) {
        end += 1;
    }
    let mut joined = String::new();
    let mut offset = 0;
    for l in start..=end {
        let (s, _) = row_text_and_cols(term, l);
        if l == line_idx {
            offset = joined.chars().count();
        }
        joined.push_str(&s);
    }
    (joined, offset, start)
}

/// Every grid row from the top of the scrollback, with its soft-wrap flag
/// and the absolute line of row 0: see [`PtyTerminal::grid_lines_wrapped`].
fn grid_rows_wrapped(term: &Term<VoidListener>) -> (Vec<String>, Vec<bool>, i32) {
    if term.columns() == 0 {
        return (Vec::new(), Vec::new(), 0);
    }
    let top = term.grid().topmost_line().0;
    let bottom = term.screen_lines() as i32 - 1;
    let mut lines = Vec::new();
    let mut wraps = Vec::new();
    let mut l = top;
    while l <= bottom {
        let (s, _cols) = row_text_and_cols(term, l);
        // A wrapped row keeps its trailing blanks: a space in its last
        // column separates words of the logical line (`Bearer ` then the
        // token), and trimming it glued them so a redact rule missed.
        let wraps_on = l < bottom && row_wraps(term, l);
        lines.push(if wraps_on {
            s
        } else {
            s.trim_end().to_string()
        });
        wraps.push(wraps_on);
        l += 1;
    }
    (lines, wraps, top)
}

/// One logical line of terminal output as find sees it: a run of rows the
/// pane soft-wrapped, joined back into the text that was printed (#1275).
/// A match position is a char index into `text`; `start` is the absolute
/// grid line of its first row.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FindLine {
    pub text: String,
    pub start: i32,
    /// Chars per row, in order, so a position maps back to its row.
    pub row_lens: Vec<usize>,
}

impl FindLine {
    /// The absolute grid line holding char `col` of this logical line.
    pub fn line_of(&self, col: usize) -> i32 {
        let mut seen = 0;
        for (i, len) in self.row_lens.iter().enumerate() {
            seen += len;
            if col < seen {
                return self.start + i as i32;
            }
        }
        self.start + self.row_lens.len().saturating_sub(1) as i32
    }
}

/// Join each run of rows whose wrap flag is set into one [`FindLine`]. A
/// row without the flag ends its line, so rows that merely sit next to each
/// other are never searched as one.
pub fn join_wrapped_rows(lines: Vec<String>, wraps: &[bool], top: i32) -> Vec<FindLine> {
    let mut out: Vec<FindLine> = Vec::new();
    let mut continues = false;
    for (i, row) in lines.into_iter().enumerate() {
        let len = row.chars().count();
        match out.last_mut() {
            Some(line) if continues => {
                line.text.push_str(&row);
                line.row_lens.push(len);
            }
            _ => out.push(FindLine {
                text: row,
                start: top + i as i32,
                row_lens: vec![len],
            }),
        }
        continues = wraps.get(i).copied().unwrap_or(false);
    }
    out
}

/// Grid rows from `top` to the bottom of the screen as `(plain, coloured,
/// wraps)`: see [`PtyTerminal::grid_lines_ansi_wrapped`], which reads from
/// the top of the scrollback, and [`PtyTerminal::screen_ansi_wrapped`],
/// which reads the visible screen only.
fn ansi_rows(term: &Term<VoidListener>, top: i32) -> Vec<(String, String, bool)> {
    let bottom = term.screen_lines() as i32 - 1;
    let ncols = term.columns();
    let mut lines = Vec::new();
    let mut l = top;
    while l <= bottom {
        // Cells are collected as (char, style key) - three Copy values,
        // no allocation per cell - so trailing default-styled blanks can
        // be trimmed before anything is serialised, and the SGR string
        // is built once per run of equal style rather than once per
        // cell. This runs under the term lock the reader thread shares,
        // and a saturated scrollback is hundreds of thousands of rows.
        let mut cells: Vec<(char, (AnsiColor, AnsiColor, Flags))> = Vec::with_capacity(ncols);
        for c in 0..ncols {
            let cell = &term.grid()[Point::new(Line(l), Column(c))];
            if cell
                .flags
                .intersects(Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER)
            {
                continue;
            }
            let ch = cell_glyph(cell.c);
            // Only the flags an SGR carries: the soft-wrap mark on a row's
            // last cell and a wide char's own flag are not styles, and keyed
            // on them a run of one colour was reset and set again around them
            // (a cast wrote `w\e[0m\e[33mr` at the wrap column, #356).
            cells.push((ch, (cell.fg, cell.bg, cell.flags & SGR_FLAGS)));
        }
        let wraps_on = l < bottom && row_wraps(term, l);
        let plain: String = cells.iter().map(|(ch, _)| *ch).collect::<String>();
        // Trailing blanks trimmed only where the row does not wrap (see
        // `grid_lines_wrapped`).
        let plain = if wraps_on {
            plain
        } else {
            plain.trim_end().to_string()
        };
        while cells
            .last()
            .is_some_and(|(ch, (fg, bg, flags))| *ch == ' ' && style_is_default(*fg, *bg, *flags))
        {
            cells.pop();
        }
        let mut out = String::new();
        let mut current: Option<(AnsiColor, AnsiColor, Flags)> = None;
        let mut styled = false;
        for (ch, key) in cells {
            if current != Some(key) {
                if styled {
                    out.push_str("\x1b[0m");
                }
                let sgr = cell_sgr(key.0, key.1, key.2);
                styled = !sgr.is_empty();
                out.push_str(&sgr);
                current = Some(key);
            }
            out.push(ch);
        }
        if styled {
            out.push_str("\x1b[0m");
        }
        lines.push((plain, out, wraps_on));
        l += 1;
    }
    lines
}

/// [`ansi_rows`] for another module's model of a pane (#694's pane host).
pub(crate) fn ansi_rows_from(term: &Term<VoidListener>, top: i32) -> Vec<(String, String, bool)> {
    ansi_rows(term, top)
}

/// Whether grid row `line_idx` soft-wraps into the next (WRAPLINE on its
/// last cell).
pub fn row_wraps(term: &Term<VoidListener>, line_idx: i32) -> bool {
    let cols = term.columns();
    cols > 0
        && term.grid()[Point::new(Line(line_idx), Column(cols - 1))]
            .flags
            .contains(Flags::WRAPLINE)
}

/// Walk the visible grid from (sr, sc) to (er, ec) inclusive, joining
/// cell contents row-by-row, trimming trailing whitespace per row, and
/// inserting `\n` between rows. Coordinates are viewport-relative;
/// `display_offset` is the alacritty grid's current scrollback offset
/// (number of rows the viewport has been scrolled back from the live
/// bottom). The grid line we read is `row - display_offset`, which is
/// negative when the user has scrolled into history — alacritty's
/// `Grid::index<Point>` accepts those negative `Line` values and
/// returns the scrollback cell, so the extracted text matches exactly
/// what the user sees highlighted on screen. Without the subtraction
/// the function silently re-reads the live grid at the viewport row,
/// which is a different cell entirely once `display_offset > 0` and
/// the user gets the wrong line on the clipboard.
/// What a grid cell shows: a blank for an empty cell and for a control
/// char. alacritty leaves `'\t'` in the cell a TAB started from so copy
/// can give the tab back, but painted raw the host terminal jumps to its
/// own tab stop while ratatui counts one cell, and the rest of the row
/// lands too far right over the previous frame's text (#1287).
fn cell_glyph(c: char) -> char {
    if c == '\0' || c.is_control() { ' ' } else { c }
}

/// One grid row as text plus a char-index → grid-column map. A wide char
/// (CJK, emoji) occupies two grid columns — the `WIDE_CHAR` cell and a
/// spacer cell — so the spacers are skipped, making the text read
/// contiguously (`"日本語"`, never `"日 本 語"`). `cols[i]` is the grid
/// column the i-th char starts at, so highlight painters can map a match's
/// char range back onto grid cells.
pub fn row_text_and_cols(term: &Term<VoidListener>, line_idx: i32) -> (String, Vec<usize>) {
    let ncols = term.columns();
    let mut s = String::with_capacity(ncols);
    let mut cols = Vec::with_capacity(ncols);
    for c in 0..ncols {
        let cell = &term.grid()[Point::new(Line(line_idx), Column(c))];
        if cell
            .flags
            .intersects(Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER)
        {
            continue;
        }
        s.push(cell_glyph(cell.c));
        cols.push(c);
    }
    (s, cols)
}

/// The typed text of the command now ending: from the newest PromptEnd
/// (`133;B`) cell to the line before the newest CommandStart (`133;C`) —
/// the same span `pair_decorations` derives after the fact. Runs in the
/// reader thread at the `133;D` mark with the term lock held; empty when
/// the B/C marks are missing (no shell integration on this pane).
fn last_command_input_text(
    term: &Term<VoidListener>,
    marks: &[StoredMark],
    clock_now: i64,
) -> String {
    use crate::shell_integration::OscEvent as E;
    let cur = |m: &StoredMark| m.line_rec - (clock_now - m.clock_rec) as i32;
    let Some(ci) = marks
        .iter()
        .rposition(|m| matches!(m.kind, E::CommandStart))
    else {
        return String::new();
    };
    let Some(b) = marks[..ci]
        .iter()
        .rev()
        .find(|m| matches!(m.kind, E::PromptEnd))
    else {
        return String::new();
    };
    let bl = cur(b);
    let cl = cur(&marks[ci]);
    if cl <= bl {
        return String::new();
    }
    without_continuation_prompts(&extract_selection_text(
        term,
        bl,
        b.col_rec,
        cl - 1,
        term.columns().saturating_sub(1),
    ))
}

/// Typed input read off the screen, minus the shell's continuation prompt
/// on each line after the first (#1250). Only a hard newline starts such a
/// line, so a soft-wrapped row is never touched. The prompt is bash's `> `
/// or zsh's `%_> ` (`for> `, `cmdsubst dquote> `); stored as input, a
/// recalled command would run it as a redirect.
fn without_continuation_prompts(text: &str) -> String {
    let strip = |line: &str| -> String {
        let is_ps2 = |head: &str| {
            !head.starts_with(' ') && head.chars().all(|c| c.is_ascii_lowercase() || c == ' ')
        };
        if let Some(i) = line.find("> ")
            && is_ps2(&line[..i])
        {
            return line[i + 2..].to_string();
        }
        match line.strip_suffix('>') {
            Some(head) if is_ps2(head) => String::new(),
            _ => line.to_string(),
        }
    };
    let mut lines = text.split('\n');
    let mut out = lines.next().unwrap_or_default().to_string();
    for line in lines {
        out.push('\n');
        out.push_str(&strip(line));
    }
    out
}

/// The finished command's OUTPUT: the rows from `start`, its first output
/// row in current grid coordinates, to the row the cursor sits on as its
/// `133;D` arrives. Escape-free (the grid never stores escapes), tail-capped
/// at [`FINISHED_OUTPUT_CAP_LINES`].
fn command_output_text(term: &Term<VoidListener>, start: i32) -> String {
    // The cursor row is INCLUDED: `133;D` moves no cursor, so a diagnostic
    // printed without a trailing newline leaves the mark ON that row — the
    // old `- 1` dropped exactly the line the matchers needed. With a
    // trailing newline the cursor row is a fresh blank, trimmed below.
    let end = term.grid().cursor.point.line.0;
    if end < start {
        return String::new();
    }
    let text = extract_selection_text(term, start, 0, end, term.columns().saturating_sub(1));
    let text = text.trim_end_matches('\n');
    let lines: Vec<&str> = text.lines().collect();
    if lines.len() > FINISHED_OUTPUT_CAP_LINES {
        lines[lines.len() - FINISHED_OUTPUT_CAP_LINES..].join("\n")
    } else {
        text.to_string()
    }
}

/// Epoch millis → local wall-clock `HH:MM:SS` (libc localtime, the same
/// no-date-crate route the trash metadata writer takes).
fn hhmmss(millis: u64) -> String {
    // `localtime_r` takes a `*const time_t`, so the binding's own definition is
    // the only correct type here. musl's is mid-migration to 64-bit and libc
    // marks the alias deprecated ahead of the change, which `-D warnings`
    // turns into a build error on the Linux targets; naming the field type
    // through `tm` is not possible (it has no `time_t` member), so the alias
    // stays and the deprecation is acknowledged at this one call.
    #[allow(deprecated)]
    let secs = (millis / 1000) as libc::time_t;
    let mut tm: libc::tm = unsafe { std::mem::zeroed() };
    if unsafe { libc::localtime_r(&secs, &mut tm) }.is_null() {
        return String::from("--:--:--");
    }
    format!("{:02}:{:02}:{:02}", tm.tm_hour, tm.tm_min, tm.tm_sec)
}

/// The surviving column spans of a block row that app chrome partially
/// overdrew: the longest common prefix and suffix between the remembered
/// row and what the grid shows. Returns the grid-column ranges to keep
/// highlighted — a pill floating over the middle of a row leaves BOTH
/// intact ends lit.
fn partial_overlap_cols(want: &str, got: &str, colmap: &[usize]) -> Vec<(u16, u16)> {
    // Row text is full grid width: strip the trailing blank run or it
    // counts as a huge shared suffix between any two rows.
    let want = want.trim_end();
    let got = got.trim_end();
    let want_n = want.chars().count();
    let got_n = got.chars().count();
    if want_n == 0 || got_n == 0 {
        return Vec::new();
    }
    let prefix = want
        .chars()
        .zip(got.chars())
        .take_while(|(a, b)| a == b)
        .count();
    let suffix = want
        .chars()
        .rev()
        .zip(got.chars().rev())
        .take_while(|(a, b)| a == b)
        .count();
    // Each surviving end must carry real content, not just indentation.
    // No minimum share of the row: a pill over the MIDDLE leaves both
    // ends under half, and this credit is paint-only — the shift was
    // already anchored by exact rows, so it can't move the highlight.
    let solid =
        |chars: &mut dyn Iterator<Item = char>| chars.filter(|c| !c.is_whitespace()).count() >= 4;
    let good_prefix = prefix > 0 && solid(&mut want.chars().take(prefix));
    let good_suffix = suffix > 0 && solid(&mut want.chars().rev().take(suffix));
    let mut spans = Vec::new();
    if good_prefix && good_suffix && prefix + suffix >= got_n {
        // The ends overlap: the row differs by a few mid-row cells (an
        // animated counter ticking inside the selection) — keep it whole.
        spans.push((colmap[0] as u16, colmap[got_n - 1] as u16));
    } else {
        if good_prefix {
            spans.push((colmap[0] as u16, colmap[prefix - 1] as u16));
        }
        if good_suffix {
            spans.push((colmap[got_n - suffix] as u16, colmap[got_n - 1] as u16));
        }
    }
    spans
}

/// Capture the content anchor for an alternate-screen selection: its row
/// text and extracted text as the grid shows them now. `None` when any
/// selected line is outside the grid (a partially scrolled-out block keeps
/// its previous, fuller anchor instead).
fn capture_alt_anchor(term: &Term<VoidListener>, sel: Selection) -> Option<AltSelAnchor> {
    let rows_vis = term.screen_lines() as i32;
    let (lo, hi) = (sel.anchor.0.min(sel.head.0), sel.anchor.0.max(sel.head.0));
    if lo < 0 || hi >= rows_vis {
        return None;
    }
    let rows = (lo..=hi).map(|l| row_text_and_cols(term, l).0).collect();
    let ctx_above = (lo > 0).then(|| row_text_and_cols(term, lo - 1).0);
    let ctx_below = (hi + 1 < rows_vis).then(|| row_text_and_cols(term, hi + 1).0);
    let text = if sel.block {
        let (rl, cl, rh, ch) = sel.block_bounds();
        block_selection_text(term, rl, cl as usize, rh, ch as usize)
    } else {
        let (sr, sc, er, ec) = sel.normalised();
        extract_selection_text(term, sr, sc as usize, er, ec as usize)
    };
    Some(AltSelAnchor {
        rows,
        top: lo,
        text,
        dormant: false,
        visible: None,
        ctx_above,
        ctx_below,
    })
}

pub fn extract_selection_text(
    term: &Term<VoidListener>,
    sr: i32,
    sc: usize,
    er: i32,
    ec: usize,
) -> String {
    let cols = term.columns();
    // Clamp the range to the grid: the newest live line is
    // `screen_lines - 1`; the oldest readable line is the grid's topmost
    // (scrollback floor). Reading outside that panics alacritty's index.
    let max_line = term.screen_lines() as i32 - 1;
    let min_line = term.grid().topmost_line().0;
    let sr = sr.max(min_line);
    let er = er.min(max_line);
    let mut out = String::new();
    let mut line_idx = sr;
    while line_idx <= er {
        let row_start = if line_idx == sr { sc } else { 0 };
        let row_end = if line_idx == er {
            ec.min(cols.saturating_sub(1))
        } else {
            cols.saturating_sub(1)
        };
        let mut line = String::new();
        for col in row_start..=row_end {
            let p = Point::new(Line(line_idx), Column(col));
            let cell = &term.grid()[p];
            // A wide char's spacer cell holds no glyph of its own — skip it
            // so copied CJK/emoji text comes out contiguous.
            if cell
                .flags
                .intersects(Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER)
            {
                continue;
            }
            let c = cell.c;
            if c == '\0' {
                line.push(' ');
            } else {
                line.push(c);
            }
            // Combining marks ride on the cell after its base char: `café`
            // typed as `e` + U+0301 copied as `cafe` without them.
            if let Some(marks) = cell.zerowidth() {
                line.extend(marks.iter());
            }
        }
        // A soft-wrapped row (WRAPLINE on its last cell) continues the
        // same logical line: no separator, so copied text, the durable
        // command history, and the sticky header all see the line the user
        // actually typed — a '\n' here corrupted stored commands and re-ran
        // only their first fragment on paste. A hard row break keeps the
        // newline. Only a hard break is trimmed: a space in a wrapped row's
        // last column is part of the line (`echo abcd efg` in ten columns
        // copied as `echo abcdefg`).
        let wrapped = line_idx != er
            && cols > 0
            && term.grid()[Point::new(Line(line_idx), Column(cols - 1))]
                .flags
                .contains(Flags::WRAPLINE);
        out.push_str(if wrapped { &line } else { line.trim_end() });
        if line_idx != er && !wrapped {
            out.push('\n');
        }
        line_idx += 1;
    }
    out
}

/// Inspect a row of `term` around `(row, col)` (both viewport-relative)
/// and return the anchor/head pair that brackets the contiguous run of
/// word characters covering the pivot. `display_offset` is the
/// alacritty grid's current scroll-back offset so the lookup
/// `Line(row - display_offset)` resolves to the scrollback cell when
/// the user has scrolled into history. Without this, a double-click
/// on text the user sees on screen but lives in scrollback would read
/// the live grid at the same viewport y, which is usually blank — so
/// `is_terminal_word_char` returns false and the function returns
/// `None`, giving the user-visible symptom "double-click doesn't
/// auto-select."
///
/// Returns `None` when the pivot sits on a non-word character
/// (whitespace, punctuation), so a double click between words is a
/// no-op rather than a spurious selection. Word semantics match
/// `widgets::editor::is_word_char`: alphanumeric + underscore. Pure
/// function so the test suite can exercise it without spawning a PTY.
pub fn select_word_at_in_term(
    term: &Term<VoidListener>,
    display_offset: usize,
    row: usize,
    col: usize,
) -> Option<((u16, u16), (u16, u16))> {
    let cols = term.columns();
    if col >= cols {
        return None;
    }
    let row_idx = row as i32 - display_offset as i32;
    let cell_char = |c: usize| -> char {
        let p = Point::new(Line(row_idx), Column(c));
        let ch = term.grid()[p].c;
        if ch == '\0' { ' ' } else { ch }
    };
    if !is_terminal_word_char(cell_char(col)) {
        return None;
    }
    let mut start = col;
    while start > 0 && is_terminal_word_char(cell_char(start - 1)) {
        start -= 1;
    }
    let mut end = col;
    while end + 1 < cols && is_terminal_word_char(cell_char(end + 1)) {
        end += 1;
    }
    Some(((row as u16, start as u16), (row as u16, end as u16)))
}

pub fn is_terminal_word_char(c: char) -> bool {
    c.is_alphanumeric() || c == '_'
}

/// Encode a mouse event as the byte sequence a child program expects.
/// `sgr` selects SGR (1006) encoding over legacy X10. `local_col`/`local_row`
/// are 0-based cells within the pane; the wire protocol is 1-based, so both
/// are offset by one. Button/modifier bit layout follows xterm: Left/Middle/
/// Right = 0/1/2, wheel up/down = 64/65, +32 for motion, +4/+8/+16 for
/// Shift/Alt/Ctrl. Under X10 a release reports button code 3 and coordinates
/// clamp to 223 (the largest a single 0x20-based byte can carry).
pub fn encode_mouse_report(
    sgr: bool,
    button: MouseButtonKind,
    action: MouseAction,
    local_col: u16,
    local_row: u16,
    mods: MouseMods,
) -> Vec<u8> {
    let mut cb: u8 = match button {
        MouseButtonKind::Left => 0,
        MouseButtonKind::Middle => 1,
        MouseButtonKind::Right => 2,
        MouseButtonKind::WheelUp => 64,
        MouseButtonKind::WheelDown => 65,
    };
    if action == MouseAction::Motion {
        cb += 32;
    }
    if mods.shift {
        cb += 4;
    }
    if mods.alt {
        cb += 8;
    }
    if mods.ctrl {
        cb += 16;
    }
    let cx = local_col + 1;
    let cy = local_row + 1;
    if sgr {
        let terminator = if action == MouseAction::Release {
            'm'
        } else {
            'M'
        };
        format!("\x1b[<{cb};{cx};{cy}{terminator}").into_bytes()
    } else {
        if action == MouseAction::Release {
            cb = (cb & !0b11) | 0b11;
        }
        let enc = |v: u16| (v.min(223) as u8).wrapping_add(32);
        vec![0x1b, b'[', b'M', cb.wrapping_add(32), enc(cx), enc(cy)]
    }
}

/// Build the byte sequence that retargets a POSIX shell's working
/// directory to `path`. Prefixed with `\x05\x15` so cursor moves to end
/// of line and the existing line is killed backward before the `cd` is
/// typed - that way a half-typed command at the prompt does not
/// concatenate with our `cd`. Path is single-quoted with embedded
/// quotes escaped via the standard `'\''` sleight-of-hand so paths
/// containing spaces or apostrophes round-trip safely.
pub fn format_cd_command(path: &std::path::Path) -> Vec<u8> {
    let s = path.to_string_lossy();
    let mut out = Vec::with_capacity(s.len() + 8);
    out.extend_from_slice(b"\x05\x15cd '");
    for c in s.chars() {
        if c == '\'' {
            out.extend_from_slice(b"'\\''");
        } else {
            let mut buf = [0u8; 4];
            out.extend_from_slice(c.encode_utf8(&mut buf).as_bytes());
        }
    }
    out.extend_from_slice(b"'\n");
    out
}

/// Build the OSC 52 escape sequence that asks the host terminal to put
/// `text` on the system clipboard.
pub fn osc52_copy_seq(text: &str) -> Vec<u8> {
    use base64::Engine;
    let encoded = base64::engine::general_purpose::STANDARD.encode(text.as_bytes());
    let mut out = Vec::with_capacity(encoded.len() + 8);
    out.extend_from_slice(b"\x1b]52;c;");
    out.extend_from_slice(encoded.as_bytes());
    out.push(0x07);
    out
}

/// The cell flags [`cell_sgr`] writes as SGR: everything else a cell carries
/// (wrap marks, wide-char spacers) is layout, not style.
const SGR_FLAGS: Flags = Flags::BOLD
    .union(Flags::DIM)
    .union(Flags::ITALIC)
    .union(Flags::UNDERLINE)
    .union(Flags::DOUBLE_UNDERLINE)
    .union(Flags::UNDERCURL)
    .union(Flags::DOTTED_UNDERLINE)
    .union(Flags::DASHED_UNDERLINE)
    .union(Flags::INVERSE)
    .union(Flags::HIDDEN)
    .union(Flags::STRIKEOUT);

/// The SGR sequence that reproduces a cell's colours and attributes, or an
/// empty string for a default cell (#257). Named and low-indexed colours go
/// out as the 16 standard codes so the reader resolves them through ITS
/// theme palette, the way the pane does; the 256-cube and truecolour pass
/// through as `38;5;n` / `38;2;r;g;b`.
fn cell_sgr(fg: AnsiColor, bg: AnsiColor, flags: Flags) -> String {
    let mut codes: Vec<String> = Vec::new();
    if flags.contains(Flags::BOLD) {
        codes.push("1".into());
    }
    if flags.contains(Flags::DIM) {
        codes.push("2".into());
    }
    if flags.contains(Flags::ITALIC) {
        codes.push("3".into());
    }
    if flags.intersects(
        Flags::UNDERLINE
            | Flags::DOUBLE_UNDERLINE
            | Flags::UNDERCURL
            | Flags::DOTTED_UNDERLINE
            | Flags::DASHED_UNDERLINE,
    ) {
        codes.push("4".into());
    }
    if flags.contains(Flags::INVERSE) {
        codes.push("7".into());
    }
    if flags.contains(Flags::HIDDEN) {
        codes.push("8".into());
    }
    if flags.contains(Flags::STRIKEOUT) {
        codes.push("9".into());
    }
    if let Some(code) = color_sgr(fg, false) {
        codes.push(code);
    }
    if let Some(code) = color_sgr(bg, true) {
        codes.push(code);
    }
    if codes.is_empty() {
        String::new()
    } else {
        format!("\x1b[{}m", codes.join(";"))
    }
}

/// Whether a cell carries no colour and no attribute the export would
/// write: the cheap test the trailing-blank trim uses, with no SGR string
/// built to find out.
fn style_is_default(fg: AnsiColor, bg: AnsiColor, flags: Flags) -> bool {
    let plain = |c: AnsiColor| matches!(c, AnsiColor::Named(n) if named_slot(n).is_none());
    plain(fg)
        && plain(bg)
        && !flags.intersects(
            Flags::BOLD
                | Flags::DIM
                | Flags::ITALIC
                | Flags::UNDERLINE
                | Flags::DOUBLE_UNDERLINE
                | Flags::UNDERCURL
                | Flags::DOTTED_UNDERLINE
                | Flags::DASHED_UNDERLINE
                | Flags::INVERSE
                | Flags::HIDDEN
                | Flags::STRIKEOUT,
        )
}

/// One colour as its SGR parameter(s): `30..37`/`90..97` (or the `40..`
/// / `100..` background forms) for the 16 slots, `38;5;n` beyond them,
/// `38;2;r;g;b` for truecolour, `None` for the default colour.
fn color_sgr(c: AnsiColor, background: bool) -> Option<String> {
    let base = if background { 40 } else { 30 };
    let bright = if background { 100 } else { 90 };
    let extended = if background { 48 } else { 38 };
    let slot = |i: u8| {
        if i < 8 {
            (base + i as u16).to_string()
        } else {
            (bright + (i - 8) as u16).to_string()
        }
    };
    match c {
        AnsiColor::Spec(rgb) => Some(format!("{extended};2;{};{};{}", rgb.r, rgb.g, rgb.b)),
        AnsiColor::Indexed(i) if i < 16 => Some(slot(i)),
        AnsiColor::Indexed(i) => Some(format!("{extended};5;{i}")),
        AnsiColor::Named(named) => named_slot(named).map(slot),
    }
}

/// The 16-slot index a named colour maps to, mirroring `named_to_ratatui`;
/// the terminal's own defaults (`Foreground`, `Background`, cursor colours)
/// have no slot and stay default.
fn named_slot(n: NamedColor) -> Option<u8> {
    use NamedColor::*;
    Some(match n {
        Foreground | Background | Cursor | DimForeground | BrightForeground => return None,
        Black | DimBlack => 0,
        Red | DimRed => 1,
        Green | DimGreen => 2,
        Yellow | DimYellow => 3,
        Blue | DimBlue => 4,
        Magenta | DimMagenta => 5,
        Cyan | DimCyan => 6,
        White | DimWhite => 7,
        BrightBlack => 8,
        BrightRed => 9,
        BrightGreen => 10,
        BrightYellow => 11,
        BrightBlue => 12,
        BrightMagenta => 13,
        BrightCyan => 14,
        BrightWhite => 15,
    })
}

/// Map an alacritty cell color to ratatui through the theme's 16-color ANSI
/// palette: Named colors and Indexed 0-15 resolve to the palette's RGB (so a
/// pane renders the same on every host terminal, the way VS Code owns its
/// terminal palette); true-color cells pass through; higher indexes keep the
/// standard 256-color cube the host renders.
fn ansi_to_ratatui(c: AnsiColor, palette: &[(u8, u8, u8); 16]) -> Option<Color> {
    match c {
        AnsiColor::Spec(rgb) => Some(Color::Rgb(rgb.r, rgb.g, rgb.b)),
        AnsiColor::Indexed(i) if i < 16 => Some(pal(palette, i as usize)),
        AnsiColor::Indexed(i) => Some(Color::Indexed(i)),
        AnsiColor::Named(named) => named_to_ratatui(named, palette),
    }
}

fn pal(palette: &[(u8, u8, u8); 16], i: usize) -> Color {
    let (r, g, b) = palette[i];
    Color::Rgb(r, g, b)
}

fn named_to_ratatui(n: NamedColor, palette: &[(u8, u8, u8); 16]) -> Option<Color> {
    use NamedColor::*;
    match n {
        Foreground | Background | Cursor | DimForeground => None,
        Black | DimBlack => Some(pal(palette, 0)),
        Red | DimRed => Some(pal(palette, 1)),
        Green | DimGreen => Some(pal(palette, 2)),
        Yellow | DimYellow => Some(pal(palette, 3)),
        Blue | DimBlue => Some(pal(palette, 4)),
        Magenta | DimMagenta => Some(pal(palette, 5)),
        Cyan | DimCyan => Some(pal(palette, 6)),
        White | DimWhite => Some(pal(palette, 7)),
        BrightBlack => Some(pal(palette, 8)),
        BrightRed => Some(pal(palette, 9)),
        BrightGreen => Some(pal(palette, 10)),
        BrightYellow => Some(pal(palette, 11)),
        BrightBlue => Some(pal(palette, 12)),
        BrightMagenta => Some(pal(palette, 13)),
        BrightCyan => Some(pal(palette, 14)),
        BrightWhite => Some(pal(palette, 15)),
        BrightForeground => None,
    }
}

impl Widget for &mut PtyTerminal {
    fn render(self, area: Rect, buf: &mut Buffer) {
        // A host-accent rule outranks the focus color: a production pane
        // must read as dangerous whether or not it holds focus.
        let block_style = if let Some((r, g, b)) = self.accent {
            Style::default().fg(Color::Rgb(r, g, b))
        } else if self.focused {
            Style::default().fg(self.theme.ui(Color::Rgb(0x4e, 0x9a, 0xff)))
        } else {
            Style::default().fg(Color::DarkGray)
        };
        // The panel group's tab strip already labels this region "TERMINAL", so
        // each pane stays titleless — a bare bordered box, matching VS Code's
        // unlabelled split terminal panes. The border alone frames the pane.
        //
        // The focused pane draws its box in heavy line-drawing glyphs
        // (┏━┓) against the unfocused pane's light ones (┌─┐), so which
        // pane has the keyboard reads at a glance and not only from the
        // border's colour (#470).
        //
        // Weight rather than a second ring: the issue asks for "twice as
        // thick", and a terminal cell is the smallest unit there is, so a
        // literally doubled border means a second box one cell inside the
        // first -- costing the shell a row and a column on every side of
        // every pane. Heavy glyphs give the emphasis for free, which is
        // what iTerm2 and WezTerm do for the same reason.
        //
        // Croft Loch draws no box: the frame is padding on the canvas and the
        // focused pane carries the brand rule along its top edge. A host
        // accent keeps a full box there too, because a production pane must
        // read as dangerous at a glance.
        let surfaces = self.theme.surfaces().is_some() && self.accent.is_none();
        let block = if surfaces {
            crate::widgets::surface::pane_block(self.theme.editor_bg())
        } else {
            Block::default()
                .borders(Borders::ALL)
                .border_type(if self.focused {
                    ratatui::widgets::BorderType::Thick
                } else {
                    ratatui::widgets::BorderType::Plain
                })
                .border_style(block_style)
        };
        let inner = block.inner(area);
        block.render(area, buf);
        // Black theme: replace the solid focus border with the orange→green
        // gradient (matching the welcome activity box).
        if self.focused && surfaces {
            crate::widgets::surface::paint_focus_rule(buf, area, self.theme);
        } else if self.focused && self.focus_gradient && self.accent.is_none() {
            crate::gradient::paint_gradient_box_heavy(buf, area);
        }
        self.last_area = area;
        self.last_inner = inner;
        // Re-anchor the selection / copy-cursor to the content they were
        // made on before painting, so the highlight scrolls WITH streaming
        // output instead of sitting at fixed screen rows while text slides
        // underneath (the Claude Code drag-select bug).
        self.rebase_selection();
        // (is_block, bounds): block selections rectangle-test each cell,
        // linear ones use the row-major span. A dormant alt-screen
        // selection paints nothing — its content is scrolled out of the
        // app's view and the frozen coordinates sit over unrelated text; a
        // partially covered one paints only its surviving rows.
        let dormant = self.alt_sel.as_ref().is_some_and(|a| a.dormant);
        let sel_clip = self.alt_sel.as_ref().and_then(|a| a.visible.clone());
        let sel_paint = self.selection.filter(|_| !dormant).map(|s| {
            if s.block {
                (true, s.block_bounds())
            } else {
                (false, s.normalised())
            }
        });

        let cols = inner.width;
        let rows = inner.height;
        self.resize(cols, rows);

        // Snapshot before taking the term lock: command_decorations locks
        // the term itself and FairMutex is not reentrant.
        let decorations = self.command_decorations();
        // Trigger set snapshot for the highlight pass (cheap Arc clone).
        let trigger_set = self.triggers.lock().unwrap().clone();

        let term = self.term.lock();
        // Annotation spans at their current grid lines, translated by the
        // scroll clock (same anchor as selections — history growth
        // saturates and froze these in long-lived panes). None while an
        // alt-screen app owns the viewport: the spans name primary-screen
        // rows, and painting them over vim/htop content is chart junk.
        let ann_spans: Vec<(i32, u16, u16)> = if term.mode().contains(TermMode::ALT_SCREEN) {
            Vec::new()
        } else {
            let ann_now = self.clock_now(&term);
            self.annotations
                .iter()
                .map(|a| (a.line_rec - (ann_now - a.clock_rec) as i32, a.start, a.len))
                .collect()
        };
        let display_offset = term.grid().display_offset();
        let cursor_visible = term.mode().contains(TermMode::SHOW_CURSOR) && self.focused;
        let alt_screen = term.mode().contains(TermMode::ALT_SCREEN);
        let cursor_point = term.grid().cursor.point;
        // The cursor is in absolute grid coords (Line is 0..rows in alt
        // screen, can wander into negative scrollback in normal screen).
        // Convert to viewport row by adding display_offset (>0 when the
        // user has scrolled up into history).
        let cursor_row_in_viewport = if alt_screen {
            cursor_point.line.0
        } else {
            cursor_point.line.0 + display_offset as i32
        };
        let cursor_col_in_viewport = cursor_point.column.0 as i32;

        // Quick-select hint drift: lines were captured at the set's clock
        // reading; re-base them to now so labels follow their matches
        // through streaming output (the annotation translation, one read
        // per frame).
        let hint_drift: i32 = self
            .hints
            .as_ref()
            .map_or(0, |(c0, _)| (self.clock_now(&term) - c0) as i32);

        // The active find match, re-based to the current clock the same way
        // (its stored line drifts by exactly the rows scrolled since it was
        // anchored, so the bright cell stays glued to its text).
        let active_match: Option<(i32, usize, usize)> = self
            .current_match
            .map(|(c0, l, c, n)| (l - (self.clock_now(&term) - c0) as i32, c, n));

        let reveal_redactions = self.reveal_redactions;
        let mut redacted_spans = 0usize;
        for y in 0..rows {
            // Find matches on this row once, then paint them per cell below.
            // Match positions are char indices in the spacer-skipped row text
            // (the same text the find bar searched); the colmap translates
            // them back to grid columns. 0 = no match, 1 = match, 2 = active.
            let row_line_idx = (y as i32) - (display_offset as i32);
            //
            // Matches are found on the logical line, as the find bar counts
            // them, and each paints the part that falls on this row: a match
            // the soft wrap cut in two lights up on both rows (#1275).
            let row_paint: Option<Vec<u8>> = self.search_needle.as_deref().map(|needle| {
                let (text, colmap) = row_text_and_cols(&term, row_line_idx);
                let (logical, offset, start) = logical_row_span(&term, row_line_idx);
                let row_len = text.chars().count();
                let mut paint = vec![0u8; cols as usize];
                for (mc, ml) in
                    crate::widgets::editor_find::line_matches(&logical, self.search_opts, needle)
                {
                    let (lo, hi) = (mc.max(offset), (mc + ml).min(offset + row_len));
                    if lo >= hi {
                        continue;
                    }
                    let active = active_match == Some((start, mc, ml));
                    for k in lo - offset..hi - offset {
                        if let Some(&col) = colmap.get(k) {
                            paint[col] = if active { 2 } else { 1 };
                        }
                    }
                }
                paint
            });
            // Quick-select hints on this row: 1 = match span, 2 = label cell
            // (the char to draw rides in the parallel vec). Char indices go
            // through the same colmap as the find highlight.
            let hint_paint: Option<(Vec<u8>, Vec<char>)> =
                self.hints.as_ref().and_then(|(_, hints)| {
                    let row_hints: Vec<&HintSpan> = hints
                        .iter()
                        .filter(|h| h.line - hint_drift == row_line_idx)
                        .collect();
                    if row_hints.is_empty() {
                        return None;
                    }
                    let (_text, colmap) = row_text_and_cols(&term, row_line_idx);
                    let mut span = vec![0u8; cols as usize];
                    let mut label = vec!['\0'; cols as usize];
                    for h in row_hints {
                        for k in h.start..h.start + h.len {
                            if let Some(&col) = colmap.get(k) {
                                span[col] = 1;
                            }
                        }
                        for (j, c) in h.label.chars().skip(h.typed).enumerate() {
                            if let Some(&col) = colmap.get(h.start + j) {
                                span[col] = 2;
                                label[col] = c;
                            }
                        }
                    }
                    Some((span, label))
                });
            // Trigger highlights on this row: per-cell fg/bg from the first
            // matching highlight trigger. Painted under the find highlight
            // and quick-select labels, which both win.
            let trig_paint: Option<TrigRowPaint> = trigger_set.has_highlights().then(|| {
                let (text, colmap) = row_text_and_cols(&term, row_line_idx);
                let mut paint: TrigRowPaint = vec![None; cols as usize];
                for s in crate::triggers::highlight_spans(&text, &trigger_set) {
                    let fg = s.fg.map(|(r, g, b)| Color::Rgb(r, g, b));
                    let bg = s.bg.map(|(r, g, b)| Color::Rgb(r, g, b));
                    for k in s.start..s.start + s.len {
                        if let Some(&col) = colmap.get(k) {
                            paint[col] = Some(TrigCell {
                                fg,
                                bg,
                                mask: false,
                            });
                        }
                    }
                }
                // Redaction (#360) is paint-only too: the grid keeps the
                // real text, the cell shows a mask glyph. Counted per span
                // for the status chip; nothing is masked while revealing.
                if !reveal_redactions {
                    // Over the logical line: a secret the soft wrap cut in
                    // two matches on neither row alone.
                    let (logical, offset) = logical_row_text(&term, row_line_idx);
                    let row_len = text.chars().count();
                    for s in crate::triggers::redact_spans(&logical, &trigger_set) {
                        let (lo, hi) =
                            (s.start.max(offset), (s.start + s.len).min(offset + row_len));
                        if lo >= hi {
                            continue;
                        }
                        // Counted on the row it starts on, once.
                        if s.start >= offset {
                            redacted_spans += 1;
                        }
                        for k in lo - offset..hi - offset {
                            if let Some(&col) = colmap.get(k) {
                                let cell = paint[col].get_or_insert(TrigCell {
                                    fg: None,
                                    bg: None,
                                    mask: false,
                                });
                                cell.mask = true;
                            }
                        }
                    }
                }
                paint
            });
            for x in 0..cols {
                let line_idx = (y as i32) - (display_offset as i32);
                let p = Point::new(Line(line_idx), Column(x as usize));
                let cell = &term.grid()[p];
                let mut display_char = cell_glyph(cell.c);
                let mut style = Style::default();
                if let Some(c) = ansi_to_ratatui(cell.fg, &self.palette) {
                    style = style.fg(c);
                }
                if let Some(c) = ansi_to_ratatui(cell.bg, &self.palette) {
                    style = style.bg(c);
                }
                let flags = cell.flags;
                if flags.contains(Flags::BOLD) {
                    style = style.add_modifier(Modifier::BOLD);
                }
                if flags.contains(Flags::ITALIC) {
                    style = style.add_modifier(Modifier::ITALIC);
                }
                // SGR 2 (faint): Claude Code's ghost suggestions and other
                // TUIs de-emphasise text with this; dropping it makes the
                // suggestion read as typed input.
                if flags.contains(Flags::DIM) {
                    style = style.add_modifier(Modifier::DIM);
                }
                if flags.intersects(Flags::ALL_UNDERLINES) {
                    style = style.add_modifier(Modifier::UNDERLINED);
                }
                if flags.contains(Flags::INVERSE) {
                    style = style.add_modifier(Modifier::REVERSED);
                }
                // SGR 9: coding agents strike through finished todo items.
                if flags.contains(Flags::STRIKEOUT) {
                    style = style.add_modifier(Modifier::CROSSED_OUT);
                }
                // SGR 8 (conceal) paints a blank, not just HIDDEN, so the
                // text stays hidden on a host terminal that ignores SGR 8.
                // The grid keeps the real text for copy, as in xterm.
                if flags.contains(Flags::HIDDEN) {
                    style = style.add_modifier(Modifier::HIDDEN);
                    display_char = ' ';
                }
                // Trigger highlight: the user's per-trigger colours over the
                // matched span. Cursor / selection / find / quick-select all
                // paint after this, so they stay visible on top.
                if let Some(paint) = trig_paint.as_ref()
                    && let Some(Some(cell)) = paint.get(x as usize)
                {
                    if let Some(c) = cell.fg {
                        style = style.fg(c);
                    }
                    if let Some(c) = cell.bg {
                        style = style.bg(c);
                    }
                    if cell.mask {
                        display_char = crate::triggers::MASK;
                    }
                }
                // Annotated spans: amber + underline, under the cursor /
                // selection / find layers so those still win.
                if ann_spans
                    .iter()
                    .any(|&(l, s0, ln)| l == line_idx && x >= s0 && x < s0 + ln)
                {
                    style = style
                        .fg(self.theme.ui(Color::Rgb(0xe5, 0xc0, 0x7b)))
                        .add_modifier(Modifier::UNDERLINED);
                }
                if cursor_visible
                    && (y as i32) == cursor_row_in_viewport
                    && (x as i32) == cursor_col_in_viewport
                {
                    style = style.add_modifier(Modifier::REVERSED);
                }
                if let Some((block, (sr, sc, er, ec))) = sel_paint
                    && sel_clip.as_ref().is_none_or(|clips| {
                        clips
                            .iter()
                            .any(|&(l, lo, hi)| l == line_idx && x >= lo && x <= hi)
                    })
                    && if block {
                        cell_in_block_selection(line_idx, x, sr, sc, er, ec)
                    } else {
                        cell_in_selection(line_idx, x, sr, sc, er, ec)
                    }
                {
                    style = style.bg(self.theme.ui(Color::Rgb(0x26, 0x4f, 0x78)));
                }
                // Find highlight: muted amber on every occurrence, bright
                // orange on the active match (VS Code's find colours).
                if let Some(paint) = row_paint.as_ref() {
                    match paint.get(x as usize) {
                        Some(1) => {
                            style = style
                                .fg(Color::Black)
                                .bg(self.theme.ui(Color::Rgb(0xff, 0xd7, 0x4a)))
                                .add_modifier(Modifier::BOLD);
                        }
                        Some(2) => {
                            style = style
                                .fg(Color::Black)
                                .bg(self.theme.ui(Color::Rgb(0xff, 0x8c, 0x2a)))
                                .add_modifier(Modifier::BOLD);
                        }
                        _ => {}
                    }
                }
                // Quick-select: matched spans turn green, label cells overlay
                // black-on-gold and replace the glyph underneath (WezTerm's
                // quick-select colours).
                if let Some((span, labels)) = hint_paint.as_ref() {
                    match span.get(x as usize) {
                        Some(1) => {
                            style = style
                                .fg(self.theme.ui(Color::Rgb(0x66, 0xcc, 0x66)))
                                .add_modifier(Modifier::BOLD);
                        }
                        Some(2) => {
                            if let Some(&lc) = labels.get(x as usize)
                                && lc != '\0'
                            {
                                display_char = lc;
                            }
                            style = Style::default()
                                .fg(Color::Black)
                                .bg(self.theme.ui(Color::Rgb(0xff, 0xd7, 0x4a)))
                                .add_modifier(Modifier::BOLD);
                        }
                        _ => {}
                    }
                }
                // Copy-mode cursor: a green modal block, painted last so the
                // caret stays visible over selection / find / trigger paint.
                if let Some((cl, cc)) = self.copy_cursor
                    && line_idx == cl
                    && x == cc
                {
                    style = Style::default()
                        .fg(Color::Black)
                        .bg(self.theme.ui(Color::Rgb(0x66, 0xcc, 0x66)))
                        .add_modifier(Modifier::BOLD);
                }
                let target_x = inner.x + x;
                let target_y = inner.y + y;
                let target = &mut buf[(target_x, target_y)];
                let mut tmp = [0u8; 4];
                target.set_symbol(display_char.encode_utf8(&mut tmp));
                target.set_style(style);
            }
        }
        self.redacted_on_screen = redacted_spans;
        // OSC 9;4 progress gauge along the bottom border (Ghostty/WezTerm
        // parity): a fill in the state's colour over the border glyphs —
        // blue normal, red error, yellow warning — and a sweeping segment
        // while indeterminate. Border cells are croft chrome, so no program
        // content is ever covered (same contract as the decoration dots).
        if let Some((state, pct)) = *self.progress.lock().unwrap()
            && area.height >= 2
            && inner.width > 0
        {
            let w = inner.width as u32;
            let (fill_from, fill_len) = if state == 3 {
                // Indeterminate: a ~fifth-width segment sweeping left to
                // right, phased off the wall clock so each frame advances.
                let seg = (w / 5).max(1);
                let span = (w - seg).max(1);
                let ms = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.as_millis() as u32)
                    .unwrap_or(0);
                ((ms / 80) % span, seg)
            } else {
                (0, w * u32::from(pct.min(100)) / 100)
            };
            let color = match state {
                2 => self.theme.ui(Color::Rgb(0xf1, 0x4c, 0x4c)),
                4 => self.theme.ui(Color::Rgb(0xe5, 0xc0, 0x7b)),
                _ => self.theme.ui(Color::Rgb(0x1b, 0x81, 0xa8)),
            };
            let by = area.y + area.height - 1;
            // The fill glyph has to be HEAVIER than the border it sits on,
            // or the gauge reads as full (#470): a focused pane's border is
            // already `━`, so painting `━` over it leaves only colour to
            // distinguish filled from unfilled -- and the focused pane is
            // the one most likely to be running the build being measured.
            // `═` against a heavy border is the same trick `━` plays
            // against a light one.
            // Croft Loch has no border to outweigh: a quarter block sits on
            // the frame row's floor, heavier than the hairline seam there.
            let fill_glyph = if surfaces {
                "\u{2582}"
            } else if self.focused {
                "═"
            } else {
                "━"
            };
            for i in 0..fill_len.min(w) {
                let x = inner.x + (fill_from + i) as u16;
                let cell = &mut buf[(x, by)];
                cell.set_symbol(fill_glyph);
                cell.set_style(Style::default().fg(color));
            }
        }
        // Timestamps gutter: the arrival clock of each stamped row hugs the
        // right edge (iTerm2's Show Timestamps), amber with a warning mark
        // when the row landed a long stall after its predecessor. Chrome
        // over content, painted only while the palette toggle is on.
        if self.show_timestamps && !alt_screen && inner.width > 14 {
            // Row ids are `clock + grid line` — content-stable through
            // scrollback saturation, matching the reader thread's stamps.
            // Clock before line_times: the shared lock order is
            // term → clock → line_times (see [`ScrollClock`]).
            let clock_now = self.clock_now(&term);
            let lt = self.line_times.lock().unwrap();
            for y in 0..rows {
                let abs = clock_now + (y as i32 - display_offset as i32) as i64;
                let Some(&ms) = lt.get(&abs) else { continue };
                let prev = lt.range(..abs).next_back().map(|(_, &v)| v);
                let stalled = prev.is_some_and(|p| ms.saturating_sub(p) >= STALL_GAP_MS);
                let mut text = hhmmss(ms);
                if stalled {
                    text = format!("\u{26a0} {text}");
                }
                let tw = text.chars().count() as u16;
                if tw >= inner.width {
                    continue;
                }
                let x0 = inner.x + inner.width - tw;
                let fg = if stalled {
                    self.theme.ui(Color::Rgb(0xe5, 0xc0, 0x7b))
                } else {
                    self.theme.ui(Color::Rgb(0x5b, 0x64, 0x72))
                };
                for (j, c) in text.chars().enumerate() {
                    let cell = &mut buf[(x0 + j as u16, inner.y + y)];
                    let mut tmpc = [0u8; 4];
                    cell.set_symbol(c.encode_utf8(&mut tmpc));
                    cell.set_style(Style::default().fg(fg));
                }
            }
        }
        // Host-accent badge watermark: the rule's badge text, dim in the
        // accent color, parked at the pane's top-right (under the sticky
        // header, over content — it is a warning, that is the point).
        if let (Some((r, g, b)), Some(badge)) = (self.accent, self.accent_badge.as_deref())
            && !badge.is_empty()
        {
            let bw = badge.chars().count() as u16;
            if bw + 2 < inner.width {
                let x0 = inner.x + inner.width - bw - 1;
                for (j, c) in badge.chars().enumerate() {
                    let cell = &mut buf[(x0 + j as u16, inner.y)];
                    let mut tmpc = [0u8; 4];
                    cell.set_symbol(c.encode_utf8(&mut tmpc));
                    cell.set_style(
                        Style::default()
                            .fg(Color::Rgb(r, g, b))
                            .add_modifier(Modifier::DIM | Modifier::BOLD),
                    );
                }
            }
        }
        // Sticky command header (Warp): when the viewport is scrolled so its
        // top row falls inside one command's output while that command's
        // prompt sits above the view, the typed command pins to the pane's
        // top row with the scroll depth. Finished commands resolve through
        // the decoration spans; the still-running one through the newest
        // CommandStart mark. Unpins the instant the top row leaves the span.
        if display_offset > 0 && !alt_screen && rows > 0 && inner.width > 4 {
            let top_row = -(display_offset as i32);
            let cols_last = term.columns().saturating_sub(1);
            let header = decorations
                .iter()
                .find(|d| d.line < top_row && d.output_start <= top_row && top_row < d.output_end)
                .and_then(|d| {
                    let (l, c) = d.input?;
                    (d.output_start > l)
                        .then(|| extract_selection_text(&term, l, c, d.output_start - 1, cols_last))
                })
                .or_else(|| {
                    let ms = self.marks.lock().unwrap();
                    let running = ms.last().is_some_and(|m| {
                        matches!(m.kind, crate::shell_integration::OscEvent::CommandStart)
                    });
                    if !running {
                        return None;
                    }
                    let now = self.clock_now(&term);
                    let last = ms.last().unwrap();
                    let c_line = last.line_rec - (now - last.clock_rec) as i32;
                    (c_line < top_row).then(|| last_command_input_text(&term, &ms, now))
                })
                .filter(|t| !t.trim().is_empty());
            if let Some(text) = header {
                let bg = self.theme.ui(Color::Rgb(0x25, 0x2b, 0x36));
                for x in 0..inner.width {
                    let cell = &mut buf[(inner.x + x, inner.y)];
                    cell.set_symbol(" ");
                    cell.set_style(Style::default().bg(bg));
                }
                // A multi-row command (soft-wrapped or a quoted/heredoc
                // newline) arrives with its rows joined by '\n'; a cell must
                // never hold ANY control char, so the whole class maps to
                // spaces, not just the row join.
                let label: String = format!("\u{25b6} {}", text.trim())
                    .chars()
                    .map(|c| if c.is_control() { ' ' } else { c })
                    .collect();
                let mut xw = inner.x + 1;
                for ch in label.chars() {
                    if xw + 1 >= inner.x + inner.width {
                        break;
                    }
                    let cell = &mut buf[(xw, inner.y)];
                    let mut tmpc = [0u8; 4];
                    cell.set_symbol(ch.encode_utf8(&mut tmpc));
                    cell.set_style(
                        Style::default()
                            .fg(self.theme.ui(Color::Rgb(0xec, 0xf0, 0xf4)))
                            .bg(bg)
                            .add_modifier(Modifier::BOLD),
                    );
                    xw += 1;
                }
                let right = format!(" \u{2191} {display_offset} ");
                let rw = right.chars().count() as u16;
                if xw + rw < inner.x + inner.width {
                    let x0 = inner.x + inner.width - rw;
                    for (j, ch) in right.chars().enumerate() {
                        let cell = &mut buf[(x0 + j as u16, inner.y)];
                        let mut tmpc = [0u8; 4];
                        cell.set_symbol(ch.encode_utf8(&mut tmpc));
                        cell.set_style(
                            Style::default()
                                .fg(self.theme.ui(Color::Rgb(0x8b, 0x93, 0xa1)))
                                .bg(bg),
                        );
                    }
                }
            }
        }
        // Command decorations: a VS Code-style dot on the left border at
        // each finished command's prompt row — blue for success, red for a
        // non-zero exit. Normal screen only; an alt-screen app owns the
        // viewport and has no prompts.
        if !alt_screen {
            for d in &decorations {
                let vp = d.line + display_offset as i32;
                if (0..rows as i32).contains(&vp) {
                    let ok = d.exit.unwrap_or(0) == 0;
                    let cell = &mut buf[(area.x, inner.y + vp as u16)];
                    cell.set_symbol("●");
                    cell.set_style(Style::default().fg(if ok {
                        self.theme.ui(Color::Rgb(0x1b, 0x81, 0xa8))
                    } else {
                        self.theme.ui(Color::Rgb(0xf1, 0x4c, 0x4c))
                    }));
                }
            }
        }
    }
}

/// Per-cell trigger paint for one row: `None` = cell untouched, `Some` =
/// the matching trigger's colours (either side optional, leaving that half
/// of the cell style alone) and whether a redact rule masks the glyph.
#[derive(Clone, Copy, Debug, Default)]
struct TrigCell {
    fg: Option<Color>,
    bg: Option<Color>,
    mask: bool,
}
type TrigRowPaint = Vec<Option<TrigCell>>;

/// The display offset that brings absolute grid line `abs_line` to the
/// vertical middle of a `rows`-tall viewport, clamped to `[0, max_off]` (0 =
/// live bottom, `max_off` = oldest scrollback). The render loop shows the
/// grid line `y - display_offset` at viewport row `y`, so centering the
/// target means `display_offset = rows/2 - abs_line`. Pure for testing.
pub fn scroll_offset_for_line(rows: i32, max_off: i32, abs_line: i32) -> i32 {
    (rows / 2 - abs_line).clamp(0, max_off.max(0))
}

/// The text a rectangular selection covers: the same inclusive column
/// slice `[cl..=ch]` from every row `[rl..=rh]`, one line per row (what
/// vim's Ctrl+V yank produces). Rows are clamped to the readable grid the
/// same way `extract_selection_text` clamps.
pub fn block_selection_text(
    term: &Term<VoidListener>,
    rl: i32,
    cl: usize,
    rh: i32,
    ch: usize,
) -> String {
    let max_line = term.screen_lines() as i32 - 1;
    let min_line = term.grid().topmost_line().0;
    let rl = rl.max(min_line);
    let rh = rh.min(max_line);
    let mut rows = Vec::new();
    for line in rl..=rh {
        rows.push(extract_selection_text(term, line, cl, line, ch));
    }
    rows.join("\n")
}

/// True iff (row, col) is inside the inclusive rectangle whose corners are
/// (rl, cl) and (rh, ch) — [`Selection::block_bounds`] output. Public for
/// unit testing.
pub fn cell_in_block_selection(row: i32, col: u16, rl: i32, cl: u16, rh: i32, ch: u16) -> bool {
    row >= rl && row <= rh && col >= cl && col <= ch
}

/// True iff (row, col) is inside the inclusive row-major range
/// [(sr,sc)..=(er,ec)]. Public for unit testing.
pub fn cell_in_selection(row: i32, col: u16, sr: i32, sc: u16, er: i32, ec: u16) -> bool {
    if row < sr || row > er {
        return false;
    }
    if row == sr && col < sc {
        return false;
    }
    if row == er && col > ec {
        return false;
    }
    true
}

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

    #[test]
    fn a_replaced_binary_still_names_a_runnable_path() {
        let dir = tempfile::tempdir().unwrap();
        let bin = dir.path().join("croft");
        std::fs::write(&bin, b"").unwrap();
        let deleted = std::path::PathBuf::from(format!("{} (deleted)", bin.display()));
        assert_eq!(live_exe(deleted), Some(bin.clone()));
        assert_eq!(live_exe(bin.clone()), Some(bin));
        assert_eq!(live_exe(dir.path().join("gone (deleted)")), None);
    }

    /// The zsh the shim tests drive, or an ANNOUNCED skip on a machine
    /// without one (#52). CI provisions zsh, so the gate holds where it
    /// matters; on a zsh-less dev box these tests must skip with a reason
    /// — a hard spawn failure (or a silent `return`) makes "suite green"
    /// ambiguous. Same convention as the cross-compile and PDF gates.
    fn zsh_or_skip() -> Option<&'static str> {
        let zsh = "/bin/zsh";
        if std::path::Path::new(zsh).exists() {
            Some(zsh)
        } else {
            eprintln!("SKIPPED: {zsh} not installed on this machine");
            None
        }
    }

    fn fresh_term(cols: usize, rows: usize) -> Term<VoidListener> {
        let cfg = Config {
            scrolling_history: 1000,
            ..Config::default()
        };
        let size = TermSize::new(cols, rows);
        Term::new(cfg, &size, VoidListener::default())
    }

    fn feed(term: &mut Term<VoidListener>, bytes: &[u8]) {
        let mut p = Processor::<StdSyncHandler>::new();
        p.advance(term, bytes);
    }

    #[test]
    fn block_selection_highlights_and_extracts_a_rectangle() {
        let mut term = fresh_term(20, 5);
        feed(&mut term, b"alpha1\r\nbravo2\r\ncharlie3\r\n");
        // A rectangle over rows 0..=2, cols 1..=3, anchored bottom-right so
        // the bounds must come from independent min/max, not the row-major
        // normalisation linear selections use.
        let sel = Selection {
            anchor: (2, 3),
            head: (0, 1),
            block: true,
        };
        let (rl, cl, rh, ch) = sel.block_bounds();
        assert_eq!((rl, cl, rh, ch), (0, 1, 2, 3));
        assert!(cell_in_block_selection(1, 2, rl, cl, rh, ch));
        assert!(!cell_in_block_selection(1, 0, rl, cl, rh, ch));
        assert!(!cell_in_block_selection(1, 4, rl, cl, rh, ch));
        assert!(!cell_in_block_selection(3, 2, rl, cl, rh, ch));
        assert_eq!(
            block_selection_text(&term, rl, cl as usize, rh, ch as usize),
            "lph\nrav\nhar",
            "a block selection copies the same column slice from every row"
        );
    }

    #[test]
    fn annotations_anchor_to_content_and_ride_the_scrollback() {
        let tmp = tempfile::tempdir().unwrap();
        let script = "n=note; echo ${n}-worthy-line; read x; i=0; while [ $i -lt 30 ]; do echo fill-$i; i=$((i+1)); done; sleep 30";
        let mut term =
            PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
                .unwrap();
        term.last_inner = Rect {
            x: 0,
            y: 0,
            width: 80,
            height: 24,
        };
        let mut waited = 0u32;
        while !term
            .grid_lines()
            .0
            .iter()
            .any(|l| l.starts_with("note-worthy-line"))
        {
            assert!(waited < 8000, "line never arrived");
            std::thread::sleep(std::time::Duration::from_millis(20));
            waited += 20;
        }
        let (lines, top) = term.grid_lines();
        let line = top
            + lines
                .iter()
                .position(|l| l.starts_with("note-worthy-line"))
                .unwrap() as i32;
        let clock = term.scroll_clock();
        term.add_annotation(line, clock, 0, 16, String::from("this is where it broke"));
        // The screen cell over the span resolves to the note.
        let (idx, text) = term
            .annotation_at(3, line as u16)
            .expect("the annotated cell must resolve");
        assert_eq!(idx, 0);
        assert_eq!(text, "this is where it broke");
        assert!(
            term.annotation_at(30, line as u16).is_none(),
            "cells past the span carry no note"
        );

        // 30 more lines push the annotated row toward (or into) history;
        // the anchor drifts with the content.
        term.write_input(b"\n");
        let mut waited = 0u32;
        while !term.grid_lines().0.iter().any(|l| l.starts_with("fill-29")) {
            assert!(waited < 8000, "filler never arrived");
            std::thread::sleep(std::time::Duration::from_millis(20));
            waited += 20;
        }
        // The reader thread can still be scrolling (the newline after
        // `fill-29`) between reading the grid and reading the anchors, so
        // compare the two only once they come from the same screen.
        let mut waited = 0u32;
        let (expect_line, cur) = loop {
            let (lines, top) = term.grid_lines();
            let expect_line = top
                + lines
                    .iter()
                    .position(|l| l.starts_with("note-worthy-line"))
                    .unwrap() as i32;
            let cur = term.annotations_current();
            if (cur.len() == 1 && cur[0].0 == expect_line) || waited >= 2000 {
                break (expect_line, cur);
            }
            std::thread::sleep(std::time::Duration::from_millis(20));
            waited += 20;
        };
        assert_eq!(cur.len(), 1);
        assert_eq!(
            cur[0].0, expect_line,
            "the annotation must still sit on its content line"
        );
        assert_eq!(cur[0].3, "this is where it broke");
    }

    #[test]
    fn prompt_click_arrows_map_a_click_to_cursor_motion() {
        let tmp = tempfile::tempdir().unwrap();
        // A prompt with 133;A/B marks and typed text, cursor parked after
        // the text (no newline). `read` keeps the shell at the prompt.
        let script = "h=hello; printf '\\033]133;A\\007$ \\033]133;B\\007'; printf \"${h}-world\"; read x; sleep 30";
        let mut term =
            PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
                .unwrap();
        term.last_inner = Rect {
            x: 1,
            y: 1,
            width: 80,
            height: 24,
        };
        let mut waited = 0u32;
        while !term
            .grid_lines()
            .0
            .iter()
            .any(|l| l.contains("hello-world"))
        {
            assert!(waited < 8000, "prompt text never arrived");
            std::thread::sleep(std::time::Duration::from_millis(20));
            waited += 20;
        }
        let (lines, top) = term.grid_lines();
        let vrow = (lines
            .iter()
            .position(|l| l.contains("hello-world"))
            .unwrap() as i32
            + top) as u16; // display_offset 0: grid line == viewport row
        // Click on the 'h' (grid col 2): the cursor sits after 'd' (col 13),
        // so 11 left-arrows bring it there.
        let bytes = term
            .prompt_click_arrows(1 + 2, 1 + vrow)
            .expect("a prompt-row click must produce motion");
        assert_eq!(bytes, b"\x1b[D".repeat(11));
        // Clamped left of the input start: col 0 is the "$ " prompt glyphs.
        let bytes = term.prompt_click_arrows(1, 1 + vrow).unwrap();
        assert_eq!(bytes, b"\x1b[D".repeat(11), "clamps to the 133;B column");
        // A click on the cursor cell itself is a no-op.
        assert!(term.prompt_click_arrows(1 + 13, 1 + vrow).is_none());
        // A click on another row does nothing.
        assert!(term.prompt_click_arrows(1 + 2, 1 + vrow + 1).is_none());
    }

    #[test]
    fn row_times_record_when_each_line_arrived() {
        // Deterministic (#170): a loaded scheduler can hold the reader
        // past the writer's sleep, coalescing both echoes into ONE read
        // that stamp_chunk marks with a single now_ms — so no real-PTY
        // timing assertion can pin per-chunk stamps. Drive the stamping
        // path directly instead, one chunk per arrival.
        let (_tmp, t) = quiet_pty();
        let mut prev = 0i64;
        feed_pty(&t, b"first-marker\r\n");
        t.stamp_chunk_for_test(&mut prev, 1000);
        feed_pty(&t, b"second-marker\r\n");
        t.stamp_chunk_for_test(&mut prev, 1400);
        let (lines, top) = t.grid_lines();
        let a = lines
            .iter()
            .position(|l| l.starts_with("first-marker"))
            .expect("first line on the grid");
        let b = lines
            .iter()
            .position(|l| l.starts_with("second-marker"))
            .expect("second line on the grid");
        let ta = t
            .row_time(top + a as i32)
            .expect("the first line must be stamped");
        let tb = t
            .row_time(top + b as i32)
            .expect("the second line must be stamped");
        assert_eq!(ta, 1000, "first row keeps its own chunk's arrival time");
        assert_eq!(tb, 1400, "second row gets the later chunk's arrival time");
    }

    #[test]
    fn reader_thread_stamps_arriving_rows() {
        // End-to-end: the real reader loop must feed stamp_chunk. Only
        // presence and ordering are asserted — any gap assertion races
        // the scheduler (#170).
        let tmp = tempfile::tempdir().unwrap();
        let script = "a=first; echo ${a}-marker; sleep 30";
        let term =
            PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
                .unwrap();
        let mut waited = 0u32;
        loop {
            let (lines, top) = term.grid_lines();
            if let Some(a) = lines.iter().position(|l| l.starts_with("first-marker")) {
                assert!(
                    term.row_time(top + a as i32).is_some(),
                    "the reader thread must stamp rows it delivers"
                );
                break;
            }
            assert!(waited < 8000, "marker never arrived");
            std::thread::sleep(std::time::Duration::from_millis(20));
            waited += 20;
        }
    }

    #[test]
    fn resize_reflows_long_lines_instead_of_truncating() {
        // Scrollback soft-reflow is an engine property (alacritty_terminal's
        // Term::resize reflows the normal screen); this pins it so a future
        // engine upgrade can't silently lose it.
        let mut term = fresh_term(30, 5);
        feed(&mut term, b"abcdefghijklmnopqrstuvwxyz1234\r\n");
        term.resize(TermSize::new(10, 5));
        let top = term.grid().topmost_line().0;
        let bottom = term.screen_lines() as i32 - 1;
        let mut all = String::new();
        for l in top..=bottom {
            let (s, _) = row_text_and_cols(&term, l);
            all.push_str(s.trim_end());
        }
        assert!(
            all.contains("abcdefghijklmnopqrstuvwxyz1234"),
            "text must survive a narrowing resize by reflowing: {all:?}"
        );
        // Widening back re-joins the soft-wrapped rows onto one line.
        term.resize(TermSize::new(40, 5));
        let joined: Vec<String> = (term.grid().topmost_line().0..term.screen_lines() as i32)
            .map(|l| row_text_and_cols(&term, l).0.trim_end().to_string())
            .collect();
        assert!(
            joined
                .iter()
                .any(|r| r.contains("abcdefghijklmnopqrstuvwxyz1234")),
            "widening must re-join the reflowed rows: {joined:?}"
        );
    }

    #[test]
    fn scroll_offset_centers_a_scrollback_match_and_clamps_to_the_range() {
        // 24-row pane, 100 lines of scrollback (max_off 100). A match on an
        // old line (-80) centers it: 12 - (-80) = 92, within [0, 100].
        assert_eq!(scroll_offset_for_line(24, 100, -80), 92);
        // A match on the live screen (line 20) wants a negative offset but is
        // clamped to 0 — you cannot scroll below the live bottom.
        assert_eq!(scroll_offset_for_line(24, 100, 20), 0);
        // A match older than the deepest scrollback is clamped to max_off.
        assert_eq!(scroll_offset_for_line(24, 100, -200), 100);
        // No scrollback (alt screen / fresh grid): always pinned to bottom.
        assert_eq!(scroll_offset_for_line(24, 0, -5), 0);
    }

    #[test]
    fn mouse_report_encoding_matches_the_xterm_wire_format() {
        let none = MouseMods::default();
        let shift = MouseMods {
            shift: true,
            ..MouseMods::default()
        };
        // SGR: 1-based coords, 'M' press / 'm' release, wheel = 64/65.
        assert_eq!(
            encode_mouse_report(true, MouseButtonKind::Left, MouseAction::Press, 0, 0, none),
            b"\x1b[<0;1;1M"
        );
        assert_eq!(
            encode_mouse_report(
                true,
                MouseButtonKind::Left,
                MouseAction::Release,
                4,
                2,
                none
            ),
            b"\x1b[<0;5;3m"
        );
        assert_eq!(
            encode_mouse_report(
                true,
                MouseButtonKind::WheelDown,
                MouseAction::Press,
                9,
                9,
                none
            ),
            b"\x1b[<65;10;10M"
        );
        // Motion adds 32; Shift adds 4.
        assert_eq!(
            encode_mouse_report(
                true,
                MouseButtonKind::Left,
                MouseAction::Motion,
                0,
                0,
                shift
            ),
            b"\x1b[<36;1;1M"
        );
        // Legacy X10: 0x20-based bytes, release collapses the button to code 3.
        assert_eq!(
            encode_mouse_report(false, MouseButtonKind::Left, MouseAction::Press, 0, 0, none),
            &[0x1b, b'[', b'M', 32, 33, 33]
        );
        assert_eq!(
            encode_mouse_report(
                false,
                MouseButtonKind::Left,
                MouseAction::Release,
                0,
                0,
                none
            ),
            &[0x1b, b'[', b'M', 35, 33, 33]
        );
    }

    #[test]
    fn dsr_cursor_position_query_round_trips_into_the_pty_response_channel() {
        // Regression for atuin reverse-search (Ctrl+R) panicking with
        // "Error: The cursor position could not be read within a normal
        // duration": atuin sends DSR (`ESC[6n`) and waits for the
        // terminal to write back `ESC[<row>;<col>R` on stdin. Before
        // this fix, croft's `VoidListener` discarded every event
        // alacritty emitted, so the reply never reached the shell and
        // atuin timed out. With the responder wiring in place, the
        // listener must publish the reply on the channel that the
        // background thread forwards to the PTY master.
        let (tx, rx) = std::sync::mpsc::channel::<String>();
        let listener = VoidListener {
            pty_response_tx: Some(tx),
            size: Some(Arc::new(std::sync::Mutex::new((80, 24)))),
            bell: None,
            clipboard: None,
        };
        let cfg = Config::default();
        let size = TermSize::new(80, 24);
        let mut term = Term::new(cfg, &size, listener);
        let mut processor = Processor::<StdSyncHandler>::new();
        processor.advance(&mut term, b"\x1b[6n");
        let response = rx
            .recv_timeout(std::time::Duration::from_millis(500))
            .expect("DSR cursor-position query must produce a PtyWrite event");
        assert_eq!(
            response, "\x1b[1;1R",
            "a fresh terminal's cursor is at row 1, column 1 (1-based), so the reply must be ESC[1;1R"
        );
    }

    #[test]
    fn text_area_size_request_replies_with_the_current_grid_geometry() {
        // CSI 18 t ("report text area size in characters") is what
        // helix, neovim, and other modern TUIs use to learn the
        // viewport size beyond what TIOCGWINSZ surfaces. The reply
        // must echo the live cols/rows held in `size_shared` so a
        // resize inside croft propagates to the embedded program
        // without a fresh listener instance.
        let (tx, rx) = std::sync::mpsc::channel::<String>();
        let size = Arc::new(std::sync::Mutex::new((120u16, 40u16)));
        let listener = VoidListener {
            pty_response_tx: Some(tx),
            size: Some(size),
            bell: None,
            clipboard: None,
        };
        let cfg = Config::default();
        let term_size = TermSize::new(120, 40);
        let mut term = Term::new(cfg, &term_size, listener);
        let mut processor = Processor::<StdSyncHandler>::new();
        processor.advance(&mut term, b"\x1b[18t");
        let response = rx
            .recv_timeout(std::time::Duration::from_millis(500))
            .expect("CSI 18 t must produce a TextAreaSizeRequest reply on the channel");
        assert_eq!(
            response, "\x1b[8;40;120t",
            "CSI 18 t reply format is ESC[8;<rows>;<cols>t per xterm convention"
        );
    }

    #[test]
    fn interactive_shell_invocation_passes_login_flag_for_zsh() {
        let (program, args) = interactive_shell_invocation("/bin/zsh");
        assert_eq!(program, "/bin/zsh");
        assert_eq!(
            args,
            vec!["-l".to_string()],
            "zsh must be spawned as a login shell so ~/.zprofile is sourced and the embedded terminal inherits the same env / keybindings as the user's native iTerm2 shell"
        );
    }

    #[test]
    fn interactive_shell_invocation_passes_login_flag_for_bash_fish_ksh() {
        for path in [
            "/bin/bash",
            "/usr/local/bin/fish",
            "/bin/ksh",
            "/usr/bin/tcsh",
        ] {
            let (_, args) = interactive_shell_invocation(path);
            assert_eq!(
                args,
                vec!["-l".to_string()],
                "{} must be spawned with -l so its login-shell rc files are sourced",
                path
            );
        }
    }

    #[test]
    fn interactive_shell_invocation_skips_login_flag_for_unknown_shells() {
        let (_, args) = interactive_shell_invocation("/opt/exotic/myshell");
        assert!(
            args.is_empty(),
            "an unknown shell must be spawned without -l in case the flag means something else there"
        );
    }

    #[test]
    fn a_large_write_to_a_child_not_reading_never_blocks_the_caller() {
        let tmp = tempfile::tempdir().unwrap();
        let mut term = PtyTerminal::new_running(
            "/bin/sh",
            &[String::from("-c"), String::from("stty raw -echo; sleep 3")],
            tmp.path(),
        )
        .unwrap();
        let big = vec![b'x'; 1 << 20];
        let started = std::time::Instant::now();
        term.write_input(&big);
        assert!(
            started.elapsed() < std::time::Duration::from_secs(1),
            "the write went to the pane's writer thread, not the caller"
        );
    }

    #[test]
    fn a_space_at_the_wrap_still_separates_words_for_redaction() {
        let tmp = tempfile::tempdir().unwrap();
        let mut term = PtyTerminal::new(tmp.path()).unwrap();
        term.resize(22, 10);
        // `Authorization: Bearer` is 21 chars: the space lands in column 22,
        // the last, and the token starts the next row.
        let token = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.c2lnbmF0dXJl";
        term.feed_bytes_for_test(
            format!("\x1b[2J\x1b[HAuthorization: Bearer {token}\r\n").as_bytes(),
        );
        let (lines, wraps, _) = term.grid_lines_wrapped();
        assert!(
            lines.concat().contains(&format!("Bearer {token}")),
            "{lines:?}"
        );
        let set = crate::triggers::TriggerSet::default().with_builtin_redactions();
        let masked = crate::triggers::mask_rows(&lines, &wraps, &set).concat();
        assert!(!masked.contains("c2lnbmF0dXJl"), "{masked}");
    }

    /// Find's logical lines join only rows that soft-wrap, and a position
    /// maps back to the row that shows it, which is where the jump scrolls
    /// (#1275).
    #[test]
    fn find_lines_join_wrapped_rows_and_map_a_position_to_its_row() {
        let rows = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
        let lines = join_wrapped_rows(
            rows(&["abc", "def", "gh", "solo", "x"]),
            &[true, true, false, false, false],
            -3,
        );
        assert_eq!(
            lines
                .iter()
                .map(|l| (l.text.as_str(), l.start))
                .collect::<Vec<_>>(),
            vec![("abcdefgh", -3), ("solo", 0), ("x", 1)]
        );
        assert_eq!(lines[0].row_lens, vec![3, 3, 2]);
        assert_eq!(lines[0].line_of(0), -3);
        assert_eq!(lines[0].line_of(3), -2);
        assert_eq!(lines[0].line_of(7), -1);
        assert_eq!(
            lines[0].line_of(99),
            -1,
            "past the end stays on the last row"
        );
        assert_eq!(lines[1].line_of(2), 0);
    }

    #[test]
    fn a_secret_cut_by_a_soft_wrap_is_masked_on_both_rows() {
        let tmp = tempfile::tempdir().unwrap();
        let mut term = PtyTerminal::new(tmp.path()).unwrap();
        term.resize(30, 10);
        let token = "ghp_abcdefghijklmnopqrstuvwxyz0123456789";
        term.feed_bytes_for_test(format!("\x1b[2J\x1b[Hexport GH={token}\r\n").as_bytes());
        let set = crate::triggers::TriggerSet::default().with_builtin_redactions();
        let (lines, wraps, _) = term.grid_lines_wrapped();
        let masked = crate::triggers::mask_rows(&lines, &wraps, &set);
        let all: String = masked.concat();
        assert!(
            !all.contains("ghp_") && !all.contains("0123456789"),
            "{masked:?}"
        );
        let t = term.term.lock();
        let first = (0..t.screen_lines() as i32)
            .find(|&l| row_text_and_cols(&t, l).0.contains("export"))
            .unwrap();
        let (logical, offset) = logical_row_text(&t, first + 1);
        assert!(logical.contains(token), "{logical}");
        assert_eq!(offset, 30);
    }

    #[test]
    fn a_pane_gets_a_utf8_ctype_when_the_inherited_one_is_not() {
        let s = |v: &str| Some(v.to_string());
        // What macOS forwards over ssh, and no locale at all.
        assert_eq!(
            utf8_ctype_fix(None, s("UTF-8"), None),
            Some(("LC_CTYPE", "C.UTF-8"))
        );
        assert_eq!(
            utf8_ctype_fix(None, None, None),
            Some(("LC_CTYPE", "C.UTF-8"))
        );
        assert_eq!(
            utf8_ctype_fix(None, None, s("C")),
            Some(("LC_CTYPE", "C.UTF-8"))
        );
        assert_eq!(
            utf8_ctype_fix(s("UTF-8"), None, None),
            Some(("LC_ALL", "C.UTF-8"))
        );
        // Already UTF-8, or pinned by the user: untouched.
        assert_eq!(utf8_ctype_fix(None, None, s("en_US.UTF-8")), None);
        assert_eq!(utf8_ctype_fix(None, s("de_DE.utf8@euro"), None), None);
        assert_eq!(utf8_ctype_fix(s("POSIX"), None, None), None);
    }

    #[test]
    fn a_paste_cannot_close_its_own_brackets() {
        let tmp = tempfile::tempdir().unwrap();
        let mut term = PtyTerminal::new(tmp.path()).unwrap();
        // The mode as the parser tracks it (the reader keeps one parser, so
        // a sequence split across reads lands too).
        term.feed_bytes_for_test(b"prompt \x1b[?1049;2004h");
        term.paste_input(b"ls\x1b[201~rm -rf ~\r");
        let written = term.written_bytes_for_test();
        let tail = &written[written.len() - b"\x1b[200~ls[201~rm -rf ~\r\x1b[201~".len()..];
        assert_eq!(tail, b"\x1b[200~ls[201~rm -rf ~\r\x1b[201~");
        // And no brackets once the program turns the mode off.
        term.feed_bytes_for_test(b"\x1b[?2004l");
        term.paste_input(b"x");
        assert!(term.written_bytes_for_test().ends_with(b"\x1b[201~x"));
    }

    #[test]
    fn pty_starts_dirty_so_first_frame_renders() {
        let tmp = tempfile::tempdir().unwrap();
        let term = PtyTerminal::new(tmp.path()).unwrap();
        assert!(
            term.take_dirty(),
            "first take_dirty must be true so we draw the initial state"
        );
    }

    #[test]
    fn take_dirty_clears_the_flag() {
        let tmp = tempfile::tempdir().unwrap();
        let term = PtyTerminal::new(tmp.path()).unwrap();
        let _ = term.take_dirty();
        assert!(
            !term.take_dirty(),
            "second take_dirty without new bytes must be false"
        );
    }

    #[test]
    fn write_input_marks_dirty() {
        let tmp = tempfile::tempdir().unwrap();
        let mut term = PtyTerminal::new(tmp.path()).unwrap();
        let _ = term.take_dirty();
        term.write_input(b"echo hi\r");
        assert!(
            term.take_dirty(),
            "write_input must mark the terminal dirty"
        );
    }

    /// #357: the REAL reader thread records output into the rewind buffer.
    ///
    /// The app-level test drives `feed_bytes_for_test`, a `#[cfg(test)]`
    /// sibling hand-edited to mirror the reader. That proves the buffer works
    /// but not that the production path uses it — deleting the reader's
    /// `rb.push` leaves it green, which was measured, not assumed. This
    /// spawns a real shell and reads what the reader thread actually stored.
    #[test]
    fn the_reader_thread_records_shell_output_for_rewind() {
        let tmp = tempfile::tempdir().unwrap();
        let mut term = PtyTerminal::new(tmp.path()).unwrap();
        // The needle only ever appears as command OUTPUT, so matching it in
        // the buffer proves the recorded bytes came through the pty rather
        // than from the echoed input line.
        term.write_input(b"echo REWIND_$(echo recorded)\n");
        crate::test_budget::await_spawned(
            std::time::Duration::from_millis(2000),
            "the shell to print the needle",
            || term.visible_text().contains("REWIND_recorded"),
        );

        let rb = term.rewind().lock().unwrap();
        let (_, frames) = rb.replay_from(u64::MAX);
        let seen: Vec<u8> = frames.iter().flat_map(|f| f.data.clone()).collect();
        assert!(
            String::from_utf8_lossy(&seen).contains("REWIND_recorded"),
            "the reader thread parsed output without recording it: {} bytes held",
            rb.bytes()
        );
    }

    /// #694: closing a pane frees its rewind buffer at once and leaves the
    /// shared budget, rather than waiting on the last handle to drop.
    ///
    /// Asserted on a clone of the handle, standing in for the reader thread's
    /// copy: that clone is exactly what kept a closed pane's buffer alive.
    #[test]
    fn closing_a_pane_frees_its_rewind_buffer() {
        let tmp = tempfile::tempdir().unwrap();
        let mut term = PtyTerminal::new(tmp.path()).unwrap();
        term.write_input(b"echo FREED_$(echo soon)\n");
        crate::test_budget::await_spawned(
            std::time::Duration::from_millis(2000),
            "the shell to print the needle",
            || term.visible_text().contains("FREED_soon"),
        );
        let handle = term.rewind().clone();
        assert!(
            !handle.lock().unwrap().is_empty(),
            "precondition: the pane recorded output"
        );
        assert!(handle.lock().unwrap().capacity() > 0);

        drop(term);
        let rb = handle.lock().unwrap();
        assert!(rb.is_empty(), "a closed pane kept {} bytes", rb.bytes());
        assert_eq!(rb.capacity(), 0, "a closed pane kept its share");
    }

    /// Output arriving BEFORE an OSC 133 mark must be recorded too.
    ///
    /// The reader splits each read at OSC events and advances the parser per
    /// segment, leaving `done` at the LAST mark in the chunk. Recording
    /// `buf[done..n]` therefore keeps only the tail, and with shell
    /// integration on — marks arriving around every prompt and command — that
    /// silently discards most of the session, which is the one thing this
    /// buffer exists to keep.
    ///
    /// `the_reader_thread_records_shell_output_for_rewind` cannot see this:
    /// its script emits no marks, so `done` stays 0 and the tail happens to
    /// BE the whole chunk. The fixture agrees with the implementation. This
    /// test puts a mark between two needles so the two differ.
    #[test]
    fn output_before_an_osc_mark_is_recorded_not_just_the_tail() {
        let tmp = tempfile::tempdir().unwrap();
        let mut term = PtyTerminal::new(tmp.path()).unwrap();
        // Both needles must be command OUTPUT ONLY. The shell ECHOES the
        // input line before running it, and that echo arrives in one chunk
        // with no mark before it — so a needle written literally in the
        // command reaches the buffer via the echo whether or not the
        // recording under test works, and the test passes vacuously. `$(..)`
        // is unexpanded in the echo, so these two strings exist only in the
        // command's output. (The sibling test above documents this; I used it
        // as a template and dropped the property it exists to explain.)
        term.write_input(
            b"printf \"BEFORE_$(echo MARK)\\n\\033]133;C\\007AFTER_$(echo MARK)\\n\"\n",
        );
        crate::test_budget::await_spawned(
            std::time::Duration::from_millis(2000),
            "the shell to print both needles",
            || {
                let v = term.visible_text();
                v.contains("BEFORE_MARK") && v.contains("AFTER_MARK")
            },
        );

        let rb = term.rewind().lock().unwrap();
        let (_, frames) = rb.replay_from(u64::MAX);
        let seen: Vec<u8> = frames.iter().flat_map(|f| f.data.clone()).collect();
        let text = String::from_utf8_lossy(&seen);
        // The tail alone is the bug: AFTER_MARK present, BEFORE_MARK dropped.
        // Asserting BOTH is what distinguishes the fix from the defect — the
        // AFTER_MARK half is the paired presence assertion that keeps the
        // BEFORE_MARK claim from passing over an empty buffer.
        assert!(
            text.contains("AFTER_MARK"),
            "nothing was recorded at all: {} bytes held",
            rb.bytes()
        );
        assert!(
            text.contains("BEFORE_MARK"),
            "output before the OSC mark was parsed but not recorded -- only \
             the tail after the last mark survived: {:?}",
            text
        );
    }

    /// Drop must REAP the shell on every path. portable-pty's `kill()` reaps
    /// only when the shell dies inside its SIGHUP grace loop; a shell that
    /// ignores HUP gets the SIGKILL escalation, which never waits — so every
    /// such closed pane left a zombie for the life of the process.
    #[test]
    fn dropping_a_terminal_reaps_a_hup_ignoring_shell() {
        let tmp = tempfile::tempdir().unwrap();
        let mut term = PtyTerminal::new(tmp.path()).unwrap();
        let pid = term.pid().expect("spawned shell has a pid") as i32;
        // The needle only ever appears as command OUTPUT ($(..) is unexpanded
        // in the input echo), so matching it proves the trap line executed.
        term.write_input(b"trap '' HUP; echo TRAP_$(echo armed)\n");
        crate::test_budget::await_spawned(
            std::time::Duration::from_millis(1200),
            "the shell to confirm the HUP trap",
            || term.visible_text().contains("TRAP_armed"),
        );
        drop(term);
        let mut status = 0i32;
        let r = unsafe { libc::waitpid(pid, &mut status, libc::WNOHANG) };
        assert!(
            r < 0,
            "the shell was left as an unreaped zombie (waitpid still found it: r={r})"
        );
    }

    /// #912: a hosted shell that exits while croft attaches can have its
    /// exit arrive in the same read as the greeting. Its code is kept, and
    /// the output before it still reaches the pane.
    #[test]
    fn an_exit_in_the_pane_hosts_greeting_keeps_its_code() {
        use crate::session_host::{Control, encode_bytes_frame, encode_control_frame};
        use std::io::{Read, Write};
        let tmp = tempfile::tempdir().unwrap();
        let socket = tmp.path().join("pane.sock");
        let listener = std::os::unix::net::UnixListener::bind(&socket).unwrap();
        let host = std::thread::spawn(move || {
            let (mut conn, _) = listener.accept().unwrap();
            let mut hello = [0u8; 512];
            let _ = conn.read(&mut hello);
            let mut greeting = encode_control_frame(&Control::PaneInfo { pid: 4242 });
            greeting.extend(encode_bytes_frame(b"bye\r\n"));
            greeting.extend(encode_control_frame(&Control::Exit { code: 7 }));
            conn.write_all(&greeting).unwrap();
        });
        let mut link = PaneLink::attach(&socket, 80, 24).unwrap();
        host.join().unwrap();
        let mut out = Vec::new();
        link.reader.read_to_end(&mut out).unwrap();
        assert_eq!(out, b"bye\r\n");
        assert_eq!(link.backend.try_exit(true), Some(Some(7)));
    }

    /// #912: a shell that exits while its pane lives is reaped then, not
    /// left a zombie until the pane is dropped, and its exit code goes
    /// under its output.
    #[test]
    fn a_shell_that_exits_is_reaped_and_its_exit_code_shown() {
        let tmp = tempfile::tempdir().unwrap();
        let mut term = PtyTerminal::new(tmp.path()).unwrap();
        let pid = term.pid().expect("spawned shell has a pid") as i32;
        term.write_input(b"exit 3\n");
        let mut code = None;
        crate::test_budget::await_spawned(
            std::time::Duration::from_millis(1500),
            "the pane to notice its shell exited",
            || {
                code = term.poll_exit();
                code.is_some()
            },
        );
        assert_eq!(code, Some(Some(3)));
        assert!(term.has_exited());
        assert_eq!(term.poll_exit(), None, "the exit is reported once");
        let mut status = 0i32;
        let r = unsafe { libc::waitpid(pid, &mut status, libc::WNOHANG) };
        assert!(r < 0, "the exited shell is still a zombie (r={r})");
        assert_eq!(term.pid(), None, "a reaped pid may name another process");
        let text = term.visible_text();
        assert!(
            text.contains("[Process exited with code 3]"),
            "no exit footer:\n{text}"
        );
    }

    /// Drop must return promptly even when a background job keeps the pty
    /// slave open: on Linux the reader's blocked `read` never returns then
    /// (no tty revoke like macOS), so joining it would freeze the UI until
    /// the job exits. The shutdown pipe is what wakes the reader.
    #[test]
    fn a_background_job_cannot_stall_a_dropped_pane() {
        let tmp = tempfile::tempdir().unwrap();
        let mut term = PtyTerminal::new(tmp.path()).unwrap();
        term.write_input(b"sleep 30 &\n");
        std::thread::sleep(std::time::Duration::from_millis(1500));
        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            drop(term);
            let _ = tx.send(());
        });
        assert!(
            rx.recv_timeout(std::time::Duration::from_secs(10)).is_ok(),
            "drop hung: the reader never woke while a background job held the pty slave"
        );
    }

    #[test]
    fn format_cd_command_single_quotes_plain_path() {
        let bytes = format_cd_command(std::path::Path::new("/tmp/foo"));
        assert_eq!(
            bytes,
            b"\x05\x15cd '/tmp/foo'\n".to_vec(),
            "Ctrl-E + Ctrl-U must precede the cd so a half-typed prompt line is cleared first, then the path is single-quoted and newline-terminated to fire immediately"
        );
    }

    #[test]
    fn format_cd_command_escapes_embedded_apostrophe() {
        let bytes = format_cd_command(std::path::Path::new("/tmp/it's a dir"));
        assert_eq!(
            bytes,
            b"\x05\x15cd '/tmp/it'\\''s a dir'\n".to_vec(),
            "embedded ' must be escaped as '\\'' so the cd does not break out of single quotes when the path contains an apostrophe (POSIX-standard quoting)"
        );
    }

    #[test]
    fn format_cd_command_quotes_paths_with_spaces() {
        let bytes = format_cd_command(std::path::Path::new("/tmp/a b/c d"));
        assert_eq!(
            bytes,
            b"\x05\x15cd '/tmp/a b/c d'\n".to_vec(),
            "single-quoting must preserve spaces verbatim so cd lands at the right directory"
        );
    }

    #[test]
    fn foreground_is_shell_flips_false_while_a_foreground_command_runs() {
        let tmp = tempfile::tempdir().unwrap();
        let mut term = PtyTerminal::new(tmp.path()).unwrap();

        let mut waited = 0u32;
        while waited < 4000 && !term.foreground_is_shell() {
            std::thread::sleep(std::time::Duration::from_millis(20));
            waited += 20;
        }
        assert!(
            term.foreground_is_shell(),
            "a shell at its prompt is the tty's foreground process group, so a cd is safe to inject"
        );

        term.write_input(b"sleep 10\n");
        let mut waited = 0u32;
        while waited < 4000 && term.foreground_is_shell() {
            std::thread::sleep(std::time::Duration::from_millis(20));
            waited += 20;
        }
        assert!(
            !term.foreground_is_shell(),
            "while a foreground command owns the tty, the foreground group is the command not the shell, so a cd must not be injected"
        );
    }

    /// Spawn a pane whose "shell" is a script holding the tty foreground
    /// group with a job-control child — the rc-startup state the #94 flake
    /// caught `change_workspace_root` in. Returns the pane after the child
    /// has taken the foreground (bounded wait, asserted).
    fn startup_owned_pane(tmp: &tempfile::TempDir) -> PtyTerminal {
        let script = tmp.path().join("slow-startup.sh");
        std::fs::write(&script, "#!/bin/bash\nset -m\nsleep 30\n").unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
        }
        let term = PtyTerminal::new_running(script.to_str().unwrap(), &[], tmp.path()).unwrap();
        let mut waited = 0u32;
        while waited < 4000 && term.foreground_is_shell() {
            std::thread::sleep(std::time::Duration::from_millis(20));
            waited += 20;
        }
        assert!(
            !term.foreground_is_shell(),
            "precondition: the startup child must own the foreground group"
        );
        term
    }

    #[test]
    fn cwd_seed_stays_safe_through_startup_until_a_prompt_mark_arrives() {
        let tmp = tempfile::tempdir().unwrap();
        let term = startup_owned_pane(&tmp);
        assert!(
            term.cwd_seed_is_safe(),
            "an untouched pane whose foreground group is shell startup must stay seedable: the seed queues as type-ahead for the first prompt"
        );
        // Once shell integration reports a prompt, startup is over — a
        // non-shell foreground group is a real app from here on.
        term.push_mark_for_test(crate::shell_integration::OscEvent::PromptStart, 0);
        assert!(
            !term.cwd_seed_is_safe(),
            "after the first prompt mark, a non-shell foreground group must suppress the seed"
        );
    }

    #[test]
    fn cwd_seed_turns_unsafe_once_the_pane_has_received_input() {
        let tmp = tempfile::tempdir().unwrap();
        let mut term = startup_owned_pane(&tmp);
        // Any input could have launched the app that owns the tty, so the
        // startup carve-out must die with the first written byte.
        term.write_input(b"q");
        assert!(
            !term.cwd_seed_is_safe(),
            "after input has been written, a non-shell foreground group must suppress the seed"
        );
    }

    /// A foreground process that owns the tty (an ssh client, exactly)
    /// controls everything the pane prints — including an OSC 7 report
    /// impersonating this machine's own hostname. The self-reported host
    /// is no proof of locality then: `local_shell_cwd` must refuse while
    /// the shell is not the foreground group, whatever the claim says.
    #[test]
    fn a_foreground_process_cannot_impersonate_a_local_cwd_report() {
        let out = std::process::Command::new("hostname").output().unwrap();
        let local = String::from_utf8_lossy(&out.stdout).trim().to_string();
        if local.is_empty() {
            return;
        }
        let tmp = tempfile::tempdir().unwrap();
        let mut term = PtyTerminal::new(tmp.path()).unwrap();
        let mut waited = 0u32;
        while waited < 4000 && !term.foreground_is_shell() {
            std::thread::sleep(std::time::Duration::from_millis(20));
            waited += 20;
        }
        // Stage the decoy: the shim's own prompt-time OSC 7 reports the
        // shell's real cwd (the tempdir), so `shell_cwd()` is `Some` long
        // before the forged claim exists — an `is_some()` stage exits on
        // this report and reads the wrong value (#69).
        let mut waited = 0u32;
        while waited < 4000 && term.shell_cwd().is_none() {
            std::thread::sleep(std::time::Duration::from_millis(20));
            waited += 20;
        }
        // A foreground job (the ssh stand-in) prints an OSC 7 claiming
        // this machine's own hostname. It sleeps BEFORE printing, so the
        // tty is lost to the job well before the claim can be parsed —
        // deterministically the ordering that flaked under suite load.
        term.write_input(
            format!("sleep 0.5; printf '\\033]7;file://{local}/tmp\\007'; sleep 10\n").as_bytes(),
        );
        let mut waited = 0u32;
        while waited < 4000 && term.foreground_is_shell() {
            std::thread::sleep(std::time::Duration::from_millis(20));
            waited += 20;
        }
        assert!(!term.foreground_is_shell(), "staging: a job owns the tty");
        // Wait for the claim ITSELF: any earlier `Some` is the decoy.
        let claim = std::path::PathBuf::from("/tmp");
        let mut waited = 0u32;
        while waited < 6000 && term.shell_cwd().as_deref() != Some(claim.as_path()) {
            std::thread::sleep(std::time::Duration::from_millis(20));
            waited += 20;
        }
        assert_eq!(
            term.shell_cwd(),
            Some(claim),
            "staging: the claim was captured"
        );
        assert_eq!(
            term.local_shell_cwd(),
            None,
            "a tty-owning foreground process must not place local splits by claim"
        );
    }

    /// The buffered claim outliving its forger: a foreground job prints a
    /// local-looking OSC 7 and dies, but the reader thread only PARSES
    /// those bytes later (here: the render side held the term lock, the
    /// production delay). Any tty-ownership sample taken at parse time
    /// sees the shell back at its prompt — PTY bytes carry no author, so
    /// timing can never establish provenance. The claim must be rejected
    /// on content: it names a directory the shell is not actually in.
    #[test]
    fn a_claim_parsed_only_after_its_job_died_is_still_untrusted() {
        let Some(zsh) = zsh_or_skip() else { return };
        let tmp = tempfile::tempdir().unwrap();
        // zsh -f: job control (the job gets its own pgroup) but no
        // integration, so nothing overwrites the forged claim.
        let mut term =
            PtyTerminal::new_running(zsh, &[String::from("-f"), String::from("-i")], tmp.path())
                .unwrap();
        let mut waited = 0u32;
        while waited < 4000 && !term.foreground_is_shell() {
            std::thread::sleep(std::time::Duration::from_millis(20));
            waited += 20;
        }
        // The job sleeps before printing, leaving time to stall the
        // reader below; then it prints the claim and lingers briefly so
        // the bytes enter the kernel buffer while it owns the tty.
        let term_arc = term.term.clone();
        term.write_input(
            b"/bin/sh -c 'sleep 1; printf \"\\033]7;file://localhost/tmp\\007\"; sleep 1'\n",
        );
        // Wait for the job to take the tty and the reader to drain the
        // command echo, THEN stall parsing by taking the term lock. The
        // lock cannot be held from the start: with the reader parked,
        // zsh's startup burst fills the kernel pty queue and blocks the
        // shell before it ever runs the line. The claim plus one prompt
        // redraw are small enough that nothing blocks during the stall.
        let mut waited = 0u32;
        while waited < 4000 && term.foreground_is_shell() {
            std::thread::sleep(std::time::Duration::from_millis(20));
            waited += 20;
        }
        assert!(!term.foreground_is_shell(), "staging: the job took the tty");
        std::thread::sleep(std::time::Duration::from_millis(150));
        let guard = term_arc.lock();
        // With parsing stalled, wait out the job's remaining life: claim
        // printed, job dead, shell back at its prompt. tcgetpgrp is
        // kernel state, untouched by our lock.
        let mut waited = 0u32;
        while waited < 8000 && !term.foreground_is_shell() {
            std::thread::sleep(std::time::Duration::from_millis(20));
            waited += 20;
        }
        assert!(
            term.foreground_is_shell(),
            "staging: the job is gone and the shell owns the tty again"
        );
        std::thread::sleep(std::time::Duration::from_millis(300));
        drop(guard);
        let mut waited = 0u32;
        while waited < 4000 && term.shell_cwd() != Some(std::path::PathBuf::from("/tmp")) {
            std::thread::sleep(std::time::Duration::from_millis(20));
            waited += 20;
        }
        assert_eq!(
            term.shell_cwd(),
            Some(std::path::PathBuf::from("/tmp")),
            "staging: the claim was captured after the job died"
        );
        assert_eq!(
            term.local_shell_cwd(),
            None,
            "a claim whose bytes were parsed after its job died must not be trusted"
        );
    }

    /// The forged claim outliving its forger: a foreground job prints an
    /// OSC 7 with a local-looking host and EXITS; the shell retakes the
    /// tty without re-reporting (no integration), so a foreground check at
    /// consultation time passes on the stale cache. A report that arrived
    /// from a job never becomes trusted, however long ago the job died.
    #[test]
    fn a_stale_claim_from_a_dead_foreground_job_stays_untrusted() {
        let Some(zsh) = zsh_or_skip() else { return };
        let tmp = tempfile::tempdir().unwrap();
        // zsh -f: job control (the claim's job gets its own pgroup, like a
        // real ssh client) but NO integration — the shell never overwrites
        // the stale claim with a fresh trusted report of its own.
        let mut term =
            PtyTerminal::new_running(zsh, &[String::from("-f"), String::from("-i")], tmp.path())
                .unwrap();
        let mut waited = 0u32;
        while waited < 4000 && !term.foreground_is_shell() {
            std::thread::sleep(std::time::Duration::from_millis(20));
            waited += 20;
        }
        // An EXTERNAL job (its own pgroup, like an ssh client — a bare
        // printf would be a zsh builtin printing from the shell's own
        // pgroup) settles as the tty owner, prints the local-looking
        // claim, lingers so the capture happens while it owns the tty,
        // and dies.
        term.write_input(
            b"/bin/sh -c 'sleep 1; printf \"\\033]7;file://localhost/tmp\\007\"; sleep 1'\n",
        );
        let mut waited = 0u32;
        while waited < 8000
            && !(term.foreground_is_shell()
                && term.shell_cwd() == Some(std::path::PathBuf::from("/tmp")))
        {
            std::thread::sleep(std::time::Duration::from_millis(20));
            waited += 20;
        }
        assert_eq!(
            term.shell_cwd(),
            Some(std::path::PathBuf::from("/tmp")),
            "staging: the claim was captured"
        );
        assert!(
            term.foreground_is_shell(),
            "staging: the job is gone and the shell owns the tty again"
        );
        assert_eq!(
            term.local_shell_cwd(),
            None,
            "a claim captured while a job owned the tty must never become trusted"
        );
    }

    #[test]
    fn clear_screen_and_scrollback_wipes_the_grid() {
        fn dump(term: &PtyTerminal) -> String {
            let t = term.term.lock();
            let rows = t.screen_lines();
            let cols = t.columns();
            let off = t.grid().display_offset() as i32;
            extract_selection_text(&t, -off, 0, rows as i32 - 1 - off, cols.saturating_sub(1))
        }
        let tmp = tempfile::tempdir().unwrap();
        // The spawn banner prints the command's argv, so the probe must never
        // appear verbatim in argv: under load the banner lands before the
        // child's output, the wait below matches the BANNER, and the clear
        // fires before the probe exists - which the assert then finds alive.
        // The shell concatenation keeps argv and output distinct.
        let mut term = PtyTerminal::new_running(
            "/bin/sh",
            &[String::from("-c"), String::from("echo CLEAR-PROBE-\"\"XYZ")],
            tmp.path(),
        )
        .unwrap();
        let mut waited = 0u32;
        while waited < 4000 && !dump(&term).contains("CLEAR-PROBE-XYZ") {
            std::thread::sleep(std::time::Duration::from_millis(20));
            waited += 20;
        }
        assert!(
            dump(&term).contains("CLEAR-PROBE-XYZ"),
            "probe present before clear"
        );
        term.clear_screen_and_scrollback();
        assert!(
            !dump(&term).contains("CLEAR-PROBE-XYZ"),
            "clear wipes the screen and scrollback"
        );
    }

    #[test]
    fn change_cwd_writes_cd_command_to_pty() {
        let tmp = tempfile::tempdir().unwrap();
        let mut term = PtyTerminal::new(tmp.path()).unwrap();
        let _ = term.take_dirty();
        let target = tempfile::tempdir().unwrap();
        term.change_cwd(target.path());
        assert!(
            term.take_dirty(),
            "change_cwd must mark the terminal dirty so the next frame paints the new prompt"
        );
    }

    #[test]
    fn new_running_spawns_program_directly_and_produces_output() {
        let tmp = tempfile::tempdir().unwrap();
        let term = PtyTerminal::new_running(
            "/bin/echo",
            &[String::from("croft-direct-spawn")],
            tmp.path(),
        )
        .unwrap();
        // Wait on the BYTE COUNTER, not the dirty flag: `pty_dirty` is
        // constructed `true`, so peeking it succeeds before /bin/echo has
        // written anything and this test would pass just as happily if direct
        // spawns stopped reaching the reader thread entirely. `pending_bytes`
        // only moves when the reader actually advanced output.
        crate::test_budget::await_spawned(
            std::time::Duration::from_millis(500),
            "the directly spawned /bin/echo to deliver bytes through the PTY",
            || term.peek_pending_bytes() > 0,
        );
        assert!(
            term.peek_pending_bytes() > 0,
            "direct-spawned /bin/echo must produce output without any write_input"
        );
    }

    /// #473: the grid must take the new size BEFORE the child hears about it.
    ///
    /// `resize` used to send the pty ioctl (which delivers SIGWINCH) first
    /// and resize alacritty's grid second. A program that repaints on
    /// WINCH - Claude Code does, with a full frame laid out for the new
    /// size - can have that frame parsed into the OLD grid whenever the
    /// render thread loses the CPU between the two steps. A frame laid out
    /// for one size and parsed into another leaves rows of stale text the
    /// program believes it erased: its renderer diffs against its own model
    /// and never repaints what it thinks is already blank. Replaying a
    /// recorded Claude Code session with the two steps swapped reproduces
    /// the residue; the correct order replays clean.
    ///
    /// The order is observed, not timed: the child records its size the
    /// moment WINCH arrives, and the test holds the grid lock across the
    /// whole `resize`. If the ioctl goes out before the grid is resized,
    /// the child reports the new size WHILE the lock is held, which the
    /// correct order makes impossible however long the wait.
    #[test]
    fn the_grid_takes_the_new_size_before_the_child_hears_the_winch() {
        let tmp = tempfile::tempdir().unwrap();
        let out = tmp.path().join("winch-size");
        // The path travels as `$1` rather than being spliced into the
        // script: a temp dir with a space, a `;` or a quote in it would break
        // an interpolated redirection, while "$1" is expanded by the shell
        // itself when WINCH fires.
        let script =
            "trap 'stty size > \"$1\"' WINCH; echo trap-armed; while :; do sleep 0.05; done";
        let mut pane = PtyTerminal::new_running(
            "/bin/sh",
            &[
                String::from("-c"),
                String::from(script),
                String::from("sh"),
                out.display().to_string(),
            ],
            tmp.path(),
        )
        .unwrap();
        crate::test_budget::await_spawned(
            std::time::Duration::from_millis(500),
            "the child shell to arm its WINCH trap",
            || pane.visible_text().contains("trap-armed"),
        );
        let grid = pane.grid_lock_for_test();
        let held = grid.lock();
        // A budget, not a race: the wrong order sends the ioctl before it
        // ever asks for the lock, so the child's report lands within
        // milliseconds; the right order cannot produce one while the lock
        // is held, so waiting longer only makes a true failure slower.
        let window = crate::test_budget::spawn_budget(std::time::Duration::from_millis(150));
        std::thread::scope(|s| {
            s.spawn(|| pane.resize(30, 10));
            std::thread::sleep(window);
            let reported = std::fs::read_to_string(&out).ok();
            // Released BEFORE asserting, or a failure deadlocks the scope
            // on a resize that is still waiting for the grid.
            drop(held);
            assert!(
                reported.is_none(),
                "the child saw the new size ({:?}) while the grid lock was still held: \
                 the pty was resized before the grid",
                reported.map(|s| s.trim().to_string())
            );
        });
        // Positive control: the trap works and the resize went through.
        crate::test_budget::await_spawned(
            std::time::Duration::from_millis(500),
            "the child to report the new size once the grid lock was released",
            || std::fs::read_to_string(&out).is_ok_and(|s| s.trim() == "10 30"),
        );
        // The parser grid itself, not the cached `cols` field: `resize`
        // writes that field before it touches the grid, so it reads 30 even
        // when the grid was never resized.
        assert_eq!(
            grid.lock().columns(),
            30,
            "the grid took the new column count"
        );
    }

    #[test]
    fn pristine_covers_only_an_untouched_interactive_shell() {
        let tmp = tempfile::tempdir().unwrap();
        let mut shell = PtyTerminal::new(tmp.path()).unwrap();
        assert!(
            shell.is_pristine(),
            "a freshly spawned shell with no input and no name is pristine"
        );
        shell.write_input(b"echo touched\n");
        assert!(
            !shell.is_pristine(),
            "any input byte permanently clears pristineness"
        );

        let mut named = PtyTerminal::new(tmp.path()).unwrap();
        named.set_manual_name(Some(String::from("srv")));
        assert!(
            !named.is_pristine(),
            "a manual name is user state; the pane must not be replaceable"
        );
        named.set_manual_name(None);
        assert!(
            !named.is_pristine(),
            "a rename latches: clearing the name back must not make the pane replaceable"
        );

        let run = PtyTerminal::new_running(
            "/bin/sh",
            &[String::from("-c"), String::from("sleep 1")],
            tmp.path(),
        )
        .unwrap();
        assert!(
            !run.is_pristine(),
            "a launched-program pane is doing user work despite having seen no input"
        );
    }

    #[test]
    fn tpgid_is_read_past_a_command_name_with_spaces_and_parens() {
        let stat = "4242 (my (odd) sh) S 1 4242 4242 34816 5151 4194560 0 0";
        assert_eq!(parse_tpgid(stat), Some(5151));
        assert_eq!(
            parse_tpgid("1 (init) S 0 1 1 0 -1 4194560"),
            None,
            "no terminal"
        );
        assert_eq!(parse_tpgid("garbage"), None);
    }

    /// A pane host for `argv` on a socket in `dir`, served on a thread.
    #[cfg(target_os = "linux")]
    fn serve_pane(
        dir: &std::path::Path,
        argv: &[&str],
    ) -> (std::path::PathBuf, std::thread::JoinHandle<Result<i32>>) {
        let spec = crate::pane_host::PaneSpec {
            socket: dir.join("pane.sock"),
            cwd: Some(dir.to_path_buf()),
            env: vec![(String::from("TERM"), String::from("xterm-256color"))],
            cols: 80,
            rows: 24,
            argv: argv.iter().map(|a| a.to_string()).collect(),
        };
        let socket = spec.socket.clone();
        let host = std::thread::spawn(move || crate::pane_host::serve(&spec));
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
        while !crate::session::is_alive(&socket) {
            assert!(
                std::time::Instant::now() < deadline,
                "the host never listened"
            );
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        (socket, host)
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn a_hosted_pane_outlives_a_croft_that_never_closed_it() {
        let tmp = tempfile::tempdir().unwrap();
        let (socket, host) = serve_pane(tmp.path(), &["sh"]);
        let mut pane = PtyTerminal::attach_hosted(&socket).unwrap();
        assert_eq!(pane.host_socket(), Some(socket.as_path()));
        let pid = pane.pid().expect("the host names its shell");
        assert_eq!(pane.shell_pid(), Some(pid as i32));
        pane.write_input(b"echo first-$((40+2))\r");
        wait_for_grid(&pane, |l| l.iter().any(|l| l.contains("first-42")));
        // The shell owns its terminal at the prompt, read without a master.
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(4);
        while pane.foreground_pid() != Some(pid as i32) {
            assert!(
                std::time::Instant::now() < deadline,
                "{:?}",
                pane.foreground_pid()
            );
            std::thread::sleep(std::time::Duration::from_millis(20));
        }

        // croft dies without dropping its panes (the OOM killer): the pane
        // is never closed, so its shell must keep running.
        std::mem::forget(pane);
        let mut again = PtyTerminal::attach_hosted(&socket).unwrap();
        assert_eq!(again.pid(), Some(pid), "the same shell");
        wait_for_grid(&again, |l| l.iter().any(|l| l.contains("first-42")));
        again.resize(100, 30);
        again.write_input(b"stty size\r");
        wait_for_grid(&again, |l| l.iter().any(|l| l.trim() == "30 100"));

        // Closing the pane ends the shell and its host.
        drop(again);
        host.join().unwrap().unwrap();
        assert!(!socket.exists());
    }

    /// Poll `grid_lines` until a predicate matches or 4s elapse.
    fn wait_for_grid<F: Fn(&[String]) -> bool>(term: &PtyTerminal, pred: F) -> Vec<String> {
        let mut waited_ms = 0u32;
        loop {
            let (lines, _top) = term.grid_lines();
            if pred(&lines) {
                return lines;
            }
            assert!(
                waited_ms < 4000,
                "expected output never reached the grid; grid was: {lines:?}"
            );
            std::thread::sleep(std::time::Duration::from_millis(20));
            waited_ms += 20;
        }
    }

    #[test]
    fn ansi_named_colors_render_through_the_theme_palette() {
        // SGR 31 red must come out as the theme palette's red (VS Code's
        // #cd3131 by default), not the host terminal's Color::Red — croft
        // owns its terminal palette the way VS Code does. A palette swap
        // repaints with the new colors.
        let tmp = tempfile::tempdir().unwrap();
        // The sentinel is assembled at runtime (`${s}RED`) so the pane's
        // `▶ …` run-label header — which contains the raw command text —
        // can never match the scan below.
        let mut term = PtyTerminal::new_running(
            "/bin/sh",
            &[
                String::from("-c"),
                String::from("s=QQ; printf \"\\033[31m${s}RED\\033[0m\\n\"; sleep 30"),
            ],
            tmp.path(),
        )
        .unwrap();
        wait_for_grid(&term, |ls| ls.iter().any(|l| l.contains("QQRED")));
        let area = Rect::new(0, 0, 60, 10);
        let find_q_fg = |term: &mut PtyTerminal| -> Option<Color> {
            let mut buf = Buffer::empty(area);
            Widget::render(term, area, &mut buf);
            for y in 0..area.height {
                for x in 1..area.width - 2 {
                    if buf[(x, y)].symbol() == "Q"
                        && buf[(x + 1, y)].symbol() == "Q"
                        && buf[(x + 2, y)].symbol() == "R"
                    {
                        return Some(buf[(x, y)].fg);
                    }
                }
            }
            None
        };
        assert_eq!(
            find_q_fg(&mut term),
            Some(Color::Rgb(0xcd, 0x31, 0x31)),
            "SGR red must map through the default palette"
        );
        let mut palette = crate::theme::VSCODE_ANSI;
        palette[1] = (0x12, 0x34, 0x56);
        term.set_palette(palette);
        assert_eq!(
            find_q_fg(&mut term),
            Some(Color::Rgb(0x12, 0x34, 0x56)),
            "a palette swap must repaint SGR red with the new color"
        );
    }

    /// #360: a redact-trigger match paints as a run of mask glyphs of the
    /// same width while the grid keeps the real text, so a click on the
    /// mask can still recover it; the count feeds the status chip; a
    /// reveal window paints the text as typed.
    #[test]
    fn redacted_spans_paint_as_masks_and_the_real_text_stays_recoverable() {
        let tmp = tempfile::tempdir().unwrap();
        let mut term = PtyTerminal::new_running(
            "/bin/sh",
            &[
                String::from("-c"),
                String::from(
                    "printf 'key AKIAIOSFODNN7EXAMPLE end\\ntail AKIAIOSFODNN7EXAMPLE\\n'; sleep 30",
                ),
            ],
            tmp.path(),
        )
        .unwrap();
        // The pane's spawn banner echoes the command line, key included, so
        // wait for the OUTPUT line, which starts at column 0.
        wait_for_grid(&term, |ls| ls.iter().any(|l| l.starts_with("tail AKIA")));
        term.set_triggers(std::sync::Arc::new(
            crate::triggers::TriggerSet::default().with_builtin_redactions(),
        ));
        let area = Rect::new(0, 0, 60, 10);
        term.last_inner = Rect::new(1, 1, 58, 8);
        let mut buf = Buffer::empty(area);
        Widget::render(&mut term, area, &mut buf);
        let row_text = |buf: &Buffer, y: u16| -> String {
            (0..area.width)
                .map(|x| buf[(x, y)].symbol().to_string())
                .collect()
        };
        let rows: Vec<String> = (0..area.height).map(|y| row_text(&buf, y)).collect();
        let (y, line) = rows
            .iter()
            .enumerate()
            .map(|(y, l)| (y as u16, l.clone()))
            .find(|(_, l)| l.starts_with("\u{2502}key "))
            .unwrap_or_else(|| {
                panic!(
                    "the key line rendered: {rows:#?} grid={:?} label={:?}",
                    term.grid_lines().0,
                    term.label()
                )
            });
        assert!(
            line.contains(&"\u{2022}".repeat(20)) && !line.contains("AKIA"),
            "the key paints as twenty masks: {line:?}"
        );
        assert!(
            line.contains(" end"),
            "text around the key is untouched: {line:?}"
        );
        assert!(
            term.redacted_on_screen >= 1,
            "the status chip counts at least the output line's span"
        );

        // The grid still holds the real text: a click on the mask finds it.
        // A column, not a byte offset: the border glyph before it is multibyte.
        let x = line.chars().position(|c| c == '\u{2022}').unwrap() as u16;
        assert_eq!(
            term.redacted_at(x, y).as_deref(),
            Some("AKIAIOSFODNN7EXAMPLE"),
            "the mask click recovers the value"
        );
        assert_eq!(
            term.redacted_at(x.saturating_sub(2), y),
            None,
            "off the mask: nothing"
        );
        // A row whose masked token is its LAST text: a click a few cells
        // right of the mask, still inside the pane, resolves to that blank
        // cell's own char (the colmap is dense) and reveals nothing.
        let (ty, tline) = rows
            .iter()
            .enumerate()
            .map(|(y, l)| (y as u16, l.clone()))
            .find(|(_, l)| l.starts_with("\u{2502}tail "))
            .expect("the tail line rendered");
        let tx = tline.chars().position(|c| c == '\u{2022}').unwrap() as u16;
        assert_eq!(
            term.redacted_at(tx, ty).as_deref(),
            Some("AKIAIOSFODNN7EXAMPLE"),
            "the last token's mask still reveals on itself"
        );
        assert!(tx + 24 < area.width - 1, "the probe stays inside the pane");
        assert_eq!(
            term.redacted_at(tx + 24, ty),
            None,
            "blank cells right of the row's text reveal nothing"
        );

        // A reveal window paints the text as typed and counts nothing.
        term.reveal_redactions = true;
        let mut buf = Buffer::empty(area);
        Widget::render(&mut term, area, &mut buf);
        assert!(row_text(&buf, y).contains("AKIAIOSFODNN7EXAMPLE"));
        assert_eq!(term.redacted_on_screen, 0);
    }

    #[test]
    fn faint_cells_render_with_the_dim_modifier() {
        // Claude Code paints its inline ghost suggestion as default-foreground
        // text under SGR 2 (faint). The pane must forward the flag as
        // Modifier::DIM, or the suggestion renders at full brightness and is
        // indistinguishable from text the user typed.
        let tmp = tempfile::tempdir().unwrap();
        let mut term = PtyTerminal::new_running(
            "/bin/sh",
            &[
                String::from("-c"),
                String::from("s=QQ; printf \"\\033[2m${s}GHOST\\033[0m\\n\"; sleep 30"),
            ],
            tmp.path(),
        )
        .unwrap();
        wait_for_grid(&term, |ls| ls.iter().any(|l| l.contains("QQGHOST")));
        let area = Rect::new(0, 0, 60, 10);
        let mut buf = Buffer::empty(area);
        Widget::render(&mut term, area, &mut buf);
        for y in 0..area.height {
            for x in 1..area.width - 2 {
                if buf[(x, y)].symbol() == "Q"
                    && buf[(x + 1, y)].symbol() == "Q"
                    && buf[(x + 2, y)].symbol() == "G"
                {
                    assert!(
                        buf[(x, y)].modifier.contains(Modifier::DIM),
                        "SGR 2 (faint) cells must carry Modifier::DIM"
                    );
                    return;
                }
            }
        }
        panic!("the faint sentinel never appeared in the rendered buffer");
    }

    /// A quiet pane fed the issue's bytes (#1288): two struck-through todo
    /// items, a concealed password and a plain word.
    fn strike_and_conceal_pane() -> (PtyTerminal, tempfile::TempDir) {
        let tmp = tempfile::tempdir().unwrap();
        let term = PtyTerminal::new_running(
            "/bin/sh",
            &[String::from("-c"), String::from("sleep 30")],
            tmp.path(),
        )
        .unwrap();
        term.feed_bytes_for_test(
            b"\x1b[2J\x1b[H\x1b[9mDONE\x1b[0m [\x1b[8mhunter2\x1b[0m] PLAIN\r\n",
        );
        (term, tmp)
    }

    #[test]
    fn struck_through_cells_paint_crossed_out_and_concealed_cells_paint_blank() {
        let (mut term, _tmp) = strike_and_conceal_pane();
        let area = Rect::new(0, 0, 60, 10);
        let mut buf = Buffer::empty(area);
        Widget::render(&mut term, area, &mut buf);
        let rows: Vec<String> = (0..area.height)
            .map(|y| (0..area.width).map(|x| buf[(x, y)].symbol()).collect())
            .collect();
        let y = rows
            .iter()
            .position(|r| r.contains("DONE"))
            .expect("the todo row is painted") as u16;
        let row = &rows[y as usize];
        assert!(!row.contains("hunter2"), "SGR 8 text is hidden: {row:?}");
        assert!(row.contains("DONE [       ] PLAIN"), "{row:?}");
        // Cells, not bytes: the pane border is a multi-byte glyph.
        let at = |word: &str| row[..row.find(word).unwrap()].chars().count() as u16;
        for x in at("DONE")..at("DONE") + 4 {
            assert!(
                buf[(x, y)].modifier.contains(Modifier::CROSSED_OUT),
                "SGR 9 cell at {x} is struck through"
            );
        }
        for x in at("PLAIN")..at("PLAIN") + 5 {
            assert!(
                !buf[(x, y)]
                    .modifier
                    .intersects(Modifier::CROSSED_OUT | Modifier::HIDDEN),
                "plain cell at {x} carries neither"
            );
        }
    }

    #[test]
    fn concealed_text_still_copies_and_exports_with_its_sgr() {
        // Negative: hiding is paint-only, as in xterm. The grid, and so a
        // copy, keeps the real text, and an export with styles writes the
        // attributes back out as 8 and 9 for the reader to honour.
        let (term, _tmp) = strike_and_conceal_pane();
        let (lines, _) = term.grid_lines();
        assert!(
            lines.iter().any(|l| l.contains("DONE [hunter2] PLAIN")),
            "{lines:?}"
        );
        let exported = term.grid_lines_ansi();
        let (_, raw) = exported
            .iter()
            .find(|(p, _)| p.contains("hunter2"))
            .expect("the row is exported");
        assert!(raw.contains("\x1b[9mDONE"), "{raw:?}");
        assert!(raw.contains("\x1b[8mhunter2"), "{raw:?}");
    }

    #[test]
    fn imgcat_style_inline_images_are_captured_with_a_grid_anchor() {
        use base64::Engine;
        // A 1x1 red PNG; what `imgcat tiny.png` would emit.
        let mut png_buf = Vec::new();
        image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255]))
            .write_to(
                &mut std::io::Cursor::new(&mut png_buf),
                image::ImageFormat::Png,
            )
            .expect("encode test png");
        let png: &[u8] = &png_buf;
        let b64 = base64::engine::general_purpose::STANDARD.encode(png);
        let tmp = tempfile::tempdir().unwrap();
        let script = format!(
            "printf 'before\\n'; printf '\\033]1337;File=inline=1:{b64}\\007\\n'; printf 'after\\n'; sleep 30"
        );
        let term =
            PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script], tmp.path()).unwrap();
        wait_for_grid(&term, |ls| ls.iter().any(|l| l.contains("after")));
        let mut waited = 0u32;
        let imgs = loop {
            let imgs = term.pane_images();
            if !imgs.is_empty() {
                break imgs;
            }
            assert!(waited < 8000, "inline image never captured");
            std::thread::sleep(std::time::Duration::from_millis(40));
            waited += 40;
        };
        assert_eq!(imgs.len(), 1);
        assert_eq!(imgs[0].data.as_slice(), png, "payload must round-trip");
        // Anchor: the row right after the `before` line (the run-label
        // header above it wraps, so absolute row numbers are not stable).
        let (lines, top) = term.grid_lines();
        let before_row = lines
            .iter()
            .rposition(|l| l.trim_end() == "before")
            .expect("the before line must be on the grid") as i32
            + top;
        assert_eq!(
            imgs[0].line,
            before_row + 1,
            "anchor must sit on the image's grid row; grid: {lines:?}"
        );
    }

    #[test]
    fn wide_chars_read_back_without_phantom_spacer_spaces() {
        // A CJK char occupies two grid columns: the WIDE_CHAR cell plus a
        // WIDE_CHAR_SPACER cell whose `c` is ' '. Text extraction must skip
        // the spacer, or copied/searched text comes out as "日 本 語" and a
        // find for "日本語" can never match.
        let tmp = tempfile::tempdir().unwrap();
        let term = PtyTerminal::new_running("/bin/echo", &[String::from("日本語 ok")], tmp.path())
            .unwrap();
        let lines = wait_for_grid(&term, |ls| ls.iter().any(|l| l.contains('日')));
        assert!(
            lines.iter().any(|l| l.contains("日本語 ok")),
            "wide chars must read back contiguously (no spacer-cell spaces); grid was: {lines:?}"
        );
    }

    #[test]
    fn wide_chars_render_the_glyph_once_with_a_blank_spacer_cell() {
        // The render loop writes the double-width glyph into its WIDE_CHAR
        // cell and must leave the following spacer cell blank — ratatui skips
        // the cell after a width-2 symbol when diffing, so anything else
        // there would corrupt column alignment.
        let tmp = tempfile::tempdir().unwrap();
        let mut term =
            PtyTerminal::new_running("/bin/echo", &[String::from("日X")], tmp.path()).unwrap();
        wait_for_grid(&term, |ls| ls.iter().any(|l| l.contains('日')));
        let area = Rect::new(0, 0, 40, 10);
        let mut buf = Buffer::empty(area);
        Widget::render(&mut term, area, &mut buf);
        let mut found = false;
        for y in 0..area.height {
            for x in 0..area.width.saturating_sub(2) {
                if buf[(x, y)].symbol() == "日" {
                    assert_eq!(
                        buf[(x + 1, y)].symbol(),
                        " ",
                        "the spacer cell after a wide glyph must stay blank"
                    );
                    assert_eq!(
                        buf[(x + 2, y)].symbol(),
                        "X",
                        "the next glyph must land two columns after the wide char"
                    );
                    found = true;
                }
            }
        }
        assert!(found, "the wide glyph must appear in the rendered buffer");
    }

    #[test]
    fn hyperlink_at_returns_the_osc8_uri_under_the_cell() {
        // OSC 8 hyperlinks live in the cell, invisible in the text. The app's
        // Cmd/Ctrl+click handler asks `hyperlink_at` before falling back to
        // the plain-text URL regex.
        let tmp = tempfile::tempdir().unwrap();
        let script =
            "printf '\\033]8;;https://example.com/doc\\033\\\\CLICK-ME\\033]8;;\\033\\\\\\n'";
        let term =
            PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
                .unwrap();
        // The run header echoes the command text, so "CLICK-ME" appears there
        // too — as plain text without a link. Wait for the child's actual
        // output row (the one without "printf").
        let is_output = |l: &String| l.contains("CLICK-ME") && !l.contains("printf");
        let lines = wait_for_grid(&term, |ls| ls.iter().any(is_output));
        let row = lines.iter().position(is_output).unwrap();
        let col = lines[row].find("CLICK-ME").unwrap();
        assert_eq!(
            term.hyperlink_at(row, col).as_deref(),
            Some("https://example.com/doc"),
            "the cell under the linked text must expose the OSC 8 URI"
        );
        assert_eq!(
            term.hyperlink_at(0, 0),
            None,
            "cells outside the link (the header row) carry no URI"
        );
    }

    #[test]
    fn osc133_marks_record_kind_exit_code_and_grid_line() {
        // Emit a prompt mark before "PROMPT", a command-start mark, and a
        // finished mark carrying exit 3. Marks must land on the grid lines
        // where the cursor sat when they arrived.
        let tmp = tempfile::tempdir().unwrap();
        let script = "printf 'before\\n\\033]133;A\\007PROMPT-LINE\\n\\033]133;C\\007out\\n\\033]133;D;3\\007'";
        let term =
            PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
                .unwrap();
        let is_output = |l: &String| l.contains("PROMPT-LINE") && !l.contains("printf");
        let lines = wait_for_grid(&term, |ls| {
            ls.iter().any(is_output) && !term.command_marks().is_empty()
        });
        let (_, top) = term.grid_lines();
        let prompt_row = lines.iter().position(is_output).unwrap();
        let marks = term.command_marks();
        let prompt_line = marks
            .iter()
            .find(|(kind, _)| *kind == crate::shell_integration::OscEvent::PromptStart)
            .map(|(_, line)| *line)
            .expect("a PromptStart mark must be recorded");
        assert_eq!(
            prompt_line,
            top + prompt_row as i32,
            "the prompt mark must sit on the line where PROMPT-LINE was printed"
        );
        assert!(
            marks
                .iter()
                .any(|(kind, _)| *kind == crate::shell_integration::OscEvent::CommandEnd(Some(3))),
            "the finished mark must carry exit code 3; marks: {marks:?}"
        );
    }

    #[test]
    fn marks_follow_their_content_into_scrollback() {
        // A mark recorded on the live screen must keep pointing at the same
        // content after later output scrolls that content into history.
        let tmp = tempfile::tempdir().unwrap();
        let script = "printf '\\033]133;A\\007MARKED-PROMPT\\n'; i=0; while [ $i -lt 40 ]; do echo filler-$i; i=$((i+1)); done";
        let term =
            PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
                .unwrap();
        wait_for_grid(&term, |ls| ls.iter().any(|l| l.contains("filler-39")));
        // The script's tail (trailing newline, shell exit) can scroll another
        // row or two AFTER filler-39 becomes visible. `lines` and `top` must
        // come from ONE settled snapshot, or the row index and the grid top
        // describe different moments and the compare is off by exactly the
        // late scroll (#110). Settle = two consecutive identical reads.
        let (lines, top) = {
            let mut prev = term.grid_lines();
            let mut waited = 0u32;
            loop {
                std::thread::sleep(std::time::Duration::from_millis(40));
                let cur = term.grid_lines();
                if cur == prev || waited >= 4000 {
                    break cur;
                }
                prev = cur;
                waited += 40;
            }
        };
        let content_row = lines
            .iter()
            .position(|l| l.contains("MARKED-PROMPT") && !l.contains("printf"))
            .expect("the marked line must still be in scrollback");
        let marks = term.command_marks();
        let prompt_line = marks
            .iter()
            .find(|(kind, _)| *kind == crate::shell_integration::OscEvent::PromptStart)
            .map(|(_, line)| *line)
            .expect("the mark must survive the scroll");
        assert_eq!(
            prompt_line,
            top + content_row as i32,
            "the mark must move with its content into history (negative grid lines)"
        );
        assert!(
            prompt_line < 0,
            "after 40 filler lines the mark is in scrollback"
        );
    }

    #[test]
    fn osc7_updates_the_shell_cwd() {
        let tmp = tempfile::tempdir().unwrap();
        let script = "printf '\\033]7;file://anyhost/tmp/croft%%20dir\\007ok\\n'";
        let term =
            PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
                .unwrap();
        wait_for_grid(&term, |ls| {
            ls.iter().any(|l| l.contains("ok") && !l.contains("printf"))
        });
        assert_eq!(
            term.shell_cwd(),
            Some(std::path::PathBuf::from("/tmp/croft dir")),
            "OSC 7 must update the pane's live cwd"
        );
    }

    /// A remote shell's OSC 7 (an in-pane ssh with integration) names a
    /// path on the REMOTE machine: consumers that act on the local
    /// filesystem (split-in-cwd, session restore) must not trust it just
    /// because the same path happens to exist locally.
    #[test]
    fn a_remote_reported_cwd_is_not_trusted_for_local_use() {
        let tmp = tempfile::tempdir().unwrap();
        let script = "printf '\\033]7;file://prod-db-1/tmp\\007ok\\n'; sleep 30";
        let term =
            PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
                .unwrap();
        wait_for_grid(&term, |ls| {
            ls.iter().any(|l| l.contains("ok") && !l.contains("printf"))
        });
        assert_eq!(
            term.shell_cwd(),
            Some(std::path::PathBuf::from("/tmp")),
            "staging: the raw report is visible"
        );
        assert_eq!(
            term.local_shell_cwd(),
            None,
            "a path reported by another machine must not be reused locally"
        );
        // The truthful counterpart: the reporter really sits in the
        // directory it claims (spawned in /tmp), so the claim matches the
        // kernel's cwd for the pane's shell and localhost IS this machine.
        let script = "printf '\\033]7;file://localhost/tmp\\007ok\\n'; sleep 30";
        let term2 = PtyTerminal::new_running(
            "/bin/sh",
            &[String::from("-c"), script.into()],
            std::path::Path::new("/tmp"),
        )
        .unwrap();
        wait_for_grid(&term2, |ls| {
            ls.iter().any(|l| l.contains("ok") && !l.contains("printf"))
        });
        assert_eq!(
            term2.local_shell_cwd(),
            Some(std::path::PathBuf::from("/tmp")),
            "a localhost report IS this machine (RFC 8089)"
        );
    }

    #[test]
    fn osc9_notifications_drain_once() {
        let tmp = tempfile::tempdir().unwrap();
        let script = "printf '\\033]9;build done\\007ok\\n'";
        let term =
            PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
                .unwrap();
        wait_for_grid(&term, |ls| {
            ls.iter().any(|l| l.contains("ok") && !l.contains("printf"))
        });
        assert_eq!(term.drain_notifications(), vec![String::from("build done")]);
        assert!(
            term.drain_notifications().is_empty(),
            "a second drain returns nothing"
        );
    }

    #[test]
    fn osc777_and_osc99_notifications_drain_like_osc9() {
        let tmp = tempfile::tempdir().unwrap();
        let script = "printf '\\033]777;notify;Build;finished OK\\007\\033]99;;kitty-style note\\033\\\\\\033]9;iTerm2-style note\\007ok\\n'";
        let term =
            PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
                .unwrap();
        // The echoed command wraps past the pane's width, so a wrapped half
        // of it can hold "ok" without "printf": wait for the output line.
        wait_for_grid(&term, |ls| ls.iter().any(|l| l.trim() == "ok"));
        assert_eq!(
            term.drain_notifications(),
            vec![
                String::from("Build: finished OK"),
                String::from("kitty-style note"),
                String::from("iTerm2-style note"),
            ]
        );
    }

    #[test]
    fn notify_triggers_fire_on_completed_output_lines() {
        let tmp = tempfile::tempdir().unwrap();
        // The shell waits for a line of input, so the trigger set is in
        // place before the matching output is ever produced.
        let script = "read x; echo deploy failed; sleep 30";
        let mut term =
            PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
                .unwrap();
        let set = crate::triggers::TriggerSet::from_json(
            r#"[ { "regex": "deploy (\\w+)", "action": "notify", "message": "deploy went \\1" } ]"#,
        );
        assert!(set.has_events());
        term.set_triggers(std::sync::Arc::new(set));
        term.write_input(b"\n");
        let mut waited = 0u32;
        let hits = loop {
            let hits = term.drain_trigger_hits();
            if !hits.is_empty() {
                break hits;
            }
            assert!(waited < 8000, "trigger never fired");
            std::thread::sleep(std::time::Duration::from_millis(40));
            waited += 40;
        };
        assert_eq!(hits.len(), 1, "{hits:?}");
        assert_eq!(hits[0].action, crate::triggers::TriggerAction::Notify);
        assert_eq!(hits[0].message, "deploy went failed");
    }

    /// A banner printed just before handing off to a full-screen app lands
    /// in the same PTY chunk as the alt-screen entry: gating the trigger
    /// scan on the chunk's FINAL mode dropped that whole chunk (and let a
    /// chunk that merely ENDED on the primary screen fire on alt content).
    /// The scanner tracks the boundary positionally, so the reader must
    /// feed it every chunk unconditionally.
    #[test]
    fn a_trigger_fires_for_primary_text_that_shares_a_chunk_with_alt_entry() {
        let tmp = tempfile::tempdir().unwrap();
        let script = "read x; printf 'deploy failed\\n\\033[?1049h'; sleep 1; printf '\\033[?1049lok\\n'; sleep 30";
        let mut term =
            PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
                .unwrap();
        let set = crate::triggers::TriggerSet::from_json(
            r#"[ { "regex": "deploy (\\w+)", "action": "notify", "message": "deploy went \\1" } ]"#,
        );
        assert!(set.has_events());
        term.set_triggers(std::sync::Arc::new(set));
        term.write_input(b"\n");
        let mut waited = 0u32;
        let hits = loop {
            let hits = term.drain_trigger_hits();
            if !hits.is_empty() {
                break hits;
            }
            assert!(
                waited < 8000,
                "the primary-screen line before the alt entry never fired"
            );
            std::thread::sleep(std::time::Duration::from_millis(40));
            waited += 40;
        };
        assert_eq!(hits.len(), 1, "{hits:?}");
        assert_eq!(hits[0].message, "deploy went failed");
    }

    #[test]
    fn poisoned_zdotdir_from_a_nested_croft_still_loads_the_user_rc() {
        // Regression: every pane exports ZDOTDIR=<shim>, so a croft launched
        // FROM a croft pane inherited it and treated the shim as the user's
        // dotfile dir — the shim then sourced itself in a recursion loop and
        // the user's real .zshrc (their theme, aliases) never ran. A
        // poisoned CROFT_USER_ZDOTDIR pointing at the shim must be ignored
        // in favour of $HOME.
        let Some(zsh) = zsh_or_skip() else { return };
        let home = tempfile::tempdir().unwrap();
        std::fs::write(
            home.path().join(".zshrc"),
            "USER_RC_SENTINEL=loaded\nexport USER_RC_SENTINEL\n",
        )
        .unwrap();
        let cfg_dir = tempfile::tempdir().unwrap();
        let shim = crate::shell_integration::ensure_zsh_shim(cfg_dir.path()).unwrap();
        let mut cmd = CommandBuilder::new(zsh);
        cmd.arg("-i");
        cmd.cwd(home.path());
        cmd.env("HOME", home.path());
        // The poison: both vars point at the shim itself, exactly what a
        // pane's environment hands a nested croft.
        cmd.env("ZDOTDIR", &shim);
        cmd.env("CROFT_USER_ZDOTDIR", &shim);
        let mut term = PtyTerminal::spawn_with(cmd, None).unwrap();
        let mut waited = 0u32;
        while term.prompt_lines().is_empty() {
            assert!(
                waited < 8000,
                "no prompt mark; grid: {:?}",
                term.grid_lines().0
            );
            std::thread::sleep(std::time::Duration::from_millis(40));
            waited += 40;
        }
        term.write_input(b"echo SENTINEL_IS=$USER_RC_SENTINEL\r");
        let mut waited = 0u32;
        loop {
            let (lines, _) = term.grid_lines();
            assert!(
                !lines.iter().any(|l| l.contains("recursion limit")),
                "the shim must never source itself; grid: {lines:?}"
            );
            if lines
                .iter()
                .any(|l| l.contains("SENTINEL_IS=loaded") && !l.contains("echo"))
            {
                break;
            }
            assert!(
                waited < 8000,
                "user rc never ran under a poisoned ZDOTDIR; grid: {lines:?}"
            );
            std::thread::sleep(std::time::Duration::from_millis(40));
            waited += 40;
        }
    }

    /// Build a mark stream from the old `(kind, line, col, dur)` shape,
    /// numbering ids by position. The fixtures below care about pairing, not
    /// identity, so an id per row keeps them readable while still exercising
    /// the id path.
    fn views(
        marks: &[(
            crate::shell_integration::OscEvent,
            i32,
            usize,
            Option<std::time::Duration>,
        )],
    ) -> Vec<MarkView> {
        marks
            .iter()
            .enumerate()
            .map(|(i, (kind, line, col, dur))| MarkView {
                id: i as u64 + 1,
                kind: kind.clone(),
                line: *line,
                col: *col,
                dur: *dur,
            })
            .collect()
    }

    #[test]
    fn pair_decorations_matches_prompts_with_exits() {
        use crate::shell_integration::OscEvent as E;
        let ms = std::time::Duration::from_millis;
        // Two full cycles (ok then failing), then a bare prompt with no
        // command: two records, the bare prompt contributes nothing. The
        // PromptEnd cell names where the typed command starts; the output
        // span runs from the CommandStart line up to the CommandEnd line.
        let marks = [
            (E::PromptStart, -10, 0, None),
            (E::PromptEnd, -10, 5, None),
            (E::CommandStart, -9, 0, None),
            (E::CommandEnd(Some(0)), -7, 0, Some(ms(2400))),
            (E::PromptStart, -7, 0, None),
            (E::PromptEnd, -7, 5, None),
            (E::CommandStart, -6, 0, None),
            (E::CommandEnd(Some(3)), -2, 0, Some(ms(150))),
            (E::PromptStart, -2, 0, None),
        ];
        assert_eq!(
            pair_decorations(&views(&marks)),
            vec![
                CommandDecoration {
                    // The `CommandStart` mark is the third row of the
                    // fixture, and the id comes from that mark, not from the
                    // prompt before it.
                    id: 3,
                    line: -10,
                    exit: Some(0),
                    duration: Some(ms(2400)),
                    input: Some((-10, 5)),
                    output_start: -9,
                    output_end: -7,
                },
                CommandDecoration {
                    id: 7,
                    line: -7,
                    exit: Some(3),
                    duration: Some(ms(150)),
                    input: Some((-7, 5)),
                    output_start: -6,
                    output_end: -2,
                },
            ]
        );
        // A duplicate CommandEnd (a second integration layer echoing the
        // marks) has no pending CommandStart and must be dropped.
        let dup = [
            (E::PromptStart, -5, 0, None),
            (E::CommandStart, -5, 0, None),
            (E::CommandEnd(Some(0)), -4, 0, Some(ms(90))),
            (E::CommandEnd(Some(0)), -4, 0, None),
        ];
        assert_eq!(pair_decorations(&views(&dup)).len(), 1);
        // A command still running (no CommandEnd yet) has no record.
        let running = [(E::PromptStart, 0, 0, None), (E::CommandStart, 0, 0, None)];
        assert!(pair_decorations(&views(&running)).is_empty());
    }

    #[test]
    fn command_output_and_input_extract_and_select() {
        // Copy Output / Re-run Command need the exact spans back out of the
        // grid: the typed command (from the PromptEnd cell) and the output
        // rows between CommandStart and CommandEnd. Selecting the output
        // highlights precisely those rows.
        let tmp = tempfile::tempdir().unwrap();
        let script = "printf '\\033]133;A\\007$ \\033]133;B\\007cmd --flag\\n\\033]133;C\\007out1\\nout2\\n\\033]133;D;0\\007'";
        let mut term =
            PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
                .unwrap();
        let mut waited = 0u32;
        while term.command_decorations().is_empty() {
            assert!(
                waited < 8000,
                "no decoration; marks: {:?}",
                term.command_marks()
            );
            std::thread::sleep(std::time::Duration::from_millis(40));
            waited += 40;
        }
        let deco = term.command_decorations()[0];
        assert_eq!(term.command_input_text(&deco), "cmd --flag");
        assert_eq!(term.command_output_text(&deco), "out1\nout2");
        term.select_command_output(&deco);
        let sel = term.selection().expect("output must be selected");
        let (sr, _, er, _) = sel.normalised();
        assert_eq!(
            (sr, er),
            (deco.output_start, deco.output_end - 1),
            "selection covers exactly the output rows"
        );
        assert_eq!(term.selection_text(), "out1\nout2");
    }

    #[test]
    fn human_duration_formats_ms_seconds_minutes() {
        let d = std::time::Duration::from_millis;
        assert_eq!(human_duration(d(480)), "480ms");
        assert_eq!(human_duration(d(3400)), "3.4s");
        assert_eq!(human_duration(d(59_940)), "59.9s");
        assert_eq!(human_duration(d(125_000)), "2m 05s");
    }

    #[test]
    fn osc133_decorations_carry_exit_and_duration_end_to_end() {
        // A real PTY run emitting the mark protocol: the finished command
        // must surface as one decoration with its exit code and a duration
        // covering the sleep between CommandStart and CommandEnd, and the
        // same completion must arrive once through the notification drain.
        let tmp = tempfile::tempdir().unwrap();
        let script = "printf '\\033]133;A\\007$ cmd\\n\\033]133;B\\007\\033]133;C\\007'; sleep 1; printf 'out\\n\\033]133;D;2\\007'";
        let term =
            PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
                .unwrap();
        let mut waited = 0u32;
        loop {
            let decos = term.command_decorations();
            if let Some(d) = decos.first() {
                assert_eq!(d.exit, Some(2), "exit code from 133;D;2");
                let dur = d.duration.expect("duration must be measured");
                // Marks are arrival-stamped by the reader thread, so a late
                // pickup of the pre-sleep chunk shrinks the measured gap
                // under suite load (#65): the floor sits at half the sleep.
                assert!(
                    dur >= std::time::Duration::from_millis(500),
                    "duration must cover the sleep; got {dur:?}"
                );
                break;
            }
            assert!(
                waited < 8000,
                "no decoration appeared; marks: {:?}",
                term.command_marks()
            );
            std::thread::sleep(std::time::Duration::from_millis(40));
            waited += 40;
        }
        let finished = term.drain_finished_commands();
        assert_eq!(finished.len(), 1, "one completion in the drain");
        assert_eq!(finished[0].exit, Some(2));
        assert!(finished[0].dur >= std::time::Duration::from_millis(500));
        assert!(
            term.drain_finished_commands().is_empty(),
            "a second drain returns nothing"
        );
    }

    #[test]
    fn decoration_dot_paints_on_the_left_border_and_hit_tests() {
        // The finished command's prompt row gets a VS Code-style dot on the
        // pane's left border: red here (exit 2). Clicking the dot resolves
        // back to the record via decoration_at_screen.
        let tmp = tempfile::tempdir().unwrap();
        let script = "printf '\\033]133;A\\007$ cmd\\n\\033]133;B\\007\\033]133;C\\007out\\n\\033]133;D;2\\007'";
        let mut term =
            PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
                .unwrap();
        let mut waited = 0u32;
        while term.command_decorations().is_empty() {
            assert!(
                waited < 8000,
                "no decoration; marks: {:?}",
                term.command_marks()
            );
            std::thread::sleep(std::time::Duration::from_millis(40));
            waited += 40;
        }
        let area = Rect::new(0, 0, 40, 12);
        let mut buf = Buffer::empty(area);
        (&mut term).render(area, &mut buf);
        let deco = term.command_decorations()[0];
        // Live view: display_offset 0, viewport row = grid line; +1 for the
        // top border.
        let y = 1 + u16::try_from(deco.line).unwrap();
        let cell = &buf[(0, y)];
        assert_eq!(
            cell.symbol(),
            "●",
            "dot on the left border at the prompt row"
        );
        assert_eq!(
            cell.style().fg,
            Some(Color::Rgb(0xf1, 0x4c, 0x4c)),
            "non-zero exit paints the error red"
        );
        // The border above the dot is untouched.
        assert_eq!(buf[(0, y - 1)].symbol(), "│");
        assert_eq!(
            term.decoration_at_screen(0, y),
            Some(deco),
            "clicking the dot resolves the record"
        );
        assert_eq!(
            term.decoration_at_screen(0, y - 1),
            None,
            "no record on a bare border row"
        );
    }

    #[test]
    fn foreign_terminal_shim_zdotdir_chains_to_the_user_rc() {
        // Regression: Ghostty and kitty inject their own shell integration by
        // pointing ZDOTDIR at their shim dir before launching their child.
        // When that child is croft itself (ghostty --initial-command=croft),
        // croft inherited the foreign shim as the "user" dotfile dir — a dir
        // with no .zshrc — so the user's real rc (theme, aliases) never ran.
        // The wrapper contract (kitty invented it, Ghostty copied it) is that
        // the foreign .zshenv restores the REAL ZDOTDIR when sourced; croft's
        // shim must re-read ZDOTDIR after chaining and source the user's rc
        // from wherever it landed.
        let Some(zsh) = zsh_or_skip() else { return };
        let home = tempfile::tempdir().unwrap();
        std::fs::write(
            home.path().join(".zshrc"),
            "USER_RC_SENTINEL=loaded\nexport USER_RC_SENTINEL\n",
        )
        .unwrap();
        // A Ghostty-style wrapper shim: only a .zshenv, which restores the
        // real ZDOTDIR (here: unset, meaning HOME) and chains onward.
        let foreign = tempfile::tempdir().unwrap();
        std::fs::write(
            foreign.path().join(".zshenv"),
            "builtin unset ZDOTDIR\n[[ -r \"$HOME/.zshenv\" ]] && builtin source \"$HOME/.zshenv\"\n",
        )
        .unwrap();
        let cfg_dir = tempfile::tempdir().unwrap();
        let shim = crate::shell_integration::ensure_zsh_shim(cfg_dir.path()).unwrap();
        let mut cmd = CommandBuilder::new(zsh);
        cmd.arg("-i");
        cmd.cwd(home.path());
        cmd.env("HOME", home.path());
        cmd.env("ZDOTDIR", &shim);
        // What resolve_user_zdotdir hands the pane: the inherited foreign dir.
        cmd.env("CROFT_USER_ZDOTDIR", foreign.path());
        let mut term = PtyTerminal::spawn_with(cmd, None).unwrap();
        let mut waited = 0u32;
        while term.prompt_lines().is_empty() {
            assert!(
                waited < 8000,
                "no prompt mark; grid: {:?}",
                term.grid_lines().0
            );
            std::thread::sleep(std::time::Duration::from_millis(40));
            waited += 40;
        }
        term.write_input(b"echo SENTINEL_IS=$USER_RC_SENTINEL\r");
        let mut waited = 0u32;
        loop {
            let (lines, _) = term.grid_lines();
            if lines
                .iter()
                .any(|l| l.contains("SENTINEL_IS=loaded") && !l.contains("echo"))
            {
                break;
            }
            assert!(
                waited < 8000,
                "user rc never ran behind a foreign terminal shim; grid: {lines:?}"
            );
            std::thread::sleep(std::time::Duration::from_millis(40));
            waited += 40;
        }
    }

    #[test]
    fn zsh_shim_emits_prompt_marks_end_to_end() {
        // The real proof: an interactive zsh reading croft's ZDOTDIR shim
        // must emit OSC 133 prompt marks and an OSC 7 cwd report at its
        // first prompt, with the user's own (here: empty) dotfiles sourced.
        let Some(zsh) = zsh_or_skip() else { return };
        let user_dir = tempfile::tempdir().unwrap();
        let cfg_dir = tempfile::tempdir().unwrap();
        let shim = crate::shell_integration::ensure_zsh_shim(cfg_dir.path()).unwrap();
        let mut cmd = CommandBuilder::new(zsh);
        cmd.arg("-i");
        cmd.cwd(user_dir.path());
        cmd.env("ZDOTDIR", &shim);
        cmd.env("CROFT_USER_ZDOTDIR", user_dir.path());
        let term = PtyTerminal::spawn_with(cmd, None).unwrap();
        crate::test_budget::await_spawned(
            std::time::Duration::from_millis(1000),
            "zsh to emit a prompt mark",
            || !term.prompt_lines().is_empty(),
        );
        assert!(
            term.shell_cwd().is_some(),
            "the shim's precmd must also report the cwd via OSC 7"
        );
    }

    /// The zsh shim must emit `$PWD` percent-escaped (fish already does):
    /// the sniffer unconditionally percent-DECODES OSC 7 paths, so a real
    /// directory containing `%41` used to be reported as `A`, corrupting
    /// the cwd every consumer sees.
    #[test]
    fn a_percent_directory_round_trips_through_the_zsh_shim() {
        let Some(zsh) = zsh_or_skip() else { return };
        let user_dir = tempfile::tempdir().unwrap();
        let odd = user_dir.path().join("a%41b");
        std::fs::create_dir(&odd).unwrap();
        let cfg_dir = tempfile::tempdir().unwrap();
        let shim = crate::shell_integration::ensure_zsh_shim(cfg_dir.path()).unwrap();
        let mut cmd = CommandBuilder::new(zsh);
        cmd.arg("-i");
        cmd.cwd(&odd);
        cmd.env("ZDOTDIR", &shim);
        cmd.env("CROFT_USER_ZDOTDIR", user_dir.path());
        let term = PtyTerminal::spawn_with(cmd, None).unwrap();
        // Two state-gated stages instead of one wall-clock guess: under full-
        // suite load, interactive zsh startup alone can eat a fixed budget and
        // the timeout measures the machine, not the shim (#109). First wait
        // for the prompt mark (proof the precmd hook ran), THEN the OSC 7
        // report — emitted by that same precmd — must follow almost at once.
        let mut waited = 0u32;
        while term.prompt_lines().is_empty() {
            assert!(
                waited < 20_000,
                "zsh never emitted a prompt mark; grid: {:?}",
                term.grid_lines().0
            );
            std::thread::sleep(std::time::Duration::from_millis(40));
            waited += 40;
        }
        let mut waited = 0u32;
        let cwd = loop {
            if let Some(c) = term.shell_cwd() {
                break c;
            }
            assert!(
                waited < 4000,
                "the shim's precmd ran (prompt mark present) but never reported a cwd; grid: {:?}",
                term.grid_lines().0
            );
            std::thread::sleep(std::time::Duration::from_millis(40));
            waited += 40;
        };
        assert!(
            cwd.ends_with("a%41b"),
            "the literal directory name must survive the OSC 7 round trip, got {cwd:?}"
        );
    }

    /// A bash new enough for `$ENV` + `--posix` injection (>= 4.4), for the
    /// e2e tests: Homebrew/Linux bash qualifies, macOS's system 3.2 not.
    fn modern_bash() -> Option<&'static str> {
        ["/opt/homebrew/bin/bash", "/usr/local/bin/bash", "/bin/bash"]
            .into_iter()
            .find(|b| bash_env_injection_supported(b))
    }

    /// An empty Enter in a bash whose user set PROMPT_COMMAND as an ARRAY
    /// (bash 5.1+, ble.sh and prompt frameworks do) must not fabricate a
    /// command: the DEBUG-trap guard joined the array with a SPACE
    /// (`${arr[*]}` under default IFS), so its own precmd entries never
    /// matched and every blank prompt emitted a spurious 133;C + 133;D —
    /// a phantom decoration that hijacked Cmd+K Shift+R/C/S.
    #[test]
    fn an_empty_enter_with_an_array_prompt_command_fabricates_no_command() {
        let Some(bash) = modern_bash() else {
            return;
        };
        // Array PROMPT_COMMAND execution needs bash >= 5.1.
        let out = std::process::Command::new(bash)
            .args(["-c", "echo ${BASH_VERSINFO[0]}${BASH_VERSINFO[1]}"])
            .output()
            .unwrap();
        let v: u32 = String::from_utf8_lossy(&out.stdout)
            .trim()
            .parse()
            .unwrap_or(0);
        if v < 51 {
            return;
        }
        let home = tempfile::tempdir().unwrap();
        std::fs::write(
            home.path().join(".bashrc"),
            "mytheme() { :; }\nPROMPT_COMMAND=(mytheme)\n",
        )
        .unwrap();
        let cfg = tempfile::tempdir().unwrap();
        let mut cmd = CommandBuilder::new(bash);
        cmd.cwd(home.path());
        cmd.env("HOME", home.path());
        let args = apply_shell_integration_env(&mut cmd, bash, cfg.path(), Vec::new());
        for a in &args {
            cmd.arg(a);
        }
        cmd.arg("-i");
        let mut term = PtyTerminal::spawn_with(cmd, None).unwrap();
        let mut waited = 0u32;
        while term.prompt_lines().is_empty() {
            assert!(waited < 8000, "bash never emitted a prompt mark");
            std::thread::sleep(std::time::Duration::from_millis(40));
            waited += 40;
        }
        let prompts_before = term.prompt_lines().len();
        term.write_input(b"\n");
        let mut waited = 0u32;
        while term.prompt_lines().len() <= prompts_before {
            assert!(waited < 8000, "the empty Enter never produced a new prompt");
            std::thread::sleep(std::time::Duration::from_millis(40));
            waited += 40;
        }
        assert!(
            pair_decorations(&term.marks_snapshot()).is_empty(),
            "an empty Enter must not fabricate a finished command"
        );
    }

    #[test]
    fn shell_integration_env_prepends_posix_for_modern_bash_only() {
        // bash is injected by inserting `--posix` before `-l` and pointing
        // $ENV at croft's shim — but only from 4.4 (the kitty/Ghostty
        // floor): macOS's system bash 3.2 ignores $ENV in posix mode, so
        // it reads the shim through `--rcfile` instead (VS Code's way),
        // non-login, with the shim replaying the login files. zsh
        // (ZDOTDIR) and fish (XDG_DATA_DIRS) are env-only and add nothing.
        let login = || vec!["-l".to_string()];
        let cfg = tempfile::tempdir().unwrap();
        if let Some(bash) = modern_bash() {
            let mut cmd = CommandBuilder::new(bash);
            assert_eq!(
                apply_shell_integration_env(&mut cmd, bash, cfg.path(), login()),
                vec!["--posix".to_string(), "-l".to_string()]
            );
        }
        assert!(!parse_bash_version_supported("3.2"));
        assert!(!parse_bash_version_supported("4.3"));
        assert!(!parse_bash_version_supported("garbage"));
        assert!(parse_bash_version_supported("4.4"));
        assert!(parse_bash_version_supported("5.2"));
        assert!(parse_bash_version_supported("10.0"));
        if std::path::Path::new("/bin/bash").exists() && !bash_env_injection_supported("/bin/bash")
        {
            // On a macOS box with system bash 3.2: the shim as its rcfile,
            // with no `-l`, which would make bash ignore `--rcfile`.
            let shim = crate::shell_integration::ensure_bash_shim(cfg.path()).unwrap();
            let mut cmd = CommandBuilder::new("/bin/bash");
            assert_eq!(
                apply_shell_integration_env(&mut cmd, "/bin/bash", cfg.path(), login()),
                vec!["--rcfile".to_string(), shim.display().to_string()],
                "bash 3.2 must take the shim as its rcfile, without posix injection"
            );
        }
        for shell in ["/bin/zsh", "/usr/bin/fish", "/bin/dash"] {
            let mut cmd = CommandBuilder::new(shell);
            assert_eq!(
                apply_shell_integration_env(&mut cmd, shell, cfg.path(), login()),
                login(),
                "{shell} must not gain args"
            );
        }
    }

    #[test]
    fn zsh_shim_marks_the_prompt_end_for_input_extraction() {
        // Copy Output / Re-run Command read the typed command from the
        // PromptEnd (133;B) mark. The shim must emit it itself — relying on
        // a chained foreign integration (Ghostty's) leaves remote Linux
        // panes with no input span at all.
        let Some(zsh) = zsh_or_skip() else { return };
        let user_dir = tempfile::tempdir().unwrap();
        let cfg_dir = tempfile::tempdir().unwrap();
        let shim = crate::shell_integration::ensure_zsh_shim(cfg_dir.path()).unwrap();
        let mut cmd = CommandBuilder::new(zsh);
        cmd.arg("-i");
        cmd.cwd(user_dir.path());
        cmd.env("ZDOTDIR", &shim);
        cmd.env("CROFT_USER_ZDOTDIR", user_dir.path());
        let term = PtyTerminal::spawn_with(cmd, None).unwrap();
        let mut waited = 0u32;
        loop {
            let marks = term.command_marks();
            if marks
                .iter()
                .any(|(k, _)| *k == crate::shell_integration::OscEvent::PromptEnd)
            {
                break;
            }
            assert!(
                waited < 8000,
                "zsh never emitted a PromptEnd mark; marks: {marks:?}, grid: {:?}",
                term.grid_lines().0
            );
            std::thread::sleep(std::time::Duration::from_millis(40));
            waited += 40;
        }
    }

    #[test]
    fn bash_shim_via_posix_env_emits_marks_and_sources_the_user_profile() {
        // The kitty/Ghostty bash injection end-to-end, exactly as croft
        // spawns it: `bash --posix -l` with ENV pointing at croft's shim.
        // In posix mode bash reads ONLY $ENV, so the shim must back out of
        // posix mode, replay the login startup files (the user's
        // .bash_profile here), and emit the full mark cycle with exit codes.
        // Needs a bash >= 4.4 (macOS system 3.2 ignores $ENV in posix mode
        // and is never injected).
        let Some(bash) = modern_bash() else {
            return;
        };
        let home = tempfile::tempdir().unwrap();
        std::fs::write(
            home.path().join(".bash_profile"),
            "USER_RC_SENTINEL=loaded\nexport USER_RC_SENTINEL\n",
        )
        .unwrap();
        let cfg_dir = tempfile::tempdir().unwrap();
        let shim = crate::shell_integration::ensure_bash_shim(cfg_dir.path()).unwrap();
        let mut cmd = CommandBuilder::new(bash);
        cmd.arg("--posix");
        cmd.arg("-l");
        cmd.cwd(home.path());
        cmd.env("HOME", home.path());
        cmd.env("ENV", &shim);
        cmd.env("CROFT_BASH_INJECT", "1");
        let mut term = PtyTerminal::spawn_with(cmd, None).unwrap();
        let mut waited = 0u32;
        while term.prompt_lines().is_empty() {
            assert!(
                waited < 8000,
                "bash never emitted a prompt mark; grid: {:?}",
                term.grid_lines().0
            );
            std::thread::sleep(std::time::Duration::from_millis(40));
            waited += 40;
        }
        assert!(
            term.shell_cwd().is_some(),
            "the shim's precmd must report cwd via OSC 7"
        );
        term.write_input(b"echo SENTINEL_IS=$USER_RC_SENTINEL\r");
        let mut waited = 0u32;
        loop {
            let (lines, _) = term.grid_lines();
            if lines
                .iter()
                .any(|l| l.contains("SENTINEL_IS=loaded") && !l.contains("echo"))
            {
                break;
            }
            assert!(
                waited < 8000,
                "user .bash_profile never ran through the shim; grid: {lines:?}"
            );
            std::thread::sleep(std::time::Duration::from_millis(40));
            waited += 40;
        }
        // A failing command must round-trip its exit code through 133;D and
        // the shim must mark the prompt end for input extraction.
        term.write_input(b"false\r");
        let mut waited = 0u32;
        loop {
            use crate::shell_integration::OscEvent as E;
            let marks = term.command_marks();
            if marks.iter().any(|(k, _)| *k == E::CommandEnd(Some(1))) {
                assert!(
                    marks.iter().any(|(k, _)| *k == E::PromptEnd),
                    "bash PS1 must carry the 133;B input-start mark; marks: {marks:?}"
                );
                break;
            }
            assert!(
                waited < 8000,
                "no CommandEnd(1) after `false`; marks: {marks:?}, grid: {:?}",
                term.grid_lines().0
            );
            std::thread::sleep(std::time::Duration::from_millis(40));
            waited += 40;
        }
    }

    /// A fish binary for the e2e: common install paths, then `$PATH`.
    /// Absent on plain macOS (skips), present on Linux boxes and via nix.
    fn find_fish() -> Option<String> {
        let fixed = [
            "/opt/homebrew/bin/fish",
            "/usr/local/bin/fish",
            "/usr/bin/fish",
        ];
        if let Some(f) = fixed.iter().find(|f| std::path::Path::new(f).exists()) {
            return Some((*f).to_string());
        }
        let path = std::env::var("PATH").ok()?;
        path.split(':')
            .map(|d| std::path::Path::new(d).join("fish"))
            .find(|p| p.is_file())
            .map(|p| p.display().to_string())
    }

    #[test]
    fn fish_integration_restores_xdg_dirs_and_yields_single_native_marks() {
        // fish end-to-end through croft's injection env: fish 4 must emit
        // the marks natively (croft's vendor script installs NO second
        // emitter, unlike Ghostty's which double-marks), the exit code must
        // round-trip, and the script must scrub the injection from the
        // session env so children never see it.
        let Some(fish) = find_fish() else {
            return;
        };
        let home = tempfile::tempdir().unwrap();
        let cfg_dir = tempfile::tempdir().unwrap();
        let dir = crate::shell_integration::ensure_fish_integration(cfg_dir.path()).unwrap();
        let mut cmd = CommandBuilder::new(&fish);
        cmd.arg("-i");
        cmd.arg("-l");
        cmd.cwd(home.path());
        cmd.env("HOME", home.path());
        cmd.env(
            "XDG_DATA_DIRS",
            crate::shell_integration::fish_xdg_data_dirs(&dir, None),
        );
        cmd.env("CROFT_FISH_XDG_DATA_DIR", &dir);
        let mut term = PtyTerminal::spawn_with(cmd, None).unwrap();
        let mut waited = 0u32;
        while term.prompt_lines().is_empty() {
            assert!(
                waited < 8000,
                "fish never emitted a prompt mark; grid: {:?}",
                term.grid_lines().0
            );
            std::thread::sleep(std::time::Duration::from_millis(40));
            waited += 40;
        }
        term.write_input(b"false\r");
        let mut waited = 0u32;
        loop {
            use crate::shell_integration::OscEvent as E;
            let marks = term.command_marks();
            if marks.iter().any(|(k, _)| *k == E::CommandEnd(Some(1))) {
                break;
            }
            assert!(
                waited < 8000,
                "no CommandEnd(1) after `false`; marks: {marks:?}, grid: {:?}",
                term.grid_lines().0
            );
            std::thread::sleep(std::time::Duration::from_millis(40));
            waited += 40;
        }
        // Exactly one finished record for `false`: a second emitter would
        // double-decorate every command.
        let failing: Vec<_> = term
            .command_decorations()
            .into_iter()
            .filter(|d| d.exit == Some(1))
            .collect();
        assert_eq!(failing.len(), 1, "duplicate decorations: {failing:?}");
        // The injection env must be gone inside the session.
        term.write_input(b"echo DIRS=$XDG_DATA_DIRS; set -q CROFT_FISH_XDG_DATA_DIR; and echo SI_LEAKED; or echo SI_CLEAN\r");
        let needle = format!("{}", dir.display());
        let mut waited = 0u32;
        loop {
            let (lines, _) = term.grid_lines();
            if lines
                .iter()
                .any(|l| l.contains("SI_CLEAN") && !l.contains("echo"))
            {
                assert!(
                    !lines
                        .iter()
                        .any(|l| l.contains("SI_LEAKED") && !l.contains("echo")),
                    "grid: {lines:?}"
                );
                let dirs_line = lines
                    .iter()
                    .find(|l| l.contains("DIRS=") && !l.contains("echo"))
                    .cloned()
                    .unwrap_or_default();
                assert!(
                    !dirs_line.contains(&needle),
                    "XDG_DATA_DIRS still carries the injection dir: {dirs_line}"
                );
                break;
            }
            assert!(
                waited < 8000,
                "env scrub probe never answered; grid: {lines:?}"
            );
            std::thread::sleep(std::time::Duration::from_millis(40));
            waited += 40;
        }
    }

    #[test]
    fn the_pane_bin_goes_first_on_the_pane_path() {
        let mut cmd = CommandBuilder::new("/bin/sh");
        cmd.env("PATH", "/opt/homebrew/bin:/pane-bin:/usr/bin");
        apply_pane_bin(&mut cmd, Some(std::path::Path::new("/pane-bin")));
        assert_eq!(
            cmd.get_env("PATH"),
            Some(std::ffi::OsStr::new("/pane-bin:/opt/homebrew/bin:/usr/bin"))
        );
        assert_eq!(
            cmd.get_env(crate::shell_integration::PANE_BIN_ENV),
            Some(std::ffi::OsStr::new("/pane-bin"))
        );
    }

    #[test]
    fn a_pane_with_no_bin_of_its_own_drops_an_inherited_one() {
        // A croft launched from a croft pane inherits that pane's bin, which
        // names the OUTER croft. Passing it on would hand this croft's panes
        // a different croft than the window they run in.
        let mut cmd = CommandBuilder::new("/bin/sh");
        cmd.env("PATH", "/outer-pane-bin:/usr/bin");
        cmd.env(crate::shell_integration::PANE_BIN_ENV, "/outer-pane-bin");
        apply_pane_bin(&mut cmd, None);
        assert_eq!(cmd.get_env(crate::shell_integration::PANE_BIN_ENV), None);
        assert_eq!(cmd.get_env("PATH"), Some(std::ffi::OsStr::new("/usr/bin")));
    }

    #[test]
    fn an_unset_path_is_left_for_the_shell_to_default() {
        // PATH=<pane bin> alone would leave the shell without /usr/bin.
        let mut cmd = CommandBuilder::new("/bin/sh");
        cmd.env_remove("PATH");
        apply_pane_bin(&mut cmd, Some(std::path::Path::new("/pane-bin")));
        assert_eq!(cmd.get_env("PATH"), None);
        assert_eq!(
            cmd.get_env(crate::shell_integration::PANE_BIN_ENV),
            Some(std::ffi::OsStr::new("/pane-bin"))
        );
    }

    /// A pane bin linking to a stand-in for the running croft, and another
    /// dir whose `croft` a user rc puts first on PATH (#1854). Each prints
    /// which one it is.
    struct TwoCrofts {
        _tmp: tempfile::TempDir,
        pane_bin: std::path::PathBuf,
        other_dir: std::path::PathBuf,
    }

    fn two_crofts() -> TwoCrofts {
        use std::os::unix::fs::PermissionsExt;
        let tmp = tempfile::tempdir().unwrap();
        let script = |path: &std::path::Path, name: &str| {
            std::fs::write(path, format!("#!/bin/sh\necho CROFT_IS={name}\n")).unwrap();
            std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
        };
        let running = tmp.path().join("running-croft");
        script(&running, "running");
        let other_dir = tmp.path().join("other");
        std::fs::create_dir(&other_dir).unwrap();
        script(&other_dir.join("croft"), "other");
        let pane_bin =
            crate::shell_integration::ensure_pane_bin(&tmp.path().join("cache"), &running).unwrap();
        TwoCrofts {
            _tmp: tmp,
            pane_bin,
            other_dir,
        }
    }

    /// Type `input`; the rest of the first line on screen starting `prefix`.
    fn pane_answer(term: &mut PtyTerminal, input: &[u8], prefix: &str) -> String {
        term.write_input(input);
        let answer = || {
            term.grid_lines()
                .0
                .iter()
                .find_map(|l| l.trim().strip_prefix(prefix).map(str::to_string))
        };
        crate::test_budget::await_spawned(
            std::time::Duration::from_millis(1000),
            &format!("an answer to {:?}", String::from_utf8_lossy(input)),
            || answer().is_some(),
        );
        answer().unwrap()
    }

    /// Type `croft` at the pane's first prompt; the name of the croft that ran.
    fn croft_that_answers(term: &mut PtyTerminal) -> String {
        // Text on screen, not a prompt mark, so a shell croft does not
        // integrate is waited for too.
        crate::test_budget::await_spawned(
            std::time::Duration::from_millis(1000),
            "the shell's first prompt",
            || term.grid_lines().0.iter().any(|l| !l.trim().is_empty()),
        );
        pane_answer(term, b"croft\r", "CROFT_IS=")
    }

    /// A zsh login pane whose user `file` prepends the dir holding the other
    /// croft, with the pane bin when `pane_bin`.
    fn zsh_login_pane(
        crofts: &TwoCrofts,
        home: &std::path::Path,
        cfg_dir: &std::path::Path,
        file: &str,
        pane_bin: bool,
    ) -> Option<PtyTerminal> {
        let zsh = zsh_or_skip()?;
        std::fs::write(
            home.join(file),
            format!("export PATH=\"{}:$PATH\"\n", crofts.other_dir.display()),
        )
        .unwrap();
        let shim = crate::shell_integration::ensure_zsh_shim(cfg_dir).unwrap();
        let mut cmd = CommandBuilder::new(zsh);
        cmd.arg("-l");
        cmd.arg("-i");
        cmd.cwd(home);
        cmd.env("HOME", home);
        cmd.env("ZDOTDIR", &shim);
        cmd.env("CROFT_USER_ZDOTDIR", home);
        apply_pane_bin(&mut cmd, pane_bin.then_some(crofts.pane_bin.as_path()));
        Some(PtyTerminal::spawn_with(cmd, None).unwrap())
    }

    #[test]
    fn a_zsh_pane_runs_its_own_croft_when_the_user_profile_prepends_another() {
        // #1854: the window was cargo's croft 0.2.32 while `croft --version`
        // in its pane printed Homebrew's 0.2.28, because `.zprofile` runs
        // `brew shellenv`, which puts /opt/homebrew/bin first after croft
        // set the pane's PATH.
        let crofts = two_crofts();
        let (home, cfg_dir) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
        let Some(mut term) =
            zsh_login_pane(&crofts, home.path(), cfg_dir.path(), ".zprofile", true)
        else {
            return;
        };
        assert_eq!(croft_that_answers(&mut term), "running");
    }

    #[test]
    fn a_zsh_pane_runs_its_own_croft_when_the_user_login_file_prepends_another() {
        // A login zsh reads `.zlogin` after `.zshrc`, so a prepend there
        // lands after the shim's `.zshrc` has put the pane bin first.
        let crofts = two_crofts();
        let (home, cfg_dir) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
        let Some(mut term) = zsh_login_pane(&crofts, home.path(), cfg_dir.path(), ".zlogin", true)
        else {
            return;
        };
        assert_eq!(croft_that_answers(&mut term), "running");
    }

    #[test]
    fn a_zsh_pane_without_a_pane_bin_keeps_the_user_path() {
        // With no pane bin the shims must leave PATH as the user's files
        // made it: their own croft first, and no empty entry, which a shell
        // reads as the current directory.
        let crofts = two_crofts();
        let (home, cfg_dir) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
        let Some(mut term) = zsh_login_pane(&crofts, home.path(), cfg_dir.path(), ".zlogin", false)
        else {
            return;
        };
        assert_eq!(croft_that_answers(&mut term), "other");
        assert_eq!(
            pane_answer(
                &mut term,
                b"case :$PATH: in *::*) echo E=1;; *) echo E=0;; esac\r",
                "E="
            ),
            "0"
        );
    }

    #[test]
    fn a_bash_login_pane_runs_its_own_croft_when_the_profile_prepends_another() {
        // The production argv, so macOS's bash 3.2, which cannot take the
        // `$ENV` injection, is covered as well as a modern bash.
        let bash = "/bin/bash";
        if !std::path::Path::new(bash).exists() {
            return;
        }
        let crofts = two_crofts();
        let (home, cfg_dir) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
        std::fs::write(
            home.path().join(".bash_profile"),
            format!("export PATH=\"{}:$PATH\"\n", crofts.other_dir.display()),
        )
        .unwrap();
        let mut cmd = interactive_shell_command(bash, cfg_dir.path());
        cmd.cwd(home.path());
        cmd.env("HOME", home.path());
        cmd.env("HISTFILE", home.path().join(".bash_history"));
        apply_pane_bin(&mut cmd, Some(&crofts.pane_bin));
        let mut term = PtyTerminal::spawn_with(cmd, None).unwrap();
        assert_eq!(croft_that_answers(&mut term), "running");
    }

    #[test]
    fn a_bash_login_pane_without_env_injection_reports_command_exits() {
        // macOS's bash 3.2 takes the shim through `--rcfile`, so its panes
        // get the prompt and command marks a modern bash does.
        if !std::path::Path::new("/bin/bash").exists() || bash_env_injection_supported("/bin/bash")
        {
            return;
        }
        let (home, cfg_dir) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
        let mut cmd = interactive_shell_command("/bin/bash", cfg_dir.path());
        cmd.cwd(home.path());
        cmd.env("HOME", home.path());
        cmd.env("HISTFILE", home.path().join(".bash_history"));
        let mut term = PtyTerminal::spawn_with(cmd, None).unwrap();
        crate::test_budget::await_spawned(
            std::time::Duration::from_millis(1000),
            "bash 3.2's first prompt mark",
            || !term.prompt_lines().is_empty(),
        );
        term.write_input(b"false\r");
        crate::test_budget::await_spawned(
            std::time::Duration::from_millis(1000),
            "the CommandEnd(1) mark for `false`",
            || {
                term.command_marks()
                    .iter()
                    .any(|(k, _)| *k == crate::shell_integration::OscEvent::CommandEnd(Some(1)))
            },
        );
    }

    #[test]
    fn a_non_login_bash_without_env_injection_replays_no_login_files() {
        // Below 4.4 bash reads the shim as its rcfile, which a login bash
        // ignores, so the shim replays the login files itself when asked.
        // Only a login spawn may ask.
        if !std::path::Path::new("/bin/bash").exists() || bash_env_injection_supported("/bin/bash")
        {
            return;
        }
        let cfg = tempfile::tempdir().unwrap();
        let shim = crate::shell_integration::ensure_bash_shim(cfg.path()).unwrap();
        let rcfile = vec!["--rcfile".to_string(), shim.display().to_string()];
        let mut cmd = CommandBuilder::new("/bin/bash");
        assert_eq!(
            apply_shell_integration_env(&mut cmd, "/bin/bash", cfg.path(), Vec::new()),
            rcfile
        );
        assert_eq!(cmd.get_env("CROFT_BASH_LOGIN"), None);
        let mut cmd = CommandBuilder::new("/bin/bash");
        assert_eq!(
            apply_shell_integration_env(&mut cmd, "/bin/bash", cfg.path(), vec!["-l".to_string()]),
            rcfile
        );
        assert_eq!(
            cmd.get_env("CROFT_BASH_LOGIN"),
            Some(std::ffi::OsStr::new("1"))
        );
    }

    #[test]
    fn a_bash_pane_runs_its_own_croft_when_the_user_rc_prepends_another() {
        // The shim is read through `--rcfile` here, which every bash honours,
        // so macOS's 3.2 runs the same script `$ENV` hands a modern bash.
        let bash = "/bin/bash";
        if !std::path::Path::new(bash).exists() {
            return;
        }
        let crofts = two_crofts();
        let home = tempfile::tempdir().unwrap();
        std::fs::write(
            home.path().join(".bashrc"),
            format!("export PATH=\"{}:$PATH\"\n", crofts.other_dir.display()),
        )
        .unwrap();
        let cfg_dir = tempfile::tempdir().unwrap();
        let shim = crate::shell_integration::ensure_bash_shim(cfg_dir.path()).unwrap();
        let mut cmd = CommandBuilder::new(bash);
        cmd.arg("--rcfile");
        cmd.arg(&shim);
        cmd.arg("-i");
        cmd.cwd(home.path());
        cmd.env("HOME", home.path());
        cmd.env("CROFT_BASH_INJECT", "1");
        apply_pane_bin(&mut cmd, Some(&crofts.pane_bin));
        let mut term = PtyTerminal::spawn_with(cmd, None).unwrap();
        assert_eq!(croft_that_answers(&mut term), "running");
    }

    #[test]
    fn a_fish_pane_runs_its_own_croft_when_the_user_config_prepends_another() {
        let Some(fish) = find_fish() else {
            return;
        };
        let crofts = two_crofts();
        let home = tempfile::tempdir().unwrap();
        let config = home.path().join(".config");
        std::fs::create_dir_all(config.join("fish")).unwrap();
        std::fs::write(
            config.join("fish").join("config.fish"),
            format!("set -gx PATH {} $PATH\n", crofts.other_dir.display()),
        )
        .unwrap();
        let cfg_dir = tempfile::tempdir().unwrap();
        let dir = crate::shell_integration::ensure_fish_integration(cfg_dir.path()).unwrap();
        let mut cmd = CommandBuilder::new(&fish);
        cmd.arg("-i");
        cmd.arg("-l");
        cmd.cwd(home.path());
        cmd.env("HOME", home.path());
        cmd.env("XDG_CONFIG_HOME", &config);
        cmd.env(
            "XDG_DATA_DIRS",
            crate::shell_integration::fish_xdg_data_dirs(&dir, None),
        );
        cmd.env("CROFT_FISH_XDG_DATA_DIR", &dir);
        apply_pane_bin(&mut cmd, Some(&crofts.pane_bin));
        let mut term = PtyTerminal::spawn_with(cmd, None).unwrap();
        assert_eq!(croft_that_answers(&mut term), "running");
    }

    #[test]
    fn prompt_jump_targets_walk_previous_and_next() {
        // Pure chooser used by Cmd+Up / Cmd+Down: pick the nearest prompt
        // line above / below the current viewport top, if any.
        let prompts = [-30, -12, 0];
        assert_eq!(pick_prompt_jump(&prompts, 0, false), Some(-12));
        assert_eq!(pick_prompt_jump(&prompts, -12, false), Some(-30));
        assert_eq!(pick_prompt_jump(&prompts, -30, false), None);
        assert_eq!(pick_prompt_jump(&prompts, -30, true), Some(-12));
        assert_eq!(pick_prompt_jump(&prompts, -12, true), Some(0));
        assert_eq!(pick_prompt_jump(&prompts, 0, true), None);
    }

    #[test]
    fn bell_sets_a_flag_the_app_can_drain() {
        let tmp = tempfile::tempdir().unwrap();
        let script = "printf 'DONE\\007\\n'";
        let term =
            PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
                .unwrap();
        // Wait for the child's output row, not the run header echoing the
        // command text — the BEL byte arrives with the output.
        wait_for_grid(&term, |ls| {
            ls.iter()
                .any(|l| l.contains("DONE") && !l.contains("printf"))
        });
        assert!(
            term.take_bell(),
            "BEL from the child must set the bell flag for the app to drain"
        );
        assert!(
            !term.take_bell(),
            "take_bell drains the flag — a second read is false"
        );
    }

    /// #678: a program in the pane copying through OSC 52 (Claude Code over
    /// SSH has no other way) must reach the app, once, and only for the
    /// clipboard: a primary-selection store is not a copy the user made.
    #[test]
    fn osc52_clipboard_store_is_latched_for_the_app_and_selection_is_not() {
        let tmp = tempfile::tempdir().unwrap();
        // "aGVsbG8=" is "hello"; the primary-selection store ("p") comes
        // first so a leak of it would be overwritten into a false pass only
        // if it were accepted AND ordered last.
        let script = "printf '\\033]52;c;aGVsbG8=\\007\\033]52;p;bm9wZQ==\\007DONE\\n'";
        let term =
            PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
                .unwrap();
        wait_for_grid(&term, |ls| {
            ls.iter()
                .any(|l| l.contains("DONE") && !l.contains("printf"))
        });
        assert_eq!(
            term.take_clipboard_store().as_deref(),
            Some("hello"),
            "the clipboard store must be latched, and the selection store ignored"
        );
        assert_eq!(
            term.take_clipboard_store(),
            None,
            "take_clipboard_store drains the latch"
        );
    }

    /// #257: the colour export round-trips through the log parser: the
    /// text is what the pane showed and the coloured run keeps its colour
    /// and weight, as the 16 symbolic slots the theme resolves.
    #[test]
    fn grid_lines_ansi_carries_the_pane_colours_as_sgr() {
        let tmp = tempfile::tempdir().unwrap();
        // The sentinel is assembled at runtime so the pane's run-label header
        // can never match the scan below.
        let term = PtyTerminal::new_running(
            "/bin/sh",
            &[
                String::from("-c"),
                String::from("s=QQ; printf \"\\033[1;31m${s}RED\\033[0m plain\\n\"; sleep 30"),
            ],
            tmp.path(),
        )
        .unwrap();
        wait_for_grid(&term, |ls| ls.iter().any(|l| l.contains("QQRED plain")));
        let exported = term.grid_lines_ansi();
        let (plain, raw) = exported
            .iter()
            .find(|(p, _)| p.contains("QQRED"))
            .expect("the coloured row is exported");
        let mut style = crate::ansi_text::AnsiStyle::default();
        let parsed = crate::ansi_text::parse_line(raw, &mut style);
        assert_eq!(
            parsed.text.trim_end(),
            plain.trim_end(),
            "the plain twin is the coloured row with its escapes stripped"
        );
        assert!(
            parsed.text.starts_with("QQRED plain"),
            "escapes never reach the text: {:?}",
            parsed.text
        );
        let red = parsed
            .spans
            .iter()
            .find(|s| s.start == 0 && s.end >= 5)
            .unwrap_or_else(|| {
                panic!("a span covers the red run: {:?} from {raw:?}", parsed.spans)
            });
        assert_eq!(
            red.style.fg,
            Some(crate::ansi_text::AnsiColor::Indexed(1)),
            "SGR 31 comes back as the symbolic red slot"
        );
        assert!(red.style.bold, "SGR 1 comes back as bold");
        let plain = parsed.spans.iter().find(|s| s.start >= 5);
        assert!(
            plain.is_none_or(|s| s.style.fg.is_none() && !s.style.bold),
            "the reset ends the run: {:?}",
            parsed.spans
        );
    }

    /// #356: the recorder's screen read is the visible screen in colour,
    /// with the cursor where the program put it, and no cursor once the
    /// program hides it.
    #[test]
    fn screen_ansi_wrapped_carries_colour_and_the_cursor() {
        let tmp = tempfile::tempdir().unwrap();
        let term = PtyTerminal::new_running(
            "/bin/sh",
            &[
                String::from("-c"),
                String::from(
                    "s=QQ; printf \"\\033[1;31m${s}RED\\033[0m plain\\n\\033[4;7H\"; sleep 30",
                ),
            ],
            tmp.path(),
        )
        .unwrap();
        wait_for_grid(&term, |ls| ls.iter().any(|l| l.contains("QQRED plain")));
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
        let (rows, cursor) = loop {
            let (rows, cursor) = term.screen_ansi_wrapped();
            if cursor == Some((3, 6)) || std::time::Instant::now() > deadline {
                break (rows, cursor);
            }
            std::thread::sleep(std::time::Duration::from_millis(20));
        };
        assert_eq!(cursor, Some((3, 6)), "CSI 4;7H is row 3, column 6");
        let (_, ansi, _) = rows
            .iter()
            .find(|(plain, _, _)| plain.contains("QQRED"))
            .expect("the coloured row is on screen");
        assert!(ansi.contains("\x1b[1;31mQQRED\x1b[0m plain"), "{ansi:?}");
        assert_eq!(
            rows.len(),
            term.term.lock().screen_lines(),
            "the screen, and none of the scrollback above it"
        );

        term.feed_bytes_for_test(b"\x1b[?25l");
        assert_eq!(
            term.screen_ansi_wrapped().1,
            None,
            "a hidden cursor is none"
        );
    }

    #[test]
    fn grid_lines_exposes_output_for_terminal_find() {
        // The find bar searches the grid text this returns. Spawn a program
        // that prints a known needle, wait for it, and confirm the search
        // helpers locate it on the mapped grid line.
        let tmp = tempfile::tempdir().unwrap();
        let needle = "croft-find-needle-42";
        let term =
            PtyTerminal::new_running("/bin/echo", &[String::from(needle)], tmp.path()).unwrap();
        let mut waited_ms = 0u32;
        loop {
            let (lines, top) = term.grid_lines();
            if let Some(row) = lines.iter().position(|l| l.contains(needle)) {
                let hit = crate::widgets::editor_find::find_next_match(
                    &lines,
                    needle,
                    crate::widgets::search::SearchOpts::default(),
                    0,
                    0,
                    false,
                )
                .expect("search must find the printed needle");
                assert_eq!(hit.row, row, "match row must line up with the grid row");
                // `top + row` maps the hit back to an absolute grid line the
                // viewport can scroll to; for the live screen that is >= 0.
                assert!(top + hit.row as i32 >= top);
                break;
            }
            assert!(waited_ms < 4000, "echo output never reached the grid");
            std::thread::sleep(std::time::Duration::from_millis(20));
            waited_ms += 20;
        }
    }

    #[test]
    fn pending_bytes_counts_advanced_output_and_resets_on_take_dirty() {
        let tmp = tempfile::tempdir().unwrap();
        let term = PtyTerminal::new_running(
            "/bin/echo",
            &[String::from("croft-pending-bytes-probe")],
            tmp.path(),
        )
        .unwrap();
        // The wait is load-scaled (#307): /bin/echo through a PTY is
        // milliseconds on a quiet box and seconds when the suite is spawning
        // dozens of shells at once, and no constant here can know which.
        crate::test_budget::await_spawned(
            std::time::Duration::from_millis(500),
            "/bin/echo to deliver a byte through the PTY",
            || term.peek_pending_bytes() > 0,
        );
        assert!(
            term.peek_pending_bytes() > 0,
            "the reader thread must accumulate the bytes it advanced so the main loop can tell echo from a bulk stream"
        );
        assert!(
            term.peek_pending_bytes() <= 4096,
            "a one-line echo must stay under the small-update threshold so it bypasses the redraw cap"
        );
        let _ = term.take_dirty();
        assert_eq!(
            term.peek_pending_bytes(),
            0,
            "take_dirty must reset the byte accumulator so the next window starts from zero"
        );
    }

    #[test]
    fn new_running_renders_running_header_in_term_immediately() {
        let tmp = tempfile::tempdir().unwrap();
        let term = PtyTerminal::new_running(
            "/bin/echo",
            &[String::from("croft-header-probe")],
            tmp.path(),
        )
        .unwrap();
        let snapshot = term.visible_text();
        assert!(
            snapshot.contains("/bin/echo croft-header-probe"),
            "expected the run command in the header line; got:\n{snapshot}"
        );
        assert!(
            snapshot.starts_with('▶') || snapshot.contains("▶ "),
            "expected a ▶ marker on the header line; got:\n{snapshot}"
        );
    }

    #[test]
    fn new_running_appends_exit_footer_when_child_finishes() {
        let tmp = tempfile::tempdir().unwrap();
        let term =
            PtyTerminal::new_running("/bin/echo", &[String::from("croft-exit-probe")], tmp.path())
                .unwrap();
        let mut waited_ms = 0u32;
        let footer_needle = "[Process exited]";
        loop {
            if term.visible_text().contains(footer_needle) {
                break;
            }
            if waited_ms >= 4000 {
                let snap = term.visible_text();
                panic!(
                    "expected '{footer_needle}' to appear within 4s of the child exiting; got:\n{snap}"
                );
            }
            std::thread::sleep(std::time::Duration::from_millis(20));
            waited_ms += 20;
        }
    }

    #[test]
    fn new_for_interactive_shell_does_not_render_running_header() {
        let tmp = tempfile::tempdir().unwrap();
        let term = PtyTerminal::new(tmp.path()).unwrap();
        std::thread::sleep(std::time::Duration::from_millis(50));
        let snapshot = term.visible_text();
        assert!(
            !snapshot.contains("▶ "),
            "interactive shell must not render a one-shot script header; got:\n{snapshot}"
        );
        assert!(
            !snapshot.contains("[Process exited]"),
            "interactive shell must not render an exit footer; got:\n{snapshot}"
        );
    }

    #[test]
    fn selection_normalised_handles_anchor_after_head() {
        let s = Selection {
            anchor: (5, 4),
            head: (2, 1),
            block: false,
        };
        assert_eq!(s.normalised(), (2, 1, 5, 4));
    }

    #[test]
    fn selection_normalised_handles_same_row() {
        let s = Selection {
            anchor: (3, 9),
            head: (3, 2),
            block: false,
        };
        assert_eq!(s.normalised(), (3, 2, 3, 9));
    }

    #[test]
    fn selection_has_area_only_when_endpoints_differ() {
        let s = Selection::new(2, 5);
        assert!(!s.has_area());
        let s2 = Selection {
            anchor: (2, 5),
            head: (2, 6),
            block: false,
        };
        assert!(s2.has_area());
    }

    #[test]
    fn cell_in_selection_within_single_row() {
        assert!(cell_in_selection(2, 5, 2, 3, 2, 7));
        assert!(!cell_in_selection(2, 2, 2, 3, 2, 7));
        assert!(!cell_in_selection(2, 8, 2, 3, 2, 7));
        assert!(!cell_in_selection(1, 5, 2, 3, 2, 7));
        assert!(!cell_in_selection(3, 5, 2, 3, 2, 7));
    }

    #[test]
    fn cell_in_selection_spans_multiple_rows() {
        assert!(!cell_in_selection(1, 4, 1, 5, 3, 2));
        assert!(cell_in_selection(1, 5, 1, 5, 3, 2));
        assert!(cell_in_selection(1, 9, 1, 5, 3, 2));
        assert!(cell_in_selection(2, 0, 1, 5, 3, 2));
        assert!(cell_in_selection(2, 9, 1, 5, 3, 2));
        assert!(cell_in_selection(3, 2, 1, 5, 3, 2));
        assert!(!cell_in_selection(3, 3, 1, 5, 3, 2));
        assert!(!cell_in_selection(4, 0, 1, 5, 3, 2));
    }

    #[test]
    fn osc52_copy_seq_wraps_with_correct_envelope() {
        let bytes = osc52_copy_seq("hello");
        assert_eq!(bytes, b"\x1b]52;c;aGVsbG8=\x07");
    }

    #[test]
    fn osc52_copy_seq_handles_empty() {
        assert_eq!(osc52_copy_seq(""), b"\x1b]52;c;\x07");
    }

    #[test]
    fn osc52_copy_seq_handles_unicode() {
        let bytes = osc52_copy_seq("héllo");
        assert!(bytes.starts_with(b"\x1b]52;c;"));
        assert_eq!(*bytes.last().unwrap(), 0x07);
        let body = &bytes[7..bytes.len() - 1];
        use base64::Engine;
        let decoded = base64::engine::general_purpose::STANDARD
            .decode(body)
            .unwrap();
        assert_eq!(decoded, "héllo".as_bytes());
    }

    #[test]
    fn select_word_at_in_term_brackets_the_alphanumeric_run_around_the_pivot() {
        let mut t = fresh_term(40, 5);
        feed(&mut t, b"hello world from croft");
        let got = select_word_at_in_term(&t, 0, 0, 8);
        assert_eq!(
            got,
            Some(((0, 6), (0, 10))),
            "pivot inside 'world' must select cols 6..=10"
        );
    }

    #[test]
    fn select_word_at_in_term_returns_none_when_pivot_is_on_whitespace() {
        let mut t = fresh_term(40, 5);
        feed(&mut t, b"hello world");
        assert_eq!(
            select_word_at_in_term(&t, 0, 0, 5),
            None,
            "pivot on the space between 'hello' and 'world' must yield no selection"
        );
    }

    #[test]
    fn select_word_at_in_term_treats_underscores_as_word_chars_and_dots_as_boundaries() {
        let mut t = fresh_term(40, 5);
        feed(&mut t, b"foo_bar.baz");
        assert_eq!(
            select_word_at_in_term(&t, 0, 0, 2),
            Some(((0, 0), (0, 6))),
            "'foo_bar' is one word (underscore is a word char), '.baz' is separate"
        );
        assert_eq!(
            select_word_at_in_term(&t, 0, 0, 9),
            Some(((0, 8), (0, 10))),
            "pivot inside 'baz' must select cols 8..=10"
        );
    }

    /// Double-click on a word that lives in scrollback must still
    /// word-select. Pre-fix, `select_word_at_in_term` ignored the
    /// scrollback offset and read the live grid at the same viewport
    /// row, which was usually blank — the lookup returned None and
    /// the user saw "double-click doesn't auto-select."
    #[test]
    fn select_word_at_in_term_word_selects_in_scrollback_when_display_offset_is_nonzero() {
        let mut t = fresh_term(20, 3);
        // Push three lines into scrollback by feeding six rows into a
        // three-row viewport.
        feed(
            &mut t,
            b"scroll-A row\r\nscroll-B row\r\nscroll-C row\r\nlive-D row\r\nlive-E row\r\nlive-F row",
        );
        t.scroll_display(alacritty_terminal::grid::Scroll::Delta(2));
        let display_offset = t.grid().display_offset();
        assert_eq!(
            display_offset, 2,
            "precondition: Scroll::Delta(2) must move the viewport into scrollback"
        );
        // Viewport row 0 with display_offset=2 = grid Line(-2) =
        // "scroll-B row". Pivot at column 2 sits inside "scroll-B".
        let got = select_word_at_in_term(&t, display_offset, 0, 2);
        assert!(
            got.is_some(),
            "double-click on a scrolled-back row must return a real anchor/head, not None - if this is None the user sees the double-click 'do nothing'"
        );
        let (anchor, head) = got.unwrap();
        // "scroll-B" spans cols 0..=7 (s=0, c=1, r=2, o=3, l=4, l=5,
        // -=… actually '-' is not a word char, so the word is
        // "scroll" at cols 0..=5). The pivot is at col 2, which
        // lives inside "scroll". The selection must cover that run.
        assert_eq!(
            anchor,
            (0, 0),
            "anchor must mark the start of the word run on viewport row 0"
        );
        assert_eq!(
            head,
            (0, 5),
            "head must mark the last char of 'scroll' before the hyphen breaks the word run"
        );
    }

    #[test]
    fn extract_selection_text_single_line() {
        let mut t = fresh_term(20, 5);
        feed(&mut t, b"hello world");
        let txt = extract_selection_text(&t, 0, 6, 0, 10);
        assert_eq!(txt, "world");
    }

    #[test]
    fn copying_keeps_a_space_at_a_wrap_and_combining_marks() {
        let mut t = fresh_term(10, 5);
        feed(&mut t, b"echo abcd efg");
        assert_eq!(extract_selection_text(&t, 0, 0, 1, 9), "echo abcd efg");
        let mut t = fresh_term(20, 5);
        feed(&mut t, "cafe\u{301}".as_bytes());
        assert_eq!(extract_selection_text(&t, 0, 0, 0, 19), "cafe\u{301}");
    }

    #[test]
    fn extract_selection_text_multi_line_trims_trailing_spaces() {
        let mut t = fresh_term(20, 5);
        feed(&mut t, b"first line\r\nsecond line");
        let txt = extract_selection_text(&t, 0, 6, 1, 5);
        assert_eq!(txt, "line\nsecond");
    }

    /// `extract_selection_text` now addresses absolute grid lines, so a
    /// negative line index reads scrollback directly and a given line
    /// returns the same content no matter how the viewport is scrolled.
    /// This is the property that lets a selection survive scrolling: the
    /// endpoints name content, not screen rows.
    #[test]
    fn extract_selection_text_addresses_absolute_grid_lines() {
        let mut t = fresh_term(20, 3);
        // Six lines into a 3-row viewport. Each `\r\n` past the bottom
        // pushes the topmost row into scrollback. End-state:
        //   scrollback: scroll-A = Line(-3), scroll-B = Line(-2), scroll-C = Line(-1)
        //   live:       live-D = Line(0), live-E = Line(1), live-F = Line(2)
        feed(
            &mut t,
            b"scroll-A row\r\nscroll-B row\r\nscroll-C row\r\nlive-D row\r\nlive-E row\r\nlive-F row",
        );

        assert_eq!(
            extract_selection_text(&t, 0, 0, 0, 19),
            "live-D row",
            "Line(0) is the first live row"
        );
        assert_eq!(
            extract_selection_text(&t, -2, 0, -2, 19),
            "scroll-B row",
            "Line(-2) reads the scrollback row directly, no display_offset needed"
        );

        // Scrolling the viewport must NOT change what an absolute line
        // returns - that invariant is why a selection no longer drifts
        // when the user scrolls mid-drag.
        t.scroll_display(alacritty_terminal::grid::Scroll::Delta(2));
        assert_eq!(t.grid().display_offset(), 2);
        assert_eq!(
            extract_selection_text(&t, -2, 0, -2, 19),
            "scroll-B row",
            "Line(-2) still reads 'scroll-B row' after scrolling - absolute lines are scroll-invariant"
        );
    }

    /// The whole point of the fix: a selection that spans from scrollback
    /// history into the live screen extracts every line, even though it
    /// is far taller than the 3-row viewport. Before the absolute-
    /// coordinate model the selection was capped at the visible pane
    /// height and the off-screen lines were simply unreachable.
    #[test]
    fn selection_stays_glued_to_its_content_while_output_streams() {
        // A selection made while a program keeps printing (Claude Code, any
        // streaming TUI) must track its content into scrollback, not stay at
        // fixed grid lines while the text slides underneath.
        let tmp = tempfile::tempdir().unwrap();
        let go = tmp.path().join("go");
        // Sentinel assembled at runtime so the `▶ sh -c …` run-label header
        // (which echoes the script text) can never match it.
        let script = format!(
            "t=TAR; echo \"${{t}}GET-line\"; until [ -e {} ]; do sleep 0.05; done; seq 1 60; sleep 30",
            go.display()
        );
        let mut term =
            PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script], tmp.path()).unwrap();
        let mut waited = 0u32;
        let line = loop {
            let (lines, top) = term.grid_lines();
            if let Some(idx) = lines.iter().position(|l| l.starts_with("TARGET-line")) {
                break top + idx as i32;
            }
            assert!(waited < 8000, "sentinel never arrived");
            std::thread::sleep(std::time::Duration::from_millis(20));
            waited += 20;
        };
        term.set_selection(Some(Selection {
            anchor: (line, 0),
            head: (line, 30),
            block: false,
        }));
        assert_eq!(term.selection_text(), "TARGET-line");

        // Release the second phase: 60 more lines scroll the buffer.
        std::fs::File::create(&go).unwrap();
        let mut waited = 0u32;
        while !term.grid_lines().0.iter().any(|l| l == "60") {
            assert!(waited < 8000, "streamed output never arrived");
            std::thread::sleep(std::time::Duration::from_millis(20));
            waited += 20;
        }
        assert_eq!(
            term.selection_text(),
            "TARGET-line",
            "the selection must follow its content as output streams past it"
        );
        let sel = term.selection().expect("selection survives streaming");
        assert!(
            sel.anchor.0 < line,
            "reported endpoints re-anchor upward as lines scroll into history"
        );
    }

    #[test]
    fn selection_survives_streaming_past_a_saturated_scrollback() {
        // Once a pane has scrolled more than SCROLLBACK_LINES, history_size
        // saturates at the cap while content keeps rotating through the
        // ring. A selection made in that state must still track its content
        // as more output streams (the live Claude Code pane: long-running,
        // scrollback full since forever).
        let tmp = tempfile::tempdir().unwrap();
        let go = tmp.path().join("go");
        let script = format!(
            "seq 1 5200; t=TAR; echo \"${{t}}GET-line\"; until [ -e {} ]; do sleep 0.05; done; seq 1 60; sleep 30",
            go.display()
        );
        let mut term =
            PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script], tmp.path()).unwrap();
        let mut waited = 0u32;
        let line = loop {
            let (lines, top) = term.grid_lines();
            if let Some(idx) = lines.iter().position(|l| l.starts_with("TARGET-line")) {
                break top + idx as i32;
            }
            assert!(waited < 8000, "sentinel never arrived");
            std::thread::sleep(std::time::Duration::from_millis(20));
            waited += 20;
        };
        let hist_at_select = term.term.lock().grid().history_size();
        term.set_selection(Some(Selection {
            anchor: (line, 0),
            head: (line, 30),
            block: false,
        }));
        assert_eq!(term.selection_text(), "TARGET-line");

        std::fs::File::create(&go).unwrap();
        let mut waited = 0u32;
        while !term.grid_lines().0.iter().any(|l| l == "60") {
            assert!(waited < 8000, "streamed output never arrived");
            std::thread::sleep(std::time::Duration::from_millis(20));
            waited += 20;
        }
        // Premise of this test: the scrollback was already full, so
        // history_size never moved even though 60 lines scrolled past.
        assert_eq!(
            term.term.lock().grid().history_size(),
            hist_at_select,
            "test setup must saturate the scrollback before streaming"
        );
        assert_eq!(
            term.selection_text(),
            "TARGET-line",
            "the selection must follow its content even with history_size saturated"
        );
    }

    #[test]
    fn alt_screen_selection_stays_partially_visible_when_app_chrome_covers_its_edge() {
        // Scrolling Claude Code slides the selected block toward its input
        // box; the rows that reach it are overdrawn by the box while the
        // rest stay visible. The surviving rows must keep their highlight
        // (matched as a partial block), and copy must still yield the whole
        // remembered selection.
        let (_tmp, mut t) = quiet_pty();
        feed_pty(
            &t,
            b"\x1b[?1049h\x1b[H\x1b[2Jalpha one\r\nbravo two\r\ncharlie three\r\ndelta four\r\necho five",
        );
        t.set_selection(Some(Selection {
            anchor: (1, 0),
            head: (3, 9),
            block: false,
        }));
        assert_eq!(t.selection_text(), "bravo two\ncharlie three\ndelta four");

        // The app scrolls one line; the block's last row slides under the
        // input box, which repaints over it. Rows 0-1 of the block survive
        // at lines 0-1; line 2 onward is app chrome.
        feed_pty(
            &t,
            b"\x1b[H\x1b[2Jbravo two\r\ncharlie three\r\n> INPUT BOX\r\n> more chrome\r\n> even more",
        );
        t.rebase_selection();
        let anchor = t.alt_sel.as_ref().expect("anchor survives");
        assert!(
            !anchor.dormant,
            "two of three selected rows are still on screen: not dormant"
        );
        assert_eq!(
            anchor.visible,
            Some(vec![(0, 0, u16::MAX), (1, 0, u16::MAX)]),
            "only the surviving rows keep their highlight"
        );
        assert_eq!(
            t.selection_text(),
            "bravo two\ncharlie three\ndelta four",
            "copy yields the whole remembered selection while partially covered"
        );

        // Scrolled back: the whole block is visible again, fully live.
        feed_pty(
            &t,
            b"\x1b[H\x1b[2Jalpha one\r\nbravo two\r\ncharlie three\r\ndelta four\r\necho five",
        );
        t.rebase_selection();
        let anchor = t.alt_sel.as_ref().expect("anchor survives");
        assert!(!anchor.dormant);
        assert_eq!(anchor.visible, None, "fully visible again: no clip");
        assert_eq!(t.selection_text(), "bravo two\ncharlie three\ndelta four");
    }

    #[test]
    fn a_single_row_selection_on_a_repeated_row_reanchors_to_its_own_copy() {
        // A one-row selection has a one-row fingerprint, and full-screen
        // apps repeat rows verbatim (divider rules, continuation markers).
        // After a repaint the nearest identical copy may be a DIFFERENT
        // copy: the neighbours captured with the anchor must break the tie
        // so the highlight follows its own row, not the closest lookalike.
        let (_tmp, mut t) = quiet_pty();
        feed_pty(
            &t,
            b"\x1b[?1049h\x1b[H\x1b[2Jalpha\r\n-----\r\nbravo\r\n-----\r\ncharlie",
        );
        // Select the SECOND divider (row 3), between bravo and charlie.
        t.set_selection(Some(Selection {
            anchor: (3, 0),
            head: (3, 4),
            block: false,
        }));
        assert_eq!(t.selection_text(), "-----");

        // The app scrolls two rows: the selected divider moves to row 1
        // (still between bravo and charlie), while a new divider appears
        // at row 4 — NEARER to the old position than the real one.
        feed_pty(
            &t,
            b"\x1b[H\x1b[2Jbravo\r\n-----\r\ncharlie\r\ndelta\r\n-----",
        );
        t.rebase_selection();
        let anchor = t.alt_sel.as_ref().expect("anchor survives");
        assert_eq!(
            anchor.top, 1,
            "the highlight must follow its own copy (neighbours bravo/charlie), not the nearest lookalike"
        );
        assert_eq!(
            t.selection.map(|s| (s.anchor, s.head)),
            Some(((1, 0), (1, 4))),
            "the selection coordinates must move with the content"
        );
        assert_eq!(t.selection_text(), "-----");
    }

    /// Drive a PtyTerminal's grid directly: parse `bytes` into its term as
    /// if the child had printed them. The child (`sleep`) stays silent, so
    /// the grid is exactly what the test painted.
    fn feed_pty(t: &PtyTerminal, bytes: &[u8]) {
        let mut p = Processor::<StdSyncHandler>::new();
        let mut term = t.term.lock();
        p.advance(&mut *term, bytes);
    }

    fn quiet_pty() -> (tempfile::TempDir, PtyTerminal) {
        let tmp = tempfile::tempdir().unwrap();
        let t = PtyTerminal::new_running("/bin/sleep", &[String::from("30")], tmp.path()).unwrap();
        (tmp, t)
    }

    /// A TAB leaves `'\t'` in the cell it started from (so copy can give
    /// the tab back). Painted raw, the host terminal jumped to its own tab
    /// stop while ratatui counted one cell, so the gap kept the previous
    /// frame's text and the rest of the row landed too far right (#1287).
    #[test]
    fn a_tab_paints_as_blank_cells_and_the_next_text_lands_on_the_tab_stop() {
        let (_tmp, mut t) = quiet_pty();
        let area = Rect::new(0, 0, 40, 12);
        let mut buf = Buffer::empty(area);
        (&mut t).render(area, &mut buf);
        t.feed_bytes_for_test(b"\x1b[2J\x1b[Ha\tb\r\n");
        for cell in buf.content.iter_mut() {
            cell.set_symbol("X");
        }
        (&mut t).render(area, &mut buf);
        let row: Vec<String> = (0..area.width)
            .map(|x| buf[(x, 1)].symbol().to_string())
            .collect();
        let a = row.iter().position(|c| c == "a").expect("a is painted");
        assert!(
            row.iter().all(|c| !c.chars().any(char::is_control)),
            "no control char reaches the host terminal: {row:?}"
        );
        assert_eq!(
            row[a + 1..a + 8].concat(),
            " ".repeat(7),
            "the tab's gap is blank, not the old frame: {row:?}"
        );
        assert_eq!(row[a + 8], "b", "b sits on the next tab stop: {row:?}");
    }

    /// The text views of the grid (find, `croft record` casts, the web
    /// client) send no raw TAB either, while copy still gives it back.
    #[test]
    fn grid_text_views_blank_a_tab_but_copy_keeps_it() {
        let (_tmp, mut t) = quiet_pty();
        t.resize(40, 10);
        t.feed_bytes_for_test(b"\x1b[2J\x1b[Ha\tb\r\n");
        let row = {
            let term = t.term.lock();
            row_text_and_cols(&term, 0).0
        };
        assert!(row.starts_with("a       b"), "{row:?}");
        let ansi = t.grid_lines_ansi();
        let first = ansi
            .iter()
            .find(|(plain, _)| plain.starts_with('a'))
            .unwrap();
        assert!(
            !first.0.contains('\t') && !first.1.contains('\t'),
            "{first:?}"
        );
        assert!(first.0.starts_with("a       b"), "{first:?}");

        let line = {
            let term = t.term.lock();
            (0..term.screen_lines() as i32)
                .find(|&l| row_text_and_cols(&term, l).0.starts_with('a'))
                .unwrap()
        };
        let mut sel = Selection::new(line, 0);
        sel.head = (line, 8);
        t.set_selection(Some(sel));
        assert!(
            t.selection_text().starts_with("a\t"),
            "copy keeps the tab: {:?}",
            t.selection_text()
        );
    }

    /// An alt-screen round trip (`git log`, vim, htop) used to wipe every
    /// arrival stamp (the alternate grid has no history, so the cursor's
    /// absolute id collapsed and looked like an ED 3 wipe) and then
    /// re-stamp the whole scrollback with the exit time. Stamps are keyed
    /// on the scroll clock now, which the alternate screen freezes.
    #[test]
    fn timestamps_survive_an_alt_screen_round_trip() {
        let (_tmp, t) = quiet_pty();
        let mut prev = 0i64;
        feed_pty(&t, b"one\r\ntwo\r\nthree\r\n");
        t.stamp_chunk_for_test(&mut prev, 1000);
        let before = t.line_time_entries_for_test();
        assert!(!before.is_empty(), "rows got stamped");
        let (first_id, first_ms) = before[0];
        assert_eq!(first_ms, 1000);
        feed_pty(&t, b"\x1b[?1049h\x1b[Hpager-screen");
        t.stamp_chunk_for_test(&mut prev, 2000);
        feed_pty(&t, b"\x1b[?1049l");
        t.stamp_chunk_for_test(&mut prev, 3000);
        let after = t.line_time_entries_for_test();
        assert_eq!(
            before.iter().map(|&(k, _)| k).collect::<Vec<_>>(),
            after.iter().map(|&(k, _)| k).collect::<Vec<_>>(),
            "an alt-screen trip must not wipe or invent stamped rows"
        );
        let kept = after.iter().find(|&&(k, _)| k == first_id).unwrap().1;
        assert_eq!(
            kept, 1000,
            "an old row must keep its true arrival time, not the pager's exit time"
        );
    }

    /// Once the scrollback ring saturates, `history_size` stops moving, so
    /// history-keyed row ids froze to screen positions: new rows overwrote
    /// the same ids and the gutter looked up unrelated rows' times. Clock
    /// ids keep advancing one per scrolled line forever.
    #[test]
    fn timestamps_keep_advancing_past_a_saturated_scrollback() {
        let (_tmp, t) = quiet_pty();
        let mut prev = 0i64;
        let mut chunk = String::new();
        for i in 0..5300 {
            chunk.push_str(&format!("s-{i}\r\n"));
        }
        feed_pty(&t, chunk.as_bytes());
        t.stamp_chunk_for_test(&mut prev, 1000);
        let max1 = t
            .line_time_entries_for_test()
            .last()
            .map(|&(k, _)| k)
            .unwrap();
        let mut more = String::new();
        for i in 0..100 {
            more.push_str(&format!("t-{i}\r\n"));
        }
        feed_pty(&t, more.as_bytes());
        t.stamp_chunk_for_test(&mut prev, 2000);
        let max2 = t
            .line_time_entries_for_test()
            .last()
            .map(|&(k, _)| k)
            .unwrap();
        assert!(
            max2 >= max1 + 100,
            "row ids must keep advancing after saturation (got {max1} then {max2})"
        );
    }

    /// An inline image captured after the scrollback saturated must ride
    /// the ring rotation like the content it anchors: `history_size` stops
    /// growing there, so a history-delta anchor freezes onto a viewport
    /// row and the picture sits on top of every later command's output.
    #[test]
    fn an_inline_image_rides_scrollback_past_saturation() {
        let (_tmp, t) = quiet_pty();
        let mut chunk = String::new();
        for i in 0..5200 {
            chunk.push_str(&format!("pre-{i}\r\n"));
        }
        feed_pty(&t, chunk.as_bytes());
        feed_pty(&t, b"image-anchor-row");
        t.push_image_for_test(vec![9, 9, 9]);
        feed_pty(&t, b"\r\n");
        let find_anchor = |t: &PtyTerminal| {
            let (lines, top) = t.grid_lines();
            top + lines
                .iter()
                .position(|l| l.starts_with("image-anchor-row"))
                .unwrap() as i32
        };
        assert_eq!(
            t.pane_images().pop().unwrap().line,
            find_anchor(&t),
            "the anchor starts on its row"
        );
        let mut more = String::new();
        for i in 0..60 {
            more.push_str(&format!("post-{i}\r\n"));
        }
        feed_pty(&t, more.as_bytes());
        assert_eq!(
            t.pane_images().pop().unwrap().line,
            find_anchor(&t),
            "the anchor must follow its content through ring rotation"
        );
    }

    /// Typing `clear` reaches the grid as ED 3 through the PTY reader
    /// thread (modern terminfo wipes scrollback), never through the pane's
    /// own Clear method: the reader must drop captured images too, or the
    /// picture floats over the fresh prompt.
    #[test]
    fn a_program_emitted_scrollback_wipe_drops_captured_images() {
        use base64::Engine;
        let mut png_buf = Vec::new();
        image::RgbaImage::from_pixel(1, 1, image::Rgba([0, 255, 0, 255]))
            .write_to(
                &mut std::io::Cursor::new(&mut png_buf),
                image::ImageFormat::Png,
            )
            .expect("encode test png");
        let b64 = base64::engine::general_purpose::STANDARD.encode(&png_buf);
        let tmp = tempfile::tempdir().unwrap();
        // Fill lines push real content into scrollback first (ED 3 can only
        // shrink a nonempty history); the wipe then waits on stdin so the
        // test can observe the capture before it lands.
        let script = format!(
            "i=0; while [ $i -lt 60 ]; do echo fill-$i; i=$((i+1)); done; printf '\\033]1337;File=inline=1:{b64}\\007\\n'; read x; printf '\\033[3J\\033[2J'; printf 'wiped\\n'; sleep 30"
        );
        let mut term =
            PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script], tmp.path()).unwrap();
        let mut waited = 0u32;
        while term.pane_images().is_empty() {
            assert!(waited < 8000, "inline image never captured");
            std::thread::sleep(std::time::Duration::from_millis(40));
            waited += 40;
        }
        term.write_input(b"\n");
        wait_for_grid(&term, |ls| ls.iter().any(|l| l.starts_with("wiped")));
        assert!(
            term.pane_images().is_empty(),
            "an ED 3 scrollback wipe from the program must drop the pane's images"
        );
    }

    /// A wipe with EMPTY scrollback (picture captured on the first screen,
    /// nothing scrolled into history yet) must drop the image too: the
    /// history-shrink heuristic saw 0 → 0 and kept the stale overlay.
    #[test]
    fn a_zero_history_screen_wipe_drops_captured_images() {
        use base64::Engine;
        let mut png_buf = Vec::new();
        image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255]))
            .write_to(
                &mut std::io::Cursor::new(&mut png_buf),
                image::ImageFormat::Png,
            )
            .expect("encode test png");
        let b64 = base64::engine::general_purpose::STANDARD.encode(&png_buf);
        let tmp = tempfile::tempdir().unwrap();
        let script = format!(
            "printf '\\033]1337;File=inline=1:{b64}\\007\\n'; read x; printf '\\033[2J\\033[3J\\033[H'; printf 'wiped\\n'; sleep 30"
        );
        let mut term =
            PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script], tmp.path()).unwrap();
        let mut waited = 0u32;
        while term.pane_images().is_empty() {
            assert!(waited < 8000, "inline image never captured");
            std::thread::sleep(std::time::Duration::from_millis(40));
            waited += 40;
        }
        term.write_input(b"\n");
        wait_for_grid(&term, |ls| ls.iter().any(|l| l.starts_with("wiped")));
        assert!(
            term.pane_images().is_empty(),
            "a screen wipe with empty history must still drop the pane's images"
        );
    }

    /// CAN/SUB cancel an incomplete CSI and an ESC inside one begins a new
    /// escape (VT100): the wipe sniffer's CSI walk must not swallow the
    /// sequence that follows a cancelled CSI, or a wipe (or alt entry)
    /// right after one goes unseen.
    #[test]
    fn a_cancelled_csi_does_not_hide_a_wipe_from_the_sniffer() {
        let mut w = WipeSniffer::default();
        // ESC inside an incomplete CSI: the ED 3 after it must be seen.
        let wipes = w.scan(b"\x1b[12\x1b[3J", false);
        assert!(
            wipes.iter().any(|w| w.hist),
            "ESC-in-CSI swallowed the scrollback wipe"
        );
        // CAN aborts; the alt entry after it must be seen, so the ED 2
        // inside the alt screen is correctly ignored.
        let mut w = WipeSniffer::default();
        let wipes = w.scan(b"\x1b[\x18\x1b[?1049h\x1b[2J", false);
        assert!(
            wipes.is_empty(),
            "CAN-cancelled CSI hid the alt entry from the sniffer"
        );
    }

    /// #876: each wipe is reported where it ends in the chunk, a sequence
    /// split across reads included, so the reader can stop the parser
    /// right there.
    #[test]
    fn the_wipe_sniffer_reports_where_each_wipe_ends() {
        let mut w = WipeSniffer::default();
        let wipes = w.scan(b"ab\x1b[2J\x1b[3", false);
        assert_eq!(
            wipes,
            vec![Wipe {
                end: 6,
                screen: true,
                hist: false
            }]
        );
        let wipes = w.scan(b"Jx\x1b", false);
        assert_eq!(
            wipes,
            vec![Wipe {
                end: 1,
                screen: false,
                hist: true
            }]
        );
        let wipes = w.scan(b"c", false);
        assert_eq!(
            wipes,
            vec![Wipe {
                end: 1,
                screen: true,
                hist: true
            }]
        );
    }

    /// `clear && vim`: the wipe and the alt-screen entry land in ONE PTY
    /// chunk. Judging the wipe by the chunk's FINAL mode attributed it to
    /// the alt screen and kept the invalidated primary images, which then
    /// reappeared over unrelated content when the app exited.
    #[test]
    fn a_wipe_followed_by_alt_entry_in_one_chunk_still_drops_images() {
        use base64::Engine;
        let mut png_buf = Vec::new();
        image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 255, 0, 255]))
            .write_to(
                &mut std::io::Cursor::new(&mut png_buf),
                image::ImageFormat::Png,
            )
            .expect("encode test png");
        let b64 = base64::engine::general_purpose::STANDARD.encode(&png_buf);
        let tmp = tempfile::tempdir().unwrap();
        // The wipe and the alt ENTRY share one write (one PTY chunk, the
        // pane still in the alt screen when it ends); the exit comes later.
        let script = format!(
            "printf '\\033]1337;File=inline=1:{b64}\\007\\n'; read x; printf '\\033[2J\\033[3J\\033[?1049halt-owns-this'; sleep 1; printf '\\033[?1049l'; printf 'back\\n'; sleep 30"
        );
        let mut term =
            PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script], tmp.path()).unwrap();
        let mut waited = 0u32;
        while term.pane_images().is_empty() {
            assert!(waited < 8000, "inline image never captured");
            std::thread::sleep(std::time::Duration::from_millis(40));
            waited += 40;
        }
        term.write_input(b"\n");
        wait_for_grid(&term, |ls| ls.iter().any(|l| l.starts_with("back")));
        assert!(
            term.pane_images().is_empty(),
            "the wipe preceded the alt entry, so the primary images are gone"
        );
    }

    /// Clearing the pane erases the content the OSC 133 marks anchored to:
    /// keeping them used to invert their drift math (history_size zeroed)
    /// so stale decoration dots later resurfaced on unrelated output rows,
    /// where clicking one copied or re-ran the wrong text.
    #[test]
    fn clearing_the_terminal_drops_its_marks() {
        use crate::shell_integration::OscEvent;
        let (_tmp, mut t) = quiet_pty();
        feed_pty(&t, b"\r\n$ ");
        t.push_mark_for_test(OscEvent::PromptStart, 0);
        t.push_mark_for_test(OscEvent::PromptEnd, 2);
        feed_pty(&t, b"cmd\r\nout\r\n");
        t.push_mark_for_test(OscEvent::CommandStart, 0);
        t.push_mark_for_test(OscEvent::CommandEnd(Some(0)), 0);
        assert_eq!(
            pair_decorations(&t.marks_snapshot()).len(),
            1,
            "staging: one finished command"
        );
        t.clear_screen_and_scrollback();
        assert!(
            pair_decorations(&t.marks_snapshot()).is_empty(),
            "cleared content keeps no command decorations"
        );
    }

    /// A decoration's id names the same command for as long as that command
    /// exists, and a positional index does not (#440).
    ///
    /// Asserted as a CONTRAST, because that is the actual claim: the same
    /// eviction is shown moving the index while leaving the id alone. An
    /// assertion that only checked "id 7 is still 7" would pass against a
    /// collector that renumbered from zero, since nothing would have moved.
    ///
    /// Driven through `pair_decorations` rather than a live pane: both
    /// eviction paths (the scrollback GC in `marks_snapshot`, the `MARKS_MAX`
    /// drain in the reader thread) end in the same observable state — a
    /// prefix of the mark stream is gone — and constructing that state
    /// directly tests the property at the level it actually holds, instead of
    /// depending on how a PTY happens to schedule its scrollback.
    #[test]
    fn a_decoration_id_outlives_the_eviction_that_moves_its_index() {
        use crate::shell_integration::OscEvent as E;
        let cycle = |line: i32| {
            [
                (E::PromptStart, line, 0, None),
                (E::PromptEnd, line, 2, None),
                (E::CommandStart, line + 1, 0, None),
                (E::CommandEnd(Some(0)), line + 2, 0, None),
            ]
        };
        let mut marks = Vec::new();
        for (n, line) in [-12, -8, -4].iter().enumerate() {
            marks.extend(cycle(*line));
            assert_eq!(marks.len(), (n + 1) * 4, "staging: four marks per cycle");
        }
        let views = views(&marks);

        let before = pair_decorations(&views);
        assert_eq!(before.len(), 3, "staging: three finished commands");
        assert!(
            before[0].id < before[1].id && before[1].id < before[2].id,
            "ids ascend with command order: {:?}",
            before.iter().map(|d| d.id).collect::<Vec<_>>()
        );

        // Evict the oldest command: its four marks leave the front of the
        // stream, exactly as the scrollback GC and the MARKS_MAX drain both
        // leave it. Ids are NOT reassigned, because they belong to the marks.
        let after = pair_decorations(&views[4..]);
        assert_eq!(after.len(), 2, "staging: one command was evicted");

        // The index has moved. The command that was last is still last here,
        // so the telling case is the MIDDLE one: it was at index 1 and is now
        // at index 0, which is what silently hands a caller the wrong command.
        assert_eq!(
            before[1].id, after[0].id,
            "the survivor moved down one slot"
        );
        assert_ne!(
            before[1].id, before[0].id,
            "staging: the slots must hold different commands"
        );
        assert_ne!(
            after[0].id,
            before.first().map(|d| d.id).unwrap(),
            "index 0 now names a different command than it did"
        );

        // The id still names the SAME command: same span, same exit.
        let found = after
            .iter()
            .find(|d| d.id == before[2].id)
            .expect("a surviving command keeps its id");
        assert_eq!(
            (found.exit, found.output_start, found.output_end),
            (before[2].exit, before[2].output_start, before[2].output_end),
            "the id must name the same command, not merely some decoration"
        );

        // And an evicted id reads as gone rather than as its neighbour, which
        // is the whole difference from a positional index.
        assert!(
            after.iter().all(|d| d.id != before[0].id),
            "an evicted command's id must never be reused by a survivor"
        );
    }

    /// A command outlives its own prompt marks, and the id says so (#440).
    ///
    /// The GC retains per MARK, not per command, and the prompt marks sit on
    /// earlier rows than the command's own — so the floor takes them first.
    /// The interesting case is therefore not the clean boundary the test
    /// above cuts, but this one: the same command, still identified, with its
    /// presentation fields degraded. Pinning it here so the limit documented
    /// on `CommandDecoration::id` cannot quietly stop being true.
    #[test]
    fn a_command_can_outlive_its_prompt_marks() {
        use crate::shell_integration::OscEvent as E;
        let marks = [
            (E::PromptStart, -10, 0, None),
            (E::PromptEnd, -10, 5, None),
            (E::CommandStart, -9, 0, None),
            (E::CommandEnd(Some(0)), -7, 0, None),
        ];
        let views = views(&marks);
        let whole = pair_decorations(&views);
        assert_eq!(whole.len(), 1, "staging: one finished command");

        // The floor rises past the prompt row but not past the command's.
        let survivors: Vec<MarkView> = views.iter().filter(|m| m.line >= -9).cloned().collect();
        assert_eq!(survivors.len(), 2, "staging: only the prompt marks evict");
        let after = pair_decorations(&survivors);
        assert_eq!(after.len(), 1, "the command itself survives");

        // Identity and the output span are untouched.
        assert_eq!(after[0].id, whole[0].id, "the id names the same command");
        assert_eq!(
            (after[0].exit, after[0].output_start, after[0].output_end),
            (whole[0].exit, whole[0].output_start, whole[0].output_end),
            "the fields taken from CommandStart/CommandEnd do not drift"
        );

        // The presentation fields DO degrade, exactly as documented.
        assert_eq!(
            whole[0].input,
            Some((-10, 5)),
            "staging: the typed-text position existed before the eviction"
        );
        assert_eq!(
            after[0].input, None,
            "the typed-text position goes with the prompt mark"
        );
        assert_eq!(whole[0].line, -10, "staging: the row was the prompt's");
        assert_eq!(
            after[0].line, after[0].output_start,
            "the row falls back to the command's own line"
        );
    }

    /// Ids are unique across panes, and a wipe does not restart them (#440).
    ///
    /// The counter is process-wide precisely so an id means one thing
    /// wherever it travels; a per-pane counter would hand two panes the same
    /// id and a wipe would hand the same pane its old ids back. Both are the
    /// kind of thing that looks fine until a consumer keys on the id, so both
    /// are pinned rather than left to the comment.
    #[test]
    fn ids_are_unique_across_panes_and_survive_a_wipe() {
        use crate::shell_integration::OscEvent;
        let run = |t: &PtyTerminal| {
            feed_pty(t, b"\r\n$ ");
            t.push_mark_for_test(OscEvent::PromptStart, 0);
            t.push_mark_for_test(OscEvent::PromptEnd, 2);
            feed_pty(t, b"cmd\r\nout\r\n");
            t.push_mark_for_test(OscEvent::CommandStart, 0);
            t.push_mark_for_test(OscEvent::CommandEnd(Some(0)), 0);
        };

        let (_a, mut a) = quiet_pty();
        let (_b, b) = quiet_pty();
        run(&a);
        run(&b);
        run(&a);
        let mut ids: Vec<u64> = a
            .command_decorations()
            .iter()
            .chain(b.command_decorations().iter())
            .map(|d| d.id)
            .collect();
        assert_eq!(ids.len(), 3, "staging: three commands across two panes");
        let before = ids.len();
        ids.sort_unstable();
        ids.dedup();
        assert_eq!(ids.len(), before, "ids must not collide between panes");

        // A wipe clears the pane's marks; the counter is not reset, so the
        // next command must not be handed an id the wipe just freed.
        let highest = *ids.last().unwrap();
        a.clear_screen_and_scrollback();
        assert!(
            a.command_decorations().is_empty(),
            "staging: the wipe must actually clear the marks"
        );
        run(&a);
        let after = a.command_decorations();
        assert_eq!(after.len(), 1, "staging: one command since the wipe");
        assert!(
            after[0].id > highest,
            "an id must not be reused after a wipe: {} came after {highest}",
            after[0].id
        );
    }

    /// A prompt mark recorded after the scrollback saturated must ride the
    /// ring rotation like its content: under the history-size model the
    /// delta froze, so the mark (and its decoration dot) drifted off its
    /// row as output streamed.
    #[test]
    fn a_prompt_mark_rides_scrollback_past_saturation() {
        use crate::shell_integration::OscEvent;
        let (_tmp, mut t) = quiet_pty();
        let mut chunk = String::new();
        for i in 0..5200 {
            chunk.push_str(&format!("pre-{i}\r\n"));
        }
        feed_pty(&t, chunk.as_bytes());
        feed_pty(&t, b"$ marker-prompt");
        t.push_mark_for_test(OscEvent::PromptStart, 0);
        feed_pty(&t, b"\r\n");
        let find = |t: &mut PtyTerminal| {
            let (lines, top) = t.grid_lines();
            top + lines
                .iter()
                .position(|l| l.starts_with("$ marker-prompt"))
                .unwrap() as i32
        };
        assert_eq!(
            t.marks_snapshot()[0].line,
            find(&mut t),
            "the mark starts on its prompt row"
        );
        let mut more = String::new();
        for i in 0..60 {
            more.push_str(&format!("post-{i}\r\n"));
        }
        feed_pty(&t, more.as_bytes());
        assert_eq!(
            t.marks_snapshot()[0].line,
            find(&mut t),
            "the mark must follow its prompt through ring rotation"
        );
    }

    /// The pane's Clear wipes screen AND scrollback: the content an inline
    /// image anchored to is gone, so the picture must go with it instead of
    /// floating over the fresh prompt at a now-meaningless row.
    #[test]
    fn clearing_the_terminal_drops_its_captured_images() {
        let (_tmp, mut t) = quiet_pty();
        feed_pty(&t, b"\r\nsome output");
        t.push_image_for_test(vec![1, 2, 3]);
        feed_pty(&t, b"\r\n");
        assert_eq!(t.pane_images().len(), 1);
        t.clear_screen_and_scrollback();
        assert!(
            t.pane_images().is_empty(),
            "a cleared pane keeps no image anchored to erased content"
        );
    }

    /// A captured line wider than the pane appears in the grid as a WRAPPED
    /// first row (a prefix of the needle): the jump must find it, must not
    /// be fooled by an unrelated short row sharing the prefix (only rows
    /// that really soft-wrap qualify for the reverse arm), and must skip
    /// continuation rows so the newest-first scan can't land mid-line.
    #[test]
    fn capture_jump_matches_wrapped_lines_without_false_prefixes() {
        let (_tmp, mut t) = quiet_pty();
        let area = Rect::new(0, 0, 40, 12);
        let mut buf = Buffer::empty(area);
        (&mut t).render(area, &mut buf);
        let needle: String = format!("error[E0308]: {}", "x".repeat(60))
            .chars()
            .take(60)
            .collect();
        // An unrelated NON-wrapped row that happens to share the prefix.
        feed_pty(&t, b"\r\nerror[E0308]: unrelated short\r\n");
        assert_eq!(
            t.find_captured_line(&needle),
            None,
            "a short non-wrapped lookalike must not match"
        );
        // The real captured line, wrapping across two grid rows.
        let full = format!("error[E0308]: {}", "x".repeat(60));
        feed_pty(&t, full.as_bytes());
        let start = {
            let term = t.term.lock();
            term.grid().cursor.point.line.0 - 1
        };
        assert_eq!(
            t.find_captured_line(&needle),
            Some(start),
            "the wrapped line's FIRST row is the jump target, not its continuation"
        );
    }

    /// A soft-wrapped logical line copies as ONE line: the WRAPLINE flag on
    /// the wrapping row's last cell tells a continuation from a real row
    /// break, so selection copy, the durable command history, and the
    /// sticky header all see the text the user actually typed. A '\n' at
    /// the wrap corrupted stored commands and re-ran only the first
    /// fragment on paste. Hard breaks keep their newline.
    #[test]
    fn selection_over_a_soft_wrapped_line_copies_one_logical_line() {
        let (_tmp, mut t) = quiet_pty();
        let area = Rect::new(0, 0, 40, 10);
        let mut buf = Buffer::empty(area);
        (&mut t).render(area, &mut buf);
        let cols = t.term.lock().columns();
        // A fresh row below any spawn banner, then a line long enough to wrap.
        feed_pty(&t, b"\r\n");
        let start = t.term.lock().grid().cursor.point.line.0;
        let long: String = "abcdefghij".repeat(6); // 60 chars > pane width
        feed_pty(&t, long.as_bytes());
        t.set_selection(Some(Selection {
            anchor: (start, 0),
            head: (start + 1, cols.saturating_sub(1) as u16),
            block: false,
        }));
        assert_eq!(
            t.selection_text(),
            long,
            "the wrapped rows must rejoin without a newline"
        );
        // A hard row break keeps its newline.
        feed_pty(&t, b"\r\nsecond");
        t.set_selection(Some(Selection {
            anchor: (start + 1, 0),
            head: (start + 2, 6),
            block: false,
        }));
        assert!(
            t.selection_text().contains('\n'),
            "a real row break still copies as two lines: {:?}",
            t.selection_text()
        );
    }

    /// The annotate prompt's existing-note lookup compares the selection
    /// line captured at snapshot time against annotation lines; both must
    /// translate at the SAME clock reading, or output scrolling between the
    /// capture and the lookup shifts the annotations away from the fixed
    /// selection line and the same span duplicates instead of editing.
    #[test]
    fn annotation_lookup_translates_at_the_callers_clock() {
        let (_tmp, mut t) = quiet_pty();
        feed_pty(&t, b"existing span\r\n");
        let clock = t.scroll_clock();
        t.add_annotation(0, clock, 0, 13, String::from("existing note"));
        // The prompt captures selection + clock in one snapshot...
        let (_, snap_clock) = t.selection_and_clock();
        // ...then 30 rows land before the existing-note lookup runs.
        let mut fill = String::new();
        for i in 0..30 {
            fill.push_str(&format!("late-{i}\r\n"));
        }
        feed_pty(&t, fill.as_bytes());
        let cur = t.annotations_at_clock(snap_clock);
        assert_eq!(
            cur[0].0, 0,
            "translated at the captured clock, the note still names the captured line"
        );
    }

    /// Annotations name PRIMARY-screen rows; while vim/htop own the
    /// viewport the same line numbers describe unrelated alternate-grid
    /// content, so neither the amber paint nor click hit-testing may
    /// resolve there — and both come back when the app exits.
    #[test]
    fn annotations_hide_while_an_alt_screen_app_owns_the_viewport() {
        let (_tmp, mut t) = quiet_pty();
        t.last_inner = Rect {
            x: 0,
            y: 0,
            width: 80,
            height: 24,
        };
        feed_pty(&t, b"annotated content row\r\n");
        let clock = t.scroll_clock();
        t.add_annotation(0, clock, 0, 15, String::from("note"));
        assert!(
            t.annotation_at(3, 0).is_some(),
            "the note resolves on the primary screen"
        );
        feed_pty(&t, b"\x1b[?1049h\x1b[Hvim-owns-this-screen");
        assert!(
            t.annotation_at(3, 0).is_none(),
            "no hit while the alternate screen is up"
        );
        feed_pty(&t, b"\x1b[?1049l");
        assert!(
            t.annotation_at(3, 0).is_some(),
            "back on the primary screen the note resolves again"
        );
    }

    /// The Annotate prompt captures its span when it OPENS; rows that
    /// stream while the user types the note must not shift the pin. The
    /// commit anchors with the open-time (line, clock) pair — sampling a
    /// fresh baseline at commit pinned the note N rows below its text
    /// after N rows of output.
    #[test]
    fn an_annotation_committed_after_output_streamed_pins_where_it_was_captured() {
        let (_tmp, mut t) = quiet_pty();
        feed_pty(&t, b"target-line alpha\r\n");
        let (lines, top) = t.grid_lines();
        let line = top
            + lines
                .iter()
                .position(|l| l.starts_with("target-line"))
                .unwrap() as i32;
        let clock = t.scroll_clock();
        // 40 rows stream while the note is being typed.
        let mut more = String::new();
        for i in 0..40 {
            more.push_str(&format!("while-typing-{i}\r\n"));
        }
        feed_pty(&t, more.as_bytes());
        t.add_annotation(line, clock, 0, 11, String::from("note"));
        let cur = t.annotations_current();
        assert_eq!(cur.len(), 1, "the annotation survives");
        let term = t.term.lock();
        let text = extract_selection_text(&term, cur[0].0, 0, cur[0].0, 20);
        assert!(
            text.starts_with("target-line alpha"),
            "the note must pin to the text selected at open, got row: {text:?}"
        );
    }

    /// Past `SCROLLBACK_LINES` the ring rotates while `history_size` stops
    /// moving, so a history-growth anchor freezes to a screen position.
    /// Annotations ride the scroll clock (like selections) and must keep
    /// following their content in exactly the long-lived panes (Claude
    /// Code, `tail -f`) the feature targets.
    #[test]
    fn an_annotation_survives_streaming_past_a_saturated_scrollback() {
        let (_tmp, mut t) = quiet_pty();
        let mut chunk = String::new();
        for i in 0..5200 {
            chunk.push_str(&format!("pre-{i}\r\n"));
        }
        feed_pty(&t, chunk.as_bytes());
        feed_pty(&t, b"note-worthy-marker here\r\n");
        let (lines, top) = t.grid_lines();
        let line = top
            + lines
                .iter()
                .position(|l| l.starts_with("note-worthy-marker"))
                .unwrap() as i32;
        let clock = t.scroll_clock();
        t.add_annotation(line, clock, 0, 18, String::from("pinned"));
        let mut more = String::new();
        for i in 0..60 {
            more.push_str(&format!("post-{i}\r\n"));
        }
        feed_pty(&t, more.as_bytes());
        let cur = t.annotations_current();
        assert_eq!(cur.len(), 1, "the annotation survives the rotation");
        let term = t.term.lock();
        let text = extract_selection_text(&term, cur[0].0, 0, cur[0].0, 25);
        assert!(
            text.starts_with("note-worthy-marker"),
            "the note must follow its content through ring rotation, got row: {text:?}"
        );
    }

    /// A command spanning several grid rows (a quoted/heredoc newline, or a
    /// soft wrap shown in a later-widened pane) joins its rows with '\n' in
    /// `extract_selection_text`; the sticky header used to print that byte
    /// into a cell verbatim, corrupting the frame on the host terminal (the
    /// screen-corruption class the pdftoppm/DAP capture fixes exist to stop).
    #[test]
    fn sticky_header_never_paints_a_control_char_for_a_multi_row_command() {
        use crate::shell_integration::OscEvent;
        let (_tmp, mut t) = quiet_pty();
        // First render sizes the grid to the pane (78 cols), so the long
        // command genuinely wraps.
        let area = Rect::new(0, 0, 80, 20);
        let mut buf = Buffer::empty(area);
        (&mut t).render(area, &mut buf);
        feed_pty(&t, b"$ ");
        t.push_mark_for_test(OscEvent::PromptEnd, 2);
        // A multi-line typed command (heredoc / quoted newline): the input
        // span covers two HARD rows, so the joined text carries a newline
        // well inside the label's painted width.
        feed_pty(&t, b"echo \"build-it-99\r\nsecond-line\"");
        feed_pty(&t, b"\r\n");
        t.push_mark_for_test(OscEvent::CommandStart, 0);
        for i in 0..40 {
            feed_pty(&t, format!("out-{i}\r\n").as_bytes());
        }
        t.push_mark_for_test(OscEvent::CommandEnd(Some(0)), 0);
        assert!(
            !t.command_decorations().is_empty(),
            "the marks must pair into a decoration"
        );
        t.scroll_to_top();
        for _ in 0..5 {
            t.scroll_down(1);
        }
        let mut buf = Buffer::empty(area);
        (&mut t).render(area, &mut buf);
        let inner = t.last_inner;
        let top: String = (inner.x..inner.x + inner.width)
            .map(|x| buf[(x, inner.y)].symbol().chars().next().unwrap_or(' '))
            .collect();
        assert!(
            top.contains("build-it-99"),
            "the wrapped command must still pin: {top:?}"
        );
        for y in 0..area.height {
            for x in 0..area.width {
                let sym = buf[(x, y)].symbol();
                assert!(
                    !sym.chars().any(|c| c.is_control()),
                    "cell ({x},{y}) holds a control char: {sym:?}"
                );
            }
        }
    }

    /// A prompt row rewritten SHORTER than the recorded 133;B column (a
    /// backgrounded `\r\x1b[K` progress writer, or a pane shrunk under the
    /// prompt) used to panic click-to-move: the clamp bounds inverted
    /// (`min > max`) and `u16::clamp` asserts. A click is never allowed to
    /// take the app down; the degraded gesture just clamps sanely.
    #[test]
    fn a_prompt_click_after_the_row_was_rewritten_shorter_does_not_panic() {
        let (_tmp, mut t) = quiet_pty();
        t.last_inner = Rect {
            x: 0,
            y: 0,
            width: 80,
            height: 24,
        };
        feed_pty(&t, b"user@host ~/Documents/croft % ");
        t.push_mark_for_test(crate::shell_integration::OscEvent::PromptEnd, 30);
        // The rewrite leaves 7 columns of text and the cursor at column 7,
        // both left of the recorded prompt-end column 30.
        feed_pty(&t, b"\r\x1b[Kworking");
        let row = t.term.lock().grid().cursor.point.line.0 as u16;
        // Live bounds: the text ends at column 7 and the cursor sits at
        // column 7, both left of the recorded 133;B column 30. The click at
        // column 5 clamps into [30.min(7), 7] = 7, which equals the cursor,
        // so the gesture degrades to no motion instead of panicking.
        assert_eq!(
            t.prompt_click_arrows(5, row),
            None,
            "a click on a shortened prompt row must degrade, not panic"
        );
    }

    #[test]
    fn alt_screen_selection_follows_content_across_repaints() {
        // Alt-screen apps (Claude Code) never scroll the grid — they
        // repaint it in place. The selection must re-find its text after
        // each repaint, hide while it is scrolled out of the app's view,
        // and come back when the content does.
        let (_tmp, mut t) = quiet_pty();
        feed_pty(
            &t,
            b"\x1b[?1049h\x1b[H\x1b[2Jalpha one\r\nbravo two\r\ncharlie three\r\ndelta four",
        );
        t.set_selection(Some(Selection {
            anchor: (1, 0),
            head: (1, 8),
            block: false,
        }));
        assert_eq!(t.selection_text(), "bravo two");

        // The app scrolls its transcript up one line and repaints.
        feed_pty(
            &t,
            b"\x1b[H\x1b[2Jbravo two\r\ncharlie three\r\ndelta four\r\necho five",
        );
        t.rebase_selection();
        assert_eq!(t.selection_text(), "bravo two");
        assert_eq!(
            t.selection().unwrap().anchor.0,
            0,
            "the highlight must move to where the app repainted its text"
        );

        // The selected content scrolls out of the app's view entirely:
        // highlight goes dormant but copy still yields the remembered text.
        feed_pty(
            &t,
            b"\x1b[H\x1b[2Jfoxtrot six\r\ngolf seven\r\nhotel eight\r\nindia nine",
        );
        t.rebase_selection();
        assert!(
            t.alt_sel.as_ref().is_some_and(|a| a.dormant),
            "no matching content anywhere in the grid: dormant"
        );
        assert_eq!(t.selection_text(), "bravo two");

        // The app scrolls the content back into view at a new position.
        feed_pty(
            &t,
            b"\x1b[H\x1b[2Jalpha one\r\nbravo two\r\ncharlie three\r\ndelta four",
        );
        t.rebase_selection();
        assert!(t.alt_sel.as_ref().is_some_and(|a| !a.dormant));
        assert_eq!(t.selection().unwrap().anchor.0, 1);
        assert_eq!(t.selection_text(), "bravo two");
    }

    #[test]
    fn alt_screen_row_half_covered_by_a_floating_pill_keeps_its_surviving_prefix() {
        // Claude Code floats a "Jump to bottom" pill ON TOP of a content
        // row. That row's text no longer equals the remembered row, but
        // its left part is untouched — it must keep a highlight clipped to
        // the surviving columns instead of dropping out entirely.
        let (_tmp, mut t) = quiet_pty();
        feed_pty(
            &t,
            b"\x1b[?1049h\x1b[H\x1b[2Jalpha one\r\nbravo two words here\r\ncharlie three words here\r\ndelta four words here\r\necho five",
        );
        t.set_selection(Some(Selection {
            anchor: (1, 0),
            head: (3, 20),
            block: false,
        }));
        // The app repaints the same content but overlays a pill over the
        // right half of the block's middle row.
        feed_pty(
            &t,
            b"\x1b[H\x1b[2Jalpha one\r\nbravo two words here\r\ncharlie three[ PILL ]here\r\ndelta four words here\r\necho five",
        );
        t.rebase_selection();
        let anchor = t.alt_sel.as_ref().expect("anchor survives");
        assert!(!anchor.dormant);
        let clips = anchor.visible.as_ref().expect("partially covered");
        assert!(
            clips.contains(&(1, 0, u16::MAX)) && clips.contains(&(3, 0, u16::MAX)),
            "intact rows keep their full highlight: {clips:?}"
        );
        assert!(
            clips
                .iter()
                .any(|&(l, lo, hi)| l == 2 && lo == 0 && (12..14).contains(&hi)),
            "the covered row keeps its surviving prefix ('charlie three'): {clips:?}"
        );
        assert!(
            clips
                .iter()
                .any(|&(l, lo, hi)| l == 2 && lo == 21 && hi == 24),
            "the surviving suffix ('here') stays lit too, even under half the row: {clips:?}"
        );
    }

    #[test]
    fn alt_screen_bottom_up_drag_from_a_blank_row_selects_and_survives_release() {
        // Bottom-up selections usually start on a blank row or an animated
        // status row: the anchor captured at mouse-down mismatches on the
        // next frame, and before drag-awareness that turned the whole drag
        // dormant (invisible). While the button is held the selection must
        // follow the pointer over whatever is on screen; release captures
        // the definitive anchor.
        let (_tmp, mut t) = quiet_pty();
        feed_pty(
            &t,
            b"\x1b[?1049h\x1b[H\x1b[2Jalpha one\r\nbravo two\r\ncharlie three\r\n\r\ntokens 42",
        );
        t.last_inner = Rect::new(0, 0, 40, 10);
        // Mouse-down on the blank row (row 3), then an app repaint changes
        // the animated status row so the blank-row anchor can't match as a
        // block, then drag upward.
        t.start_selection_at(5, 3);
        feed_pty(&t, b"\x1b[5;1Htokens 43\x1b[K");
        t.extend_selection_to(0, 1);
        let anchor = t.alt_sel.as_ref().expect("anchor present");
        assert!(
            !anchor.dormant,
            "a held drag never hides itself, whatever the anchor matched"
        );
        assert_eq!(t.selection_text(), "bravo two\ncharlie three\n");
        t.end_drag();
        // After release the anchor is definitive: the app scrolls its
        // content down one row and the highlight follows.
        feed_pty(
            &t,
            b"\x1b[H\x1b[2Jnew line\r\nalpha one\r\nbravo two\r\ncharlie three\r\n\r\ntokens 44",
        );
        t.rebase_selection();
        assert_eq!(t.selection().expect("survives").normalised().0, 2);
        assert_eq!(t.selection_text(), "bravo two\ncharlie three\n");
    }

    #[test]
    fn alt_screen_edge_autoscroll_forwards_wheel_to_the_tracking_app() {
        // On the alternate screen a drag held past the pane edge cannot
        // scroll croft scrollback (there is none); a mouse-tracking app
        // gets a wheel report at the edge cell so IT scrolls, and the
        // selection head re-pins to the edge row.
        let tmp = tempfile::tempdir().unwrap();
        // `cat -v` echoes whatever the pty receives back as printable
        // text, so the wheel report's arrival is observable in the grid.
        let mut t =
            PtyTerminal::new_running("/bin/cat", &[String::from("-v")], tmp.path()).unwrap();
        feed_pty(&t, b"\x1b[?1049h\x1b[?1002h\x1b[?1006h\x1b[H\x1b[2J");
        t.last_inner = Rect::new(0, 0, 40, 10);
        t.set_selection(Some(Selection {
            anchor: (2, 0),
            head: (2, 5),
            block: false,
        }));
        t.autoscroll_select(1, 5);
        assert_eq!(
            t.selection().unwrap().head.0,
            9,
            "the head re-pins to the bottom edge row"
        );
        let mut waited = 0u32;
        // SGR wheel-down at 1-based cell (6, 10): `ESC[<65;6;10M`.
        while !t.grid_lines().0.iter().any(|l| l.contains("[<65;6;10M")) {
            assert!(waited < 8000, "the app never received the wheel report");
            std::thread::sleep(std::time::Duration::from_millis(20));
            waited += 20;
        }
    }

    #[test]
    fn primary_selection_survives_alt_round_trip_but_alt_selection_dies_on_exit() {
        let (_tmp, mut t) = quiet_pty();
        feed_pty(&t, b"hello world\r\n");
        // The `▶ /bin/sleep 30` run-label header owns the top row(s), so
        // find where the fed line actually landed.
        let (lines, top) = t.grid_lines();
        let line = top
            + lines
                .iter()
                .position(|l| l.starts_with("hello"))
                .expect("fed line present") as i32;
        t.set_selection(Some(Selection {
            anchor: (line, 0),
            head: (line, 4),
            block: false,
        }));
        assert_eq!(t.selection_text(), "hello");
        // vim-style round trip: enter and leave the alternate screen.
        feed_pty(&t, b"\x1b[?1049h\x1b[H\x1b[2Jvim vim vim");
        t.rebase_selection();
        feed_pty(&t, b"\x1b[?1049l");
        t.rebase_selection();
        assert_eq!(
            t.selection_text(),
            "hello",
            "a primary-screen selection is frozen across an alt-screen trip"
        );
        // A selection made ON the alt screen names alternate-grid content;
        // leaving the alt screen destroys that content and the selection.
        feed_pty(&t, b"\x1b[?1049h\x1b[H\x1b[2Jquick brown fox");
        t.set_selection(Some(Selection {
            anchor: (0, 0),
            head: (0, 4),
            block: false,
        }));
        assert_eq!(t.selection_text(), "quick");
        feed_pty(&t, b"\x1b[?1049l");
        t.rebase_selection();
        assert!(
            t.selection().is_none(),
            "an alt-screen selection dies with the alternate grid"
        );
    }

    #[test]
    fn selection_spanning_scrollback_into_live_extracts_every_line() {
        let mut t = fresh_term(20, 3);
        feed(&mut t, b"AAAA\r\nBBBB\r\nCCCC\r\nDDDD\r\nEEEE\r\nFFFF");
        // Select from the oldest scrollback line (AAAA = Line(-3)) all
        // the way to the last live line (FFFF = Line(2)).
        let all = extract_selection_text(&t, -3, 0, 2, 19);
        assert_eq!(all, "AAAA\nBBBB\nCCCC\nDDDD\nEEEE\nFFFF");
    }

    #[test]
    fn process_name_resolves_a_live_pid() {
        let me = std::process::id() as i32;
        let name = process_name(me);
        assert!(
            name.as_deref().is_some_and(|n| !n.is_empty()),
            "the test process resolves to a non-empty name: {name:?}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn process_cmdline_reads_a_live_process_argv() {
        // #1846: the plain refresh never read the command line, so this was
        // always `None` and no pane running `ssh box` read as an ssh session.
        let mut child = std::process::Command::new("sleep")
            .arg("30")
            .spawn()
            .expect("sleep runs");
        // `spawn` can return while the child still reads as the test binary
        // that forked it, before its exec lands; a loaded runner caught that.
        // Read until the argv is sleep's: a process_cmdline that never reads
        // the command line still fails here, when the budget runs out.
        let mut argv = None;
        crate::test_budget::await_spawned(
            std::time::Duration::from_millis(200),
            "the child's argv to read as sleep's",
            || {
                argv = process_cmdline(child.id() as i32);
                argv.as_ref()
                    .is_some_and(|a| a.last().map(String::as_str) == Some("30"))
            },
        );
        let _ = child.kill();
        let _ = child.wait();
        let argv = argv.expect("a live child's argv");
        assert!(argv[0].ends_with("sleep"), "{argv:?}");
        assert_eq!(argv.last().map(String::as_str), Some("30"), "{argv:?}");
    }

    #[test]
    fn pick_pane_label_prefers_a_manual_name() {
        assert_eq!(pick_pane_label(Some("server"), "zsh"), "server");
        assert_eq!(pick_pane_label(None, "vim"), "vim");
        assert_eq!(pick_pane_label(None, ""), "");
    }

    #[test]
    fn parse_shells_skips_comments_and_dedupes_by_basename() {
        let s = "# /etc/shells\n/bin/zsh\n/bin/bash\n/usr/local/bin/bash\n\nnot-a-path\n/usr/bin/fish\n";
        let p = parse_shells(s);
        let bases: Vec<&str> = p.iter().map(|(_, b)| b.as_str()).collect();
        assert_eq!(
            bases,
            vec!["zsh", "bash", "fish"],
            "comments/blanks/non-paths skipped, basenames deduped"
        );
        assert_eq!(p[0].0, "/bin/zsh", "full path retained");
    }
    #[test]
    fn finished_command_carries_its_output_block() {
        let tmp = tempfile::tempdir().unwrap();
        let script = "printf '\\033]133;A\\007$ \\033]133;B\\007make\\n\\033]133;C\\007'; printf 'main.c:7:3: error: boom\\nsecond line\\n'; printf '\\033]133;D;1\\007'";
        let term =
            PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
                .unwrap();
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
        let mut finished = Vec::new();
        while std::time::Instant::now() < deadline {
            finished.extend(term.drain_finished_commands());
            if !finished.is_empty() {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(40));
        }
        let f = finished
            .first()
            .expect("the 133;D must yield a FinishedCommand");
        assert!(
            f.output.contains("main.c:7:3: error: boom") && f.output.contains("second line"),
            "the output block must ride the completion; got {:?}",
            f.output
        );
    }

    /// Run `script` under `/bin/sh` in a pane and return the first `n`
    /// commands its marks finish.
    fn finished_commands(script: &str, n: usize) -> Vec<FinishedCommand> {
        let tmp = tempfile::tempdir().unwrap();
        let term =
            PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
                .unwrap();
        let mut finished = Vec::new();
        crate::test_budget::await_spawned(
            std::time::Duration::from_millis(1500),
            "the script's 133;D marks",
            || {
                finished.extend(term.drain_finished_commands());
                finished.len() >= n
            },
        );
        finished
    }

    /// #876: `clear` erases the rows the typed command and its output were
    /// read back from at `133;D`, so the history, the build matchers and
    /// the run notices all got an empty command. A full reset (`reset`,
    /// RIS) erases them in place, without scrolling, so the output start
    /// has to move to the top of the screen.
    #[test]
    fn a_command_that_clears_the_screen_keeps_its_text_and_output() {
        let script = "printf '\\033]133;A\\007$ \\033]133;B\\007clear; echo hi\\n\\033]133;C\\007\\033[H\\033[2J\\033[3Jhi\\n\\033]133;D;0\\007\\033]133;A\\007$ \\033]133;B\\007echo bye; clear\\n\\033]133;C\\007bye\\n\\033[H\\033[2J\\033[3J\\033]133;D;0\\007\\033]133;A\\007$ \\033]133;B\\007reset; echo again\\n\\033]133;C\\007\\033cagain\\n\\033]133;D;0\\007'";
        let f = finished_commands(script, 3);
        assert_eq!(f[0].cmd, "clear; echo hi");
        assert_eq!(f[0].output, "hi");
        assert_eq!(f[1].cmd, "echo bye; clear");
        assert_eq!(f[1].output, "", "the clear erased the output");
        assert_eq!(f[2].cmd, "reset; echo again");
        assert_eq!(f[2].output, "again");
    }

    /// #876: a clear in its own read, after an earlier command whose marks
    /// survive in the scrollback (ED 2 alone pushes the screen there), must
    /// not hand the earlier command's text or output to this one.
    #[test]
    fn a_clear_in_its_own_read_does_not_pick_up_the_previous_command() {
        let script = "printf '\\033]133;A\\007$ \\033]133;B\\007echo one\\n\\033]133;C\\007one\\n\\033]133;D;0\\007\\033]133;A\\007$ \\033]133;B\\007clear; echo two\\n\\033]133;C\\007'; sleep 0.3; printf '\\033[H\\033[2J'; sleep 0.3; printf 'two\\n\\033]133;D;0\\007'";
        let f = finished_commands(script, 2);
        assert_eq!(
            (f[0].cmd.as_str(), f[0].output.as_str()),
            ("echo one", "one")
        );
        assert_eq!(
            (f[1].cmd.as_str(), f[1].output.as_str()),
            ("clear; echo two", "two")
        );
    }

    /// #876: output that scrolls past the screen right after a clear, in
    /// the same read, is captured from its first line.
    #[test]
    fn output_scrolling_after_a_clear_is_captured_whole() {
        let script = "printf '\\033]133;A\\007$ \\033]133;B\\007clear; seq 60\\n\\033]133;C\\007\\033[H\\033[2J\\033[3J%s\\n\\033]133;D;0\\007' \"$(seq 60)\"";
        let f = finished_commands(script, 1);
        assert_eq!(f[0].cmd, "clear; seq 60");
        let want: Vec<String> = (1..=60).map(|i| i.to_string()).collect();
        assert_eq!(f[0].output, want.join("\n"));
    }

    /// Run `typed` as the input between a `133;B` and `133;C` mark, and
    /// return what the finished command recorded and what Re-run reads.
    fn recorded_command(typed: &str) -> (String, String) {
        let tmp = tempfile::tempdir().unwrap();
        let script = format!(
            "printf '\\033]133;A\\007$ \\033]133;B\\007{typed}\\n\\033]133;C\\007out\\n\\033]133;D;0\\007'"
        );
        let term =
            PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script], tmp.path()).unwrap();
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
        let mut finished = Vec::new();
        while std::time::Instant::now() < deadline {
            finished.extend(term.drain_finished_commands());
            if !finished.is_empty() && !term.command_decorations().is_empty() {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(40));
        }
        let f = finished
            .first()
            .expect("the 133;D must yield a FinishedCommand");
        let deco = term.command_decorations()[0];
        (f.cmd.clone(), term.command_input_text(&deco))
    }

    /// The `printf` formats fish runs in `func` of croft's fish hooks, in
    /// order, rewritten for `/bin/sh`'s printf (which spells ESC `\033`).
    fn fish_hook_printfs(script: &str, func: &str) -> Vec<String> {
        let mut out = Vec::new();
        let mut lines = script.lines();
        let Some(head) = lines.find(|l| {
            l.trim_start().starts_with(&format!("function {func} "))
                || l.trim() == format!("function {func}")
        }) else {
            return out;
        };
        let indent = head.len() - head.trim_start().len();
        for line in lines {
            let t = line.trim_start();
            if t == "end" && line.len() - t.len() == indent {
                break;
            }
            if let Some(rest) = t.strip_prefix("printf '") {
                let fmt = &rest[..rest.find('\'').unwrap()];
                out.push(fmt.replace("\\e", "\\033"));
            }
        }
        out
    }

    /// #1514: replay what croft's fish 3 hooks print around one command
    /// (the prompt event, the user's prompt, the wrapped prompt's end mark,
    /// the typed line, preexec, postexec) through a real pane, and the
    /// command is recorded with its text. Without an end-of-prompt mark it
    /// was recorded empty, so the history never got it.
    #[test]
    fn a_fish_3_pane_records_the_typed_command() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = crate::shell_integration::ensure_fish_integration(tmp.path()).unwrap();
        let script = std::fs::read_to_string(dir.join("fish/vendor_conf.d/croft.fish")).unwrap();
        let fmts = |func: &str| {
            fish_hook_printfs(&script, func)
                .into_iter()
                .filter(|f| !f.contains("]7;"))
                .map(|f| f.replace("%s", "0"))
                .collect::<String>()
        };
        // The prompt event's own `133;D` closes a cycle a command left
        // open; with none open here, it does not fire.
        let prompt_start = fmts("_croft_mark_prompt").replace("\\033]133;D\\a", "");
        assert!(prompt_start.contains("133;A"), "{prompt_start:?}");
        let stream = format!(
            "{prompt_start}~> {}ls -d /tmp\\n{}/tmp\\n{}",
            fmts("_croft_prompt_end"),
            fmts("_croft_mark_output_start"),
            fmts("_croft_mark_output_end"),
        );
        let term = PtyTerminal::new_running(
            "/bin/sh",
            &[String::from("-c"), format!("printf '{stream}'")],
            tmp.path(),
        )
        .unwrap();
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
        let mut finished = Vec::new();
        while std::time::Instant::now() < deadline {
            finished.extend(term.drain_finished_commands());
            if !finished.is_empty() {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(40));
        }
        let f = finished.first().expect("the hooks' 133;D ends a command");
        assert_eq!(f.cmd, "ls -d /tmp", "stream {stream:?}");
    }

    /// #1514 negative: fish 4 marks prompts itself, so croft's hooks, the
    /// prompt wrap among them, stay behind the old-fish check and never
    /// add a second set of marks.
    #[test]
    fn the_fish_prompt_wrap_is_only_for_old_fish() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = crate::shell_integration::ensure_fish_integration(tmp.path()).unwrap();
        let script = std::fs::read_to_string(dir.join("fish/vendor_conf.d/croft.fish")).unwrap();
        let gate = script.find("forward-char-passive").unwrap();
        let wrap = script.find("function _croft_wrap_prompt").unwrap();
        let end_mark = script.find("133;B").unwrap();
        assert!(gate < wrap && gate < end_mark);
        // The wrap leaves an already wrapped prompt alone, so a redrawn
        // prompt does not stack wrappers or print the mark twice.
        let body = &script[wrap..];
        let body = &body[..body.find("\n        end\n").unwrap()];
        assert!(body.contains("string match -q '*_croft_prompt_end*'; and return"));
    }

    /// #1514: `funcsave fish_prompt` (and `fish_config prompt save`, which
    /// calls it) and `funced` must see the user's prompt, not croft's
    /// wrapper, or the saved prompt would call croft-only helpers in every
    /// later fish session. Both are wrapped to unwrap the prompt first, and
    /// only on old fish, where the prompt wrap exists.
    #[test]
    fn saving_the_fish_prompt_saves_the_users_prompt_not_the_wrapper() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = crate::shell_integration::ensure_fish_integration(tmp.path()).unwrap();
        let script = std::fs::read_to_string(dir.join("fish/vendor_conf.d/croft.fish")).unwrap();
        let gate = script.find("forward-char-passive").unwrap();
        let unwrap = script.find("function _croft_unwrap_prompt").unwrap();
        assert!(gate < unwrap);
        let body = &script[unwrap..];
        let body = &body[..body.find("\n        end\n").unwrap()];
        assert!(body.contains("functions --copy _croft_user_prompt fish_prompt"));
        for cmd in ["funcsave", "funced"] {
            assert!(script.contains(&format!("functions --copy {cmd} _croft_{cmd}")));
            let def = format!("function {cmd}\n");
            let at = script
                .find(&def)
                .unwrap_or_else(|| panic!("{cmd} is wrapped"));
            assert!(gate < at);
            let wrapper = &script[at..];
            let wrapper = &wrapper[..wrapper.find("\n            end\n").unwrap()];
            let un = wrapper.find("_croft_unwrap_prompt").unwrap();
            let orig = wrapper.find(&format!("_croft_{cmd} $argv")).unwrap();
            assert!(un < orig, "{wrapper}");
        }
    }

    #[test]
    fn a_multi_line_command_is_recorded_without_its_continuation_prompt() {
        // #1250: bash's PS2 `> ` was stored as typed input, and recalling
        // the command ran `> cat notes` as a redirect.
        let (cmd, rerun) = recorded_command("for f in a b; do\\n> cat notes; done");
        assert_eq!(cmd, "for f in a b; do\ncat notes; done");
        assert_eq!(rerun, cmd, "Re-run reads the same text");
        let (cmd, _) = recorded_command("ls \\\\\\n> -la");
        assert_eq!(cmd, "ls \\\n-la");
    }

    #[test]
    fn zsh_continuation_prompts_are_dropped_too() {
        let (cmd, _) = recorded_command("for f in a b\\nfor> do echo $f\\nfor> done");
        assert_eq!(cmd, "for f in a b\ndo echo $f\ndone");
        let (cmd, _) = recorded_command("echo \"a\\ndquote> b\"");
        assert_eq!(cmd, "echo \"a\nb\"");
    }

    #[test]
    fn redirects_typed_by_the_user_stay_in_the_command() {
        // Negative: only the prompt goes. A `>` the user typed, on the first
        // line or at the start of a continuation line, is kept.
        let (cmd, _) = recorded_command("echo hi > out.txt");
        assert_eq!(cmd, "echo hi > out.txt");
        let (cmd, _) = recorded_command("{ echo a\\n> > log; }");
        assert_eq!(cmd, "{ echo a\n> log; }");
    }

    #[test]
    fn an_empty_continuation_line_keeps_no_prompt() {
        // The grid drops a row's trailing blanks, so an empty line after
        // `> ` reads as a bare `>`.
        assert_eq!(
            without_continuation_prompts("ls \\\n>\n> -la"),
            "ls \\\n\n-la"
        );
        assert_eq!(without_continuation_prompts("for x\nfor>"), "for x\n");
        assert_eq!(without_continuation_prompts("a\n>> log"), "a\n>> log");
    }

    #[test]
    fn a_soft_wrapped_line_is_not_a_continuation() {
        // Negative: a long line wraps with no newline and no PS2, so text
        // that happens to sit at the start of the next row is kept.
        let long = format!("echo {}> x", "y".repeat(78));
        let (cmd, _) = recorded_command(&long);
        assert_eq!(cmd, long);
    }

    #[test]
    fn finished_output_keeps_a_final_line_without_trailing_newline() {
        // `133;D` moves no cursor: a diagnostic printed WITHOUT a trailing
        // newline leaves the mark on that very row, and excluding the
        // cursor row dropped exactly the line the matchers needed (#120
        // review).
        let tmp = tempfile::tempdir().unwrap();
        let script = "printf '\\033]133;A\\007$ \\033]133;B\\007cc\\n\\033]133;C\\007'; printf 'lib.c:2:1: error: no newline here'; printf '\\033]133;D;1\\007'";
        let term =
            PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
                .unwrap();
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
        let mut finished = Vec::new();
        while std::time::Instant::now() < deadline {
            finished.extend(term.drain_finished_commands());
            if !finished.is_empty() {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(40));
        }
        let f = finished.first().expect("completion expected");
        assert!(
            f.output.contains("lib.c:2:1: error: no newline here"),
            "the unterminated final row must be captured; got {:?}",
            f.output
        );
    }
}