term-wm-pty-engine 0.9.24-alpha

Cross-platform PTY engine for term-wm (Unix PTY and Windows ConPTY), with vt100 emulation and OSC/clipboard handling.
Documentation
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
use std::io::{Read, Write};
use std::sync::{
    Arc, Condvar, Mutex, OnceLock,
    atomic::{AtomicBool, AtomicUsize, Ordering},
};
use std::thread::{self, JoinHandle};
use std::time::Instant;

use portable_pty::{Child, CommandBuilder, MasterPty, PtySize, native_pty_system};

#[cfg(windows)]
use crate::job_object::JobObject;
use crate::pty_state_tracker::PtyPerformAdapter;
use term_clipboard::{Clipboard, Osc52Extractor};

/// Size of the PTY master read buffer (single `read()` call).
/// 64KB keeps the reader parked most of the time under heavy output
/// (64KB × 60fps ≈ 3.8MB/s throughput, enough for any terminal workload).
const PTY_READ_BUF_SIZE: usize = 65536;

/// Drain-starvation bound (Unix only): a continuous stream (`yes`, busy logs)
/// never returns WouldBlock, so apply any pending resize at least this often to
/// keep the grid attached to the physical window bounds. On Windows the reader
/// applies pending resizes at every (blocking) read boundary instead.
#[cfg(unix)]
const MAX_DRAIN_BYTES: usize = 65536;

/// Windows error `ERROR_OPERATION_ABORTED` (995): the code a blocking
/// `ReadFile` returns when `CancelSynchronousIo` aborts it. The reader treats
/// this as a resize wake — never a fatal read error. (Inert on Unix, where
/// `errno` can never be 995.)
const ERROR_OPERATION_ABORTED: i32 = 995;

#[cfg(unix)]
use std::os::unix::io::RawFd;

/// Wake primitive that nudges the reader thread out of `poll` when the UI
/// requests a resize (Unix). A self-pipe: the read end is polled alongside the
/// PTY master fd, and `signal` writes a byte. On Windows there is no pipe to
/// poll — the ConPTY output pipe is a blocking anonymous pipe — so the wake is
/// instead delivered by `CancelSynchronousIo` in [`Pty::wake_reader`].
#[cfg(unix)]
struct ResizeWake {
    read_fd: RawFd,
    write_fd: RawFd,
}

#[cfg(unix)]
impl ResizeWake {
    fn new() -> std::io::Result<Self> {
        let mut fds = [0i32; 2];
        // SAFETY: pipe writes to a valid 2-element array.
        if unsafe { libc::pipe(fds.as_mut_ptr()) } != 0 {
            return Err(std::io::Error::last_os_error());
        }
        // Both ends non-blocking so poll() returns immediately when signalled
        // and a signal never blocks.
        for fd in &fds {
            // SAFETY: fds are valid descriptors returned by pipe() above.
            unsafe { libc::fcntl(*fd, libc::F_SETFL, libc::O_NONBLOCK) };
        }
        Ok(Self {
            read_fd: fds[0],
            write_fd: fds[1],
        })
    }

    fn read_fd(&self) -> RawFd {
        self.read_fd
    }

    fn signal(&self) {
        let byte = [1u8];
        // SAFETY: write one byte to the pipe write end.
        unsafe {
            let _ = libc::write(self.write_fd, byte.as_ptr() as *const libc::c_void, 1);
        }
    }
}

#[cfg(unix)]
impl Drop for ResizeWake {
    fn drop(&mut self) {
        // SAFETY: close the two pipe ends created in `new`.
        unsafe {
            libc::close(self.read_fd);
            libc::close(self.write_fd);
        }
    }
}

/// Clear (drain) any pending wake bytes on the reader side of the self-pipe.
#[cfg(unix)]
fn clear_wake(fd: RawFd) {
    let mut buf = [0u8; 64];
    loop {
        // SAFETY: read into a valid buffer.
        let n = unsafe { libc::read(fd, buf.as_mut_ptr() as *mut libc::c_void, buf.len()) };
        if n <= 0 {
            break;
        }
    }
}

/// Number of bytes from the end of the previous chunk to carry forward
/// for cross-boundary pattern detection (DSR, OSC 52 header).
/// Must cover the 5-byte OSC 52 header `\x1b]52;` across chunk boundaries
/// (needs at least 4 bytes of tail; 8 provides margin).
const HISTORY_TAIL_LEN: usize = 8;

/// Length of the DSR request sequence `\x1b[6n`.
const DSR_PATTERN_LEN: usize = 4;

/// Env var that enables dumping raw PTY→emulator bytes (as hex) to a file.
/// Temporary diagnostic aid for seeing exactly what a child app sends (e.g.
/// pico's escape sequences at the right margin of a long line).
const ESC_TRACE_ENV: &str = "TERM_WM_TRACE_ESC";

/// Whether `ESC_TRACE_ENV` is set — checked once per process.
static ESC_TRACE_ENABLED: OnceLock<bool> = OnceLock::new();

/// Append a chunk of raw bytes fed to the emulator as a hex line to the file
/// named by `TERM_WM_TRACE_ESC` (default `term_wm_esc_trace.log`). Off by
/// default; no-op when the env var is unset.
fn esc_trace_chunk(bytes: &[u8]) {
    if !*ESC_TRACE_ENABLED.get_or_init(|| std::env::var_os(ESC_TRACE_ENV).is_some()) {
        return;
    }
    let path = std::env::var(ESC_TRACE_ENV).unwrap_or_else(|_| "term_wm_esc_trace.log".to_string());
    if let Ok(mut file) = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(&path)
    {
        let _ = writeln!(file, "{}", hex_bytes(bytes));
    }
}

/// Format bytes as a lowercase hex string (hand-rolled; no extra dependency).
fn hex_bytes(bytes: &[u8]) -> String {
    let mut out = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        out.push_str(&format!("{b:02x}"));
    }
    out
}

/// Buffer size for `proc_name()` on macOS.
#[cfg(target_os = "macos")]
const PROC_NAME_BUF_SIZE: usize = 64;

/// How often to check the foreground process group for title changes.
const FOREGROUND_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_secs(1);
use crate::PtyStatus;
use crate::title::extract_osc_title;

pub type PtyResult<T> = Result<T, Box<dyn std::error::Error + Send + Sync>>;

type StatusCallback = Arc<Mutex<Option<Box<dyn Fn(PtyStatus) + Send + Sync>>>>;

/// Cloneable handle to the PTY input writer.
///
/// Writes to a PTY/ConPTY master are blocking synchronous I/O: when the
/// kernel input buffer fills (fast typing, large paste, or a child that
/// paused reading stdin), `write_all` blocks the calling thread. Callers
/// running on an async runtime (e.g. the session server) must offload writes
/// to a blocking thread (tokio's `spawn_blocking`) via this handle, so a
/// full input buffer never starves a runtime worker. The internal mutex
/// serializes concurrent writers and keeps each `write_bytes` call atomic.
#[derive(Clone)]
pub struct PtyWriter {
    inner: Arc<Mutex<Box<dyn Write + Send>>>,
}

impl PtyWriter {
    fn new(writer: Box<dyn Write + Send>) -> Self {
        Self {
            inner: Arc::new(Mutex::new(writer)),
        }
    }

    /// Write bytes to the PTY master. Blocks until the bytes are accepted
    /// (or the writer fails); call from a dedicated blocking thread.
    pub fn write_bytes(&self, input: &[u8]) -> std::io::Result<()> {
        let mut writer = self.inner.lock().unwrap_or_else(|err| err.into_inner());
        writer.write_all(input)?;
        writer.flush()
    }
}

pub struct Pty {
    /// Shared master for Unix-only process-group queries (`foreground_pid`,
    /// `process_group_id`, `signal_process_group`). The reader thread owns its
    /// own clone for drain-synchronized resizes, so on Windows this field is
    /// absent entirely.
    #[cfg(unix)]
    master: Arc<Mutex<Box<dyn MasterPty + Send>>>,
    writer: PtyWriter,
    /// Raw bytes from the reader thread, kept for consumers that need
    /// unparsed output (e.g., session server forwarding).
    pending: Arc<Mutex<Vec<u8>>>,
    bytes_received: Arc<AtomicUsize>,
    last_bytes: Arc<Mutex<Vec<u8>>>,
    dsr_requested: Arc<AtomicBool>,
    pending_title: Arc<Mutex<Option<String>>>,
    foreground_title: Arc<Mutex<Option<String>>>,
    last_fg_pid: u32,
    last_fg_check: Instant,
    /// Parsed screen shared between the reader thread and the main thread.
    /// The reader parses bytes into this parser in-place. The main thread
    /// locks it to read cells directly — zero clones.
    pub(crate) shared_parser: Arc<Mutex<term_wm_vt100::Parser>>,
    /// Set by the reader thread when new content has been parsed.
    pub(crate) dirty: Arc<AtomicBool>,
    /// Condvar for I/O burst budget: reader waits here when budget exceeded
    /// and the UI hasn't rendered yet.
    pub(crate) dirty_cond: Arc<(Mutex<()>, Condvar)>,
    /// Current emulator size. Owned/shared: the reader applies drain-synchronized
    /// resizes and updates this; the main thread reads it via [`Pty::size`].
    size: Arc<Mutex<PtySize>>,
    /// Latest resize requested by the UI, applied by the reader thread at the
    /// next pipe-drain boundary (never mid-shell-write).
    pending_resize: Arc<Mutex<Option<PtySize>>>,
    /// Wake primitive used to nudge the reader out of `poll` on a resize request.
    #[cfg(unix)]
    resize_wake: ResizeWake,
    scrollback_len: usize,
    child: Option<Box<dyn Child + Send + Sync>>,
    /// Win32 Job Object containing the child's process tree (Windows only).
    /// Dropping it with `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE` terminates any
    /// processes still in the job, so an un-killed `Pty` never orphans
    /// descendants. The Windows analogue of the Unix process group.
    #[cfg(windows)]
    job: Option<JobObject>,
    exited: bool,
    exit_status: Option<portable_pty::ExitStatus>,
    /// Guards against double-fire of the Exited callback from both
    /// has_exited() and the reader thread (EOF detection race).
    exited_emitted: Arc<AtomicBool>,
    reader: Option<JoinHandle<()>>,
    /// Status callback invoked by the reader thread on wakeup and exit.
    status_cb: StatusCallback,
    /// Application state tracker (alternate screen, mouse tracking, margins).
    /// Shared via Arc: reader thread writes (via PtyPerformAdapter), main thread reads.
    pub(crate) tracker: std::sync::Arc<crate::PtyStateTracker>,
    /// Shutdown flag: when true, the reader thread exits its loop ASAP.
    /// Set by into_parts() and Drop.
    shutdown: Arc<AtomicBool>,
}

/// The bounded channel between PTY reader threads and the main event loop
/// provides mechanical backpressure: when the channel is full, the reader
/// thread's `send()` blocks → the PTY master read call pauses → the OS
/// pipe buffer fills → the child process's `write()` blocks. This prevents
/// memory exhaustion when output floods faster than the UI can render.
/// Parts of a `Pty` that can be moved into the `Reaper` for async teardown.
pub struct PtyParts {
    pub child: Option<Box<dyn Child + Send + Sync>>,
    pub reader_handle: Option<JoinHandle<()>>,
}

/// Constant env values applied to every spawned PTY child so ncurses and
/// modern CLI tools render correctly when the session runs across SSH /
/// container hops (see `sanitize_child_environment`).
///
/// macOS ships a defective `screen-256color` terminfo lacking the `bce`
/// (Background Color Erase) capability, which makes ncurses apps (pico, nano)
/// reset attributes before line erases and drop background colors.
/// `xterm-256color` has `bce` and is safe on macOS now that the invalid
/// `LC_CTYPE=UTF-8` is stripped (the grid-math crashes previously associated
/// with it were caused by `setlocale` failing on that locale, not the terminfo
/// entry). Other platforms keep `screen-256color` — their terminfo has `bce`.
#[cfg(target_os = "macos")]
const CHILD_TERM: &str = "xterm-256color";
#[cfg(not(target_os = "macos"))]
const CHILD_TERM: &str = "screen-256color";
const CHILD_COLORTERM: &str = "truecolor";

/// Apply the multiplexer-safe environment to a spawned PTY child.
///
/// - Forces `TERM` to a terminfo entry with `bce` (Background Color Erase):
///   `xterm-256color` on macOS (where Apple's `screen-256color` terminfo is
///   broken and missing `bce`), `screen-256color` elsewhere. Without `bce`,
///   ncurses apps reset attributes before line erases, which erases the
///   background in the emulated screen.
/// - Opts into `COLORTERM=truecolor` for modern CLI tools (Neovim, bat, delta,
///   lsd) that look for COLORTERM to bypass the 256-color limit of the
///   screen-256color terminfo. ncurses ignores COLORTERM entirely — it keys
///   off the terminfo database for `$TERM` — so this is purely for those
///   direct-ANSI tools.
/// - Strips the invalid `LC_CTYPE=UTF-8` injected by macOS/OrbStack SSH hops.
///   "UTF-8" is a character encoding, not a valid POSIX locale name, which
///   causes `setlocale()` to fail and ncurses to crash or corrupt layout.
///   Removing it lets the child fall back to its own native locale default.
fn sanitize_child_environment(command: &mut CommandBuilder) {
    sanitize_child_environment_with_lc_ctype(command, std::env::var("LC_CTYPE").ok().as_deref());
}

/// Core of [`sanitize_child_environment`], parameterized over the incoming
/// `LC_CTYPE` value so the stripping logic is deterministically unit-testable
/// without mutating the process-global environment.
fn sanitize_child_environment_with_lc_ctype(command: &mut CommandBuilder, lc_ctype: Option<&str>) {
    command.env("TERM", CHILD_TERM);
    command.env("COLORTERM", CHILD_COLORTERM);
    if lc_ctype == Some("UTF-8") {
        command.env_remove("LC_CTYPE");
    }
}

impl Pty {
    pub fn spawn(command: CommandBuilder, size: PtySize) -> PtyResult<Self> {
        Self::spawn_with_scrollback(command, size, 0)
    }

    pub fn spawn_with_scrollback(
        mut command: CommandBuilder,
        size: PtySize,
        scrollback_len: usize,
    ) -> PtyResult<Self> {
        sanitize_child_environment(&mut command);
        let pty_system = native_pty_system();
        let pair = pty_system
            .openpty(size)
            .map_err(|err| wrap_err("openpty", err))?;
        let child = pair
            .slave
            .spawn_command(command)
            .map_err(|err| wrap_err("spawn_command", err))?;
        #[cfg(windows)]
        let job = {
            // Contain the child's process tree in a Job Object so kill paths
            // tear down grandchildren too (the Windows analogue of
            // `kill(-pgid, sig)`). Assignment happens immediately after spawn:
            // Win32 allows nested jobs, so membership in any parent job does
            // not block this. Once the child is assigned, every descendant it
            // subsequently spawns inherits job membership and dies with the
            // job (or on job-handle close).
            //
            // TODO(windows): assignment is post-spawn, so a descendant spawned
            // in the window between portable-pty's `CreateProcessW` returning
            // and our `AssignProcessToJobObject` call escapes the job and
            // would be orphaned by a kill. The formal zero-escape guarantee
            // requires spawning the child with `CREATE_SUSPENDED`, assigning
            // the suspended process to the job, then `ResumeThread`. portable-pty
            // 0.9.0 hardcodes the creation flags (`psuedocon.rs`:
            // `EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT`) and
            // `CommandBuilder` exposes no creation-flags hook, so the suspended
            // spawn must be added upstream (or the crate forked). Until then
            // the guarantee is: descendants spawned after assignment are
            // contained; descendants spawned during the startup race are not.
            let job = JobObject::new().ok();
            if let (Some(job), Some(proc)) = (&job, child.as_raw_handle())
                && let Err(err) = unsafe { job.assign(proc) }
            {
                tracing::warn!(
                    "AssignProcessToJobObject failed: {err}; falling back to single-process kill"
                );
            }
            job
        };
        let reader = pair
            .master
            .try_clone_reader()
            .map_err(|err| wrap_err("try_clone_reader", err))?;
        let writer = PtyWriter::new(
            pair.master
                .take_writer()
                .map_err(|err| wrap_err("take_writer", err))?,
        );
        // The reader thread applies drain-synchronized resizes (reflow + ioctl),
        // so master must be shared with it.
        let master = Arc::new(Mutex::new(pair.master));
        let reader_master = Arc::clone(&master);
        let size_arc = Arc::new(Mutex::new(size));
        let reader_size = Arc::clone(&size_arc);
        let pending_resize = Arc::new(Mutex::new(None));
        let reader_pending_resize = Arc::clone(&pending_resize);
        #[cfg(unix)]
        let resize_wake = ResizeWake::new().map_err(|err| wrap_err("resize wake", err))?;
        let pending = Arc::new(Mutex::new(Vec::new()));
        let bytes_received = Arc::new(AtomicUsize::new(0));
        let last_bytes = Arc::new(Mutex::new(Vec::new()));
        let dsr_requested = Arc::new(AtomicBool::new(false));
        let reader_pending = Arc::clone(&pending);
        let reader_bytes = Arc::clone(&bytes_received);
        let reader_last = Arc::clone(&last_bytes);
        let reader_dsr = Arc::clone(&dsr_requested);
        let status_cb: StatusCallback = Arc::new(Mutex::new(None));
        let reader_status_cb = Arc::clone(&status_cb);
        let exited_emitted = Arc::new(AtomicBool::new(false));
        let reader_exited_emitted = Arc::clone(&exited_emitted);

        let pending_title = Arc::new(Mutex::new(None));
        let foreground_title = Arc::new(Mutex::new(None));
        let initial_parser = term_wm_vt100::Parser::new(size.rows, size.cols, scrollback_len);
        let tracker = std::sync::Arc::new(crate::PtyStateTracker::new(size.rows));
        let reader_tracker = std::sync::Arc::clone(&tracker);
        let shared_parser = Arc::new(Mutex::new(initial_parser));
        let dirty = Arc::new(AtomicBool::new(false));
        let dirty_cond = Arc::new((Mutex::new(()), Condvar::new()));
        let shutdown = Arc::new(AtomicBool::new(false));
        let reader_shutdown = Arc::clone(&shutdown);
        let reader_parser = Arc::clone(&shared_parser);
        let reader_dirty = Arc::clone(&dirty);
        let reader_dirty_cond = Arc::clone(&dirty_cond);
        let reader_pending_title = Arc::clone(&pending_title);
        #[cfg(unix)]
        let wake_read_fd = resize_wake.read_fd();
        let reader_handle = thread::spawn(move || {
            parser_read_loop(ParserReadLoopArgs {
                reader,
                pending: reader_pending,
                bytes_received: reader_bytes,
                last_bytes: reader_last,
                dsr_requested: reader_dsr,
                shared_parser: reader_parser,
                dirty: reader_dirty,
                dirty_cond: reader_dirty_cond,
                pending_title: reader_pending_title,
                status_cb: reader_status_cb,
                scrollback_len,
                osc52_text: None,
                clipboard: None,
                exited_emitted: reader_exited_emitted,
                tracker: reader_tracker,
                master: reader_master,
                size: reader_size,
                pending_resize: reader_pending_resize,
                #[cfg(unix)]
                wake_read_fd,
                shutdown: reader_shutdown,
            })
        });
        Ok(Self {
            #[cfg(unix)]
            master,
            writer,
            pending,
            bytes_received,
            last_bytes,
            dsr_requested,
            pending_title,
            foreground_title,
            last_fg_pid: 0,
            last_fg_check: Instant::now(),
            shared_parser,
            dirty,
            dirty_cond,
            size: size_arc,
            pending_resize,
            #[cfg(unix)]
            resize_wake,
            tracker,
            scrollback_len,
            child: Some(child),
            #[cfg(windows)]
            job,
            exited: false,
            exit_status: None,
            reader: Some(reader_handle),
            status_cb,
            exited_emitted,
            shutdown,
        })
    }

    /// Set a status callback invoked by the reader thread on data and exit.
    /// Uses `Arc<Mutex<>>` so the reader thread (which holds a clone) sees updates.
    ///
    /// If the child has already exited (reader thread detected EOF before the
    /// callback was registered, or ConPTY swallowed the EOF), fires the callback
    /// immediately so the async polling loop can process the exit state.
    pub fn set_status_callback(&mut self, cb: Option<Box<dyn Fn(PtyStatus) + Send + Sync>>) {
        let mut fire_cb = None;

        if let Ok(mut guard) = self.status_cb.lock() {
            if self.exited {
                self.exited_emitted.store(true, Ordering::Release);
                fire_cb = cb;
                *guard = None;
            } else if let Some(child) = self.child.as_mut()
                && let Ok(Some(status)) = child.try_wait()
            {
                self.exited = true;
                self.exit_status = Some(status);
                self.child = None;
                self.exited_emitted.store(true, Ordering::Release);
                fire_cb = cb;
                *guard = None;
            } else {
                *guard = cb;
            }
        }

        if let Some(reader) = &self.reader {
            reader.thread().unpark();
        }

        if let Some(cb_fn) = fire_cb {
            cb_fn(PtyStatus::Exited);
        }
    }

    /// Extract the child and reader handle for async reaping.
    /// After this call, the Pty is a shell — `update()` will no longer
    /// receive new data. Used by `Reaper::reap()`.
    pub fn into_parts(&mut self) -> PtyParts {
        self.shutdown.store(true, Ordering::Release);
        if let Some(reader) = &self.reader {
            reader.thread().unpark();
        }
        // Wake the reader so it notices `shutdown` and exits promptly (on
        // Windows this aborts the blocking ConPTY read; on Unix it nudges the
        // poll), so a later join on the returned handle does not hang.
        self.wake_reader();
        PtyParts {
            child: self.child.take(),
            reader_handle: self.reader.take(),
        }
    }

    /// Number of bytes received from the pty — always returns 0 after
    /// `into_parts()` has been called.
    pub fn reader_is_alive(&self) -> bool {
        self.reader.is_some()
    }

    /// Request a resize. The reader thread applies it (emulator reflow + OS
    /// `ioctl` / SIGWINCH) at the next pipe-drain boundary, so the grid width
    /// never changes while the shell is mid-draw and SIGWINCH is delivered only
    /// when the child is idle (drain-synchronized; no timers).
    pub fn resize(&mut self, size: PtySize) -> PtyResult<()> {
        // WORKAROUND: vt100 0.16.2 Grid::col_wrap (grid.rs:683) panics with a
        // subtraction overflow at cols=1; rows=1 causes similar issues. Clamp
        // the minimum so the PTY emulator doesn't crash when the terminal is
        // shrunk small.
        if size.rows < 2 || size.cols < 2 {
            return Ok(());
        }
        let mut pending = self
            .pending_resize
            .lock()
            .unwrap_or_else(|err| err.into_inner());
        if *pending == Some(size) {
            return Ok(()); // already requested
        }
        *pending = Some(size);
        drop(pending);
        self.wake_reader();
        Ok(())
    }

    /// Nudge the reader thread out of its blocking wait so it reaches the
    /// drain boundary and applies a pending resize promptly.
    ///
    /// Unix: writes the resize-wake self-pipe, which the reader polls alongside
    /// the PTY master fd.
    ///
    /// Windows: the ConPTY output pipe is a blocking anonymous pipe that cannot
    /// be polled or timed out (WSAPoll is sockets-only), so the reader parks in
    /// `ReadFile` while the pipe is idle and would never reach a drain boundary.
    /// `CancelSynchronousIo` aborts that in-flight read, which the reader
    /// recognises as a wake (`ERROR_OPERATION_ABORTED`), not an error. Safe to
    /// call when the reader is not currently blocked — the reader also re-checks
    /// `pending_resize` before its next blocking read.
    fn wake_reader(&mut self) {
        #[cfg(unix)]
        self.resize_wake.signal();
        #[cfg(windows)]
        if let Some(reader) = &self.reader {
            use std::os::windows::io::{AsHandle, AsRawHandle};
            // SAFETY: `handle` is the OS thread handle backing the reader's
            // `JoinHandle`, which is alive for as long as the `Pty` holds it.
            // It was created by `CreateThread` with `THREAD_ALL_ACCESS`, which
            // `CancelSynchronousIo` requires.
            unsafe {
                kernel32::CancelSynchronousIo(reader.as_handle().as_raw_handle());
            }
        }
    }

    pub fn write_bytes(&mut self, input: &[u8]) -> std::io::Result<()> {
        self.writer.write_bytes(input)
    }

    /// Cloneable handle for offloading blocking PTY writes to a dedicated
    /// thread (e.g. tokio's `spawn_blocking`). Never call the write from an
    /// async worker directly: a full kernel input buffer blocks the thread.
    pub fn writer_handle(&self) -> PtyWriter {
        self.writer.clone()
    }

    pub fn write_str(&mut self, input: &str) -> std::io::Result<()> {
        self.write_bytes(input.as_bytes())
    }

    pub fn take_pending_title(&self) -> Option<String> {
        let fg = self
            .foreground_title
            .lock()
            .unwrap_or_else(|err| err.into_inner())
            .clone();

        if fg.is_some() {
            // Process name is authoritative. Purge any stale OSC titles.
            let _ = self
                .pending_title
                .lock()
                .unwrap_or_else(|err| err.into_inner())
                .take();
            return fg;
        }

        self.pending_title
            .lock()
            .unwrap_or_else(|err| err.into_inner())
            .take()
    }

    fn poll_foreground(&mut self) {
        if self.last_fg_check.elapsed() >= FOREGROUND_POLL_INTERVAL {
            self.last_fg_check = Instant::now();
            if let Some(fg_pid) = self.foreground_pid()
                && fg_pid != self.last_fg_pid
            {
                self.last_fg_pid = fg_pid;
                let name = get_process_name(fg_pid);
                *self
                    .foreground_title
                    .lock()
                    .unwrap_or_else(|err| err.into_inner()) = name;
            }
        }
    }

    #[cfg(unix)]
    fn foreground_pid(&self) -> Option<u32> {
        self.master
            .lock()
            .unwrap_or_else(|err| err.into_inner())
            .process_group_leader()
            .map(|p| p as u32)
    }

    #[cfg(windows)]
    fn foreground_pid(&self) -> Option<u32> {
        let shell_pid = self.child.as_ref().and_then(|c| c.process_id())?;
        find_foreground_process_windows(shell_pid)
    }

    #[cfg(not(any(unix, windows)))]
    fn foreground_pid(&self) -> Option<u32> {
        None
    }

    /// Read pending bytes from the PTY reader thread (non-blocking).
    /// Used by the session server to forward raw bytes to remote clients.
    pub fn drain_pending(&mut self) -> Vec<u8> {
        let mut pending = self.pending.lock().unwrap_or_else(|err| err.into_inner());
        pending.split_off(0)
    }

    /// Drain all buffered output after the child has exited, first waiting
    /// (bounded by `grace`) for the reader thread to finish its EOF processing.
    ///
    /// The OS exit signal (`child.try_wait()`) can precede the reader thread's
    /// final read of the master fd, so draining immediately could truncate
    /// trailing bytes. The reader thread appends each chunk to `pending` before
    /// it reads EOF, so once the thread terminates `pending` is guaranteed
    /// complete. On Unix the reader EOFs within microseconds of process exit, so
    /// the wait is effectively free; on Windows ConPTY (where EOF can be
    /// swallowed and `has_exited()` relies on the `try_wait` fallback) the grace
    /// bounds the wait and we drain best-effort.
    pub fn drain_final_output(&mut self, grace: std::time::Duration) -> Vec<u8> {
        self.screen();
        if let Some(handle) = self.reader.as_ref() {
            let deadline = std::time::Instant::now() + grace;
            while !handle.is_finished() && std::time::Instant::now() < deadline {
                std::thread::sleep(std::time::Duration::from_millis(2));
            }
        }
        self.drain_pending()
    }

    pub fn screen_lines(&mut self) -> Vec<String> {
        self.screen(); // sync dirty state
        // Clone the screen out of the lock and drop the guard before any
        // string formatting, so the reader thread can keep ingesting bytes.
        let screen = self
            .shared_parser
            .lock()
            .unwrap_or_else(|err| err.into_inner())
            .screen()
            .clone();
        let contents = screen.contents();
        let mut lines: Vec<String> = contents.lines().map(|line| line.to_string()).collect();
        let rows = self.size.lock().unwrap_or_else(|err| err.into_inner()).rows as usize;
        if lines.len() < rows {
            lines.resize(rows, String::new());
        }
        lines
    }

    pub fn has_exited(&mut self) -> bool {
        if self.exited {
            return true;
        }
        let Some(child) = self.child.as_mut() else {
            return true;
        };
        match child.try_wait() {
            Ok(Some(status)) => {
                self.exited = true;
                self.exit_status = Some(status);
                self.child = None;

                // ConPTY pipes on Windows frequently swallow EOF, leaving the
                // reader thread blocked forever. Since this method is polled
                // every frame, we manually synthesize the exit callback here
                // when we detect the child process has died.
                // Use an atomic latch so the callback fires at most once —
                // the reader thread may also detect EOF and race to fire it.
                if let Ok(guard) = self.status_cb.lock()
                    && let Some(ref cb) = *guard
                    && !self.exited_emitted.swap(true, Ordering::AcqRel)
                {
                    cb(crate::PtyStatus::Exited);
                }

                true
            }
            Ok(None) => false,
            Err(_) => false,
        }
    }

    pub fn exit_status(&self) -> Option<portable_pty::ExitStatus> {
        self.exit_status.clone()
    }

    pub fn take_exit_status(&mut self) -> Option<portable_pty::ExitStatus> {
        self.exit_status.take()
    }

    /// Kill the child process if present.
    ///
    /// On Windows the whole contained tree is terminated via the Job Object
    /// (grandchildren included), falling back to single-process termination
    /// when containment was not established. The job handle is taken so its
    /// `Drop` (KILL_ON_JOB_CLOSE) is the last line of defense for stragglers.
    pub fn kill_child(&mut self) -> PtyResult<()> {
        #[cfg(windows)]
        if let Some(job) = self.job.take() {
            let _ = job.terminate(1);
        }
        if let Some(mut child) = self.child.take() {
            child.kill().map_err(|err| wrap_err("kill", err))?;
            self.exited = true;
            self.child = None;
        }
        Ok(())
    }

    /// Process group leader (pgid) of the PTY child's session, when known.
    ///
    /// On Unix the child is started via `setsid()` (portable-pty), so its pgid
    /// equals its pid; a negative-pgid `kill(2)` then signals the whole
    /// process tree. Returns `None` where the platform does not expose it
    /// (e.g. Windows ConPTY).
    #[cfg(unix)]
    pub fn process_group_id(&self) -> Option<i32> {
        self.master
            .lock()
            .unwrap_or_else(|err| err.into_inner())
            .process_group_leader()
    }

    /// Send a signal to the child's entire process group, not just the leader.
    ///
    /// Strictly non-blocking: translates to a single `kill(-pgid, signal)` and
    /// returns immediately. This is mechanism only — the caller (the daemon
    /// supervisor) owns any escalation policy (grace timers, SIGTERM→SIGKILL
    /// sequencing, exited-state arbitration). No temporal waits live here.
    ///
    /// Returns an error when no process group is known on this platform; the
    /// supervisor falls back to `kill_child()` (single process).
    #[cfg(unix)]
    pub fn signal_process_group(&self, signal: i32) -> PtyResult<()> {
        let Some(pgid) = self
            .master
            .lock()
            .unwrap_or_else(|err| err.into_inner())
            .process_group_leader()
        else {
            return Err(wrap_err(
                "signal_process_group",
                std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "PTY child has no process group",
                ),
            ));
        };
        let ret = unsafe { libc::kill(-pgid, signal) };
        if ret == -1 {
            return Err(wrap_err(
                "signal_process_group",
                std::io::Error::last_os_error(),
            ));
        }
        Ok(())
    }

    pub fn size(&self) -> PtySize {
        *self.size.lock().unwrap_or_else(|err| err.into_inner())
    }

    /// Sync dirty state and handle DSR/foreground polling.
    /// The caller should then lock `shared_parser()` directly for cell access.
    pub fn screen(&mut self) {
        self.poll_foreground();
        if self.dirty.swap(false, Ordering::Acquire) {
            // Send DSR response if requested by the reader thread.
            if self.dsr_requested.swap(false, Ordering::Relaxed) {
                let parser = self.shared_parser.lock().unwrap();
                let (row, col) = parser.screen().cursor_position();
                drop(parser);
                let response = format!("\x1b[{};{}R", row.saturating_add(1), col.saturating_add(1));
                let _ = self.write_bytes(response.as_bytes());
            }
            // Acquire the lock to prevent lost wakeups on the condition variable
            let (lock, cvar) = &*self.dirty_cond;
            let _guard = lock.lock().unwrap();
            cvar.notify_all();
        }
    }

    /// Sync dirty state and return the full terminal snapshot.
    /// Combines screen() (which clears dirty and wakes the reader)
    /// with a formatted snapshot of the current parser state.
    pub fn generate_snapshot(&mut self) -> Vec<u8> {
        self.screen();
        // Clone the screen out of the lock and drop the guard before the
        // O(rows x cols) escape-code formatting, so the reader thread can keep
        // ingesting bytes while the snapshot is built.
        self.shared_parser
            .lock()
            .unwrap_or_else(|err| err.into_inner())
            .screen()
            .clone()
            .state_formatted()
    }

    pub fn bytes_received(&self) -> usize {
        self.bytes_received.load(Ordering::Relaxed)
    }

    pub fn last_bytes_text(&self) -> String {
        let bytes = self
            .last_bytes
            .lock()
            .map(|buf| buf.clone())
            .unwrap_or_default();
        bytes_to_debug_text(&bytes, 32)
    }

    pub fn scrollback(&mut self) -> usize {
        self.screen(); // sync dirty state
        let parser = self.shared_parser.lock().unwrap();
        parser.screen().scrollback()
    }

    pub fn set_scrollback(&mut self, rows: usize) {
        let max = self.scrollback_len;
        let mut parser = self.shared_parser.lock().unwrap();
        parser.screen_mut().set_scrollback(rows.min(max));
    }

    pub fn scrollback_len(&self) -> usize {
        self.scrollback_len
    }

    pub fn max_scrollback(&mut self) -> usize {
        let max_sb = self.scrollback_len;
        if max_sb == 0 {
            return 0;
        }
        let mut parser = self.shared_parser.lock().unwrap();
        let screen = parser.screen_mut();
        let current = screen.scrollback();
        screen.set_scrollback(max_sb);
        let max = screen.scrollback();
        screen.set_scrollback(current);
        max
    }

    pub fn alternate_screen(&mut self) -> bool {
        self.screen(); // sync dirty state
        let parser = self.shared_parser.lock().unwrap();
        parser.screen().alternate_screen()
    }

    /// Return an `Arc<dyn DirectInputTracker>` for this PTY's state tracker.
    /// Used by the window manager to auto-enable Direct Mode when the
    /// application enters alternate screen, enables mouse tracking, etc.
    pub fn direct_input_tracker(&self) -> std::sync::Arc<dyn crate::DirectInputTracker> {
        self.tracker.clone()
    }
}

impl Drop for Pty {
    fn drop(&mut self) {
        self.shutdown.store(true, Ordering::Release);
        if let Some(reader) = &self.reader {
            reader.thread().unpark();
        }
        self.wake_reader();
    }
}

/// Configuration and shared state for the PTY reader thread.
struct ParserReadLoopArgs {
    reader: Box<dyn Read + Send>,
    pending: Arc<Mutex<Vec<u8>>>,
    bytes_received: Arc<AtomicUsize>,
    last_bytes: Arc<Mutex<Vec<u8>>>,
    dsr_requested: Arc<AtomicBool>,
    shared_parser: Arc<Mutex<term_wm_vt100::Parser>>,
    dirty: Arc<AtomicBool>,
    dirty_cond: Arc<(std::sync::Mutex<()>, Condvar)>,
    pending_title: Arc<Mutex<Option<String>>>,
    status_cb: StatusCallback,
    scrollback_len: usize,
    /// Shared latch: taken once by whichever path detects exit first.
    exited_emitted: Arc<AtomicBool>,
    /// Test-only hook: when `Some`, the extracted OSC 52 text is written here
    /// in addition to the real clipboard, so tests can assert the value.
    osc52_text: Option<Arc<Mutex<Option<String>>>>,
    /// Clipboard to relay extracted OSC 52 sequences through. `None` in
    /// production (the loop constructs a default handle); tests inject an
    /// isolated, headless [`Clipboard`] so the relay can be exercised without
    /// touching the real system clipboard or process-global default buffer.
    clipboard: Option<Clipboard>,
    /// Application state tracker — shared via Arc with Pty.
    tracker: std::sync::Arc<crate::PtyStateTracker>,
    /// Shared master for drain-synchronized `ioctl` resizes applied by the reader.
    master: Arc<Mutex<Box<dyn MasterPty + Send>>>,
    /// Current emulator size (shared; updated by the reader when it applies a resize).
    size: Arc<Mutex<PtySize>>,
    /// Resize requested by the UI, applied at the next pipe-drain boundary.
    pending_resize: Arc<Mutex<Option<PtySize>>>,
    /// Read end of the resize wake self-pipe (polled alongside the PTY fd).
    #[cfg(unix)]
    wake_read_fd: RawFd,
    /// Set by `into_parts`/`Drop`: the reader exits its loop ASAP. On Windows
    /// in particular the blocking ConPTY read is otherwise uninterruptible.
    shutdown: Arc<AtomicBool>,
}

fn parser_read_loop(args: ParserReadLoopArgs) {
    let ParserReadLoopArgs {
        mut reader,
        pending,
        bytes_received,
        last_bytes,
        dsr_requested,
        shared_parser,
        dirty,
        dirty_cond,
        pending_title,
        status_cb,
        scrollback_len: _scrollback_len,
        osc52_text,
        clipboard,
        exited_emitted,
        tracker,
        master,
        size,
        pending_resize,
        #[cfg(unix)]
        wake_read_fd,
        shutdown,
    } = args;
    let mut prev_tail: [u8; HISTORY_TAIL_LEN] = [0; HISTORY_TAIL_LEN];
    let mut buf = [0u8; PTY_READ_BUF_SIZE];
    let mut osc52 = Osc52Extractor::new();
    let mut bytes_since_render = 0usize;
    let mut vte_parser = vte::Parser::new();
    let tracker_for_adapter = std::sync::Arc::clone(&tracker);
    let mut tracker_adapter = PtyPerformAdapter::new(tracker_for_adapter);
    // One clipboard handle for the whole reader lifetime: re-initialising
    // arboard per OSC 52 sequence would repeat the display-server handshake
    // on every copy event.  Each extracted sequence is relayed synchronously
    // (no debounce) so the tail payload of a burst is never dropped.
    //
    // Initialised lazily on the first OSC 52 sequence: arboard's handshake can
    // block for 500ms+ (macOS pasteboard / Wayland), and we must not stall the
    // reader loop's startup (and thus the first drain-synchronized resize) on it.
    let mut clipboard: Option<Clipboard> = clipboard;
    const IO_BURST_BUDGET: usize = 256 * 1024; // 256 KB
    // The pty master fd never changes — fetch it once to avoid a Mutex lock on
    // every drain iteration (the UI thread and apply_resize also lock `master`).
    #[cfg(unix)]
    let master_fd = master
        .lock()
        .unwrap_or_else(|err| err.into_inner())
        .as_raw_fd()
        .unwrap_or(-1);
    'reader: loop {
        if shutdown.load(Ordering::Acquire) {
            break 'reader;
        }
        // Block until the PTY master or the resize-wake is readable, so a
        // resize request is noticed even while the pipe is idle.
        #[cfg(unix)]
        {
            let mut pollfds = [
                libc::pollfd {
                    fd: master_fd,
                    events: libc::POLLIN,
                    revents: 0,
                },
                libc::pollfd {
                    fd: wake_read_fd,
                    events: libc::POLLIN,
                    revents: 0,
                },
            ];
            let _ = unsafe { libc::poll(pollfds.as_mut_ptr(), pollfds.len() as libc::nfds_t, -1) };
            if pollfds[1].revents & libc::POLLIN != 0 {
                clear_wake(wake_read_fd);
            }
        }

        // Drain: keep reading until the pipe is empty (or the starvation bound),
        // then apply any pending resize at the drain boundary.
        #[cfg(unix)]
        let mut drain_bytes = 0usize;
        // Clippy: on Windows every path through this loop breaks — the blocking
        // ConPTY read cannot drain multiple chunks per iteration, so the shape
        // is deliberately a single read + drain boundary (the boundary code is
        // shared with Unix below).
        #[allow(clippy::never_loop)]
        loop {
            // (Windows) The ConPTY read is a blocking anonymous pipe that cannot
            // be polled or timed out. A `CancelSynchronousIo` wake can be lost
            // if it lands while the reader is between reads, so check for a
            // pending resize (and shutdown) before blocking — the boundary apply
            // below then reflows the grid without waiting for the next chunk of
            // output.
            #[cfg(windows)]
            {
                let has_pending = pending_resize
                    .lock()
                    .unwrap_or_else(|err| err.into_inner())
                    .is_some();
                if has_pending || shutdown.load(Ordering::Acquire) {
                    break;
                }
            }
            // (Unix) zero-timeout availability check: pipe empty → drain boundary.
            #[cfg(unix)]
            {
                let mut pfd = libc::pollfd {
                    fd: master_fd,
                    events: libc::POLLIN,
                    revents: 0,
                };
                let pr = unsafe { libc::poll(&mut pfd, 1, 0) };
                let hup = pfd.revents & (libc::POLLHUP | libc::POLLERR) != 0;
                if pr <= 0 || (pfd.revents & libc::POLLIN == 0 && !hup) {
                    break;
                }
            }
            match reader.read(&mut buf) {
                Ok(0) => {
                    // EOF — child exited. Flush any buffered OSC 52 payload
                    // (Windows ConPTY may have consumed the terminator).
                    if let Some(text) = osc52.finish() {
                        if clipboard.is_none() {
                            clipboard = Some(Clipboard::new());
                        }
                        if let Some(clip) = clipboard.as_mut() {
                            clip.set(&text);
                        }
                        if let Some(ref capture) = osc52_text {
                            *capture.lock().unwrap_or_else(|err| err.into_inner()) = Some(text);
                        }
                    }
                    // Send wakeup for final screen, then exited.
                    let guard = status_cb.lock().unwrap_or_else(|err| err.into_inner());
                    if let Some(ref cb) = *guard {
                        cb(crate::PtyStatus::Wakeup);
                        if !exited_emitted.swap(true, Ordering::AcqRel) {
                            cb(crate::PtyStatus::Exited);
                        }
                    }
                    break 'reader;
                }
                Ok(n) => {
                    bytes_received.fetch_add(n, Ordering::Relaxed);
                    bytes_since_render += n;
                    // DSR detection: 65536-byte reads make cross-chunk splitting
                    // of the 4-byte \x1b[6n pattern vanishingly unlikely.
                    if buf[..n].windows(DSR_PATTERN_LEN).any(|w| w == b"\x1b[6n") {
                        dsr_requested.store(true, Ordering::Relaxed);
                    }
                    let mut last = last_bytes.lock().unwrap_or_else(|err| err.into_inner());
                    last.clear();
                    last.extend_from_slice(&buf[..n]);
                    let mut p = pending.lock().unwrap_or_else(|err| err.into_inner());
                    p.extend_from_slice(&buf[..n]);
                    // Cap pending to prevent unbounded growth when no
                    // consumer calls drain_pending() (local terminal mode).
                    const PENDING_CAP: usize = 1024 * 1024; // 1 MB
                    if p.len() > PENDING_CAP {
                        p.clear();
                    }

                    // Process bytes through the application state tracker
                    // (alternate screen, mouse tracking, margins — atomics, no lock).
                    let prev_mode = tracker.direct_input_mode();
                    vte_parser.advance(&mut tracker_adapter, &buf[..n]);
                    let new_mode = tracker.direct_input_mode();
                    if prev_mode != new_mode {
                        tracing::info!(
                            "[STAGE 1] PTY routing flipped: {:?} -> {:?}",
                            prev_mode,
                            new_mode
                        );
                        let guard = status_cb.lock().unwrap_or_else(|err| err.into_inner());
                        if let Some(ref cb) = *guard {
                            cb(crate::PtyStatus::DirectInputChanged(new_mode));
                        } else {
                            tracing::error!(
                                "[STAGE 1] status_cb is NONE when transition occurred!"
                            );
                        }
                    }

                    // Process bytes directly into the shared parser.
                    {
                        let mut shared =
                            shared_parser.lock().unwrap_or_else(|err| err.into_inner());
                        shared.process(&buf[..n]);
                    }
                    esc_trace_chunk(&buf[..n]);

                    if let Some(title) = extract_osc_title(&buf[..n]) {
                        let mut guard = pending_title.lock().unwrap_or_else(|err| err.into_inner());
                        *guard = Some(title);
                    }
                    // Intercept OSC 52 clipboard sequences (cross-chunk buffering).
                    // Relay each extracted sequence synchronously via the hoisted
                    // handle — no debounce, so the tail payload is never dropped.
                    // The handle is lazy-initialised on the first sequence so the
                    // reader loop's startup is never blocked on arboard's handshake.
                    //
                    // TODO: OSC 52 interception currently runs unconditionally —
                    // including in Direct Input Mode, where mouse-managed clipboard
                    // handling is otherwise delegated to the running app. Decide
                    // whether (and how) to gate this relay (also considering the
                    // nested term-session client relay) and file a GitHub issue to
                    // track it.
                    if let Some(text) = osc52.push(&buf[..n], &prev_tail) {
                        if clipboard.is_none() {
                            clipboard = Some(Clipboard::new());
                        }
                        if let Some(clip) = clipboard.as_mut() {
                            clip.set(&text);
                        }
                        if let Some(ref capture) = osc52_text {
                            *capture.lock().unwrap_or_else(|err| err.into_inner()) = Some(text);
                        }
                    }

                    // Update prev_tail for next iteration's cross-chunk detection.
                    if n >= HISTORY_TAIL_LEN {
                        prev_tail.copy_from_slice(&buf[n - HISTORY_TAIL_LEN..n]);
                    } else if n > 0 {
                        prev_tail.rotate_left(n);
                        prev_tail[HISTORY_TAIL_LEN - n..].copy_from_slice(&buf[..n]);
                    }

                    // Edge-triggered wakeup: only notify on false→true transition.
                    // Prevents flooding the IPC channel with thousands of redundant
                    // PtyWakeup messages per second at unthrottled ingestion speeds.
                    if !dirty.swap(true, Ordering::AcqRel) {
                        let guard = status_cb.lock().unwrap_or_else(|err| err.into_inner());
                        if let Some(ref cb) = *guard {
                            cb(crate::PtyStatus::Wakeup);
                        }
                        // Reset budget because a new render cycle has begun
                        bytes_since_render = 0;
                    }

                    // I/O burst budget: when the reader has ingested more than
                    // IO_BURST_BUDGET bytes without a render, wait on the Condvar
                    // until the UI thread clears dirty. This prevents a single
                    // reader thread from consuming 100% CPU on infinite streams.
                    if bytes_since_render >= IO_BURST_BUDGET {
                        let (lock, cvar) = &*dirty_cond;
                        let mut guard = lock.lock().unwrap_or_else(|err| err.into_inner());
                        while dirty.load(Ordering::Acquire) {
                            guard = cvar.wait(guard).unwrap_or_else(|err| err.into_inner());
                        }
                        bytes_since_render = 0;
                    }

                    // Drain-sync: break at the starvation bound so a continuous
                    // stream (which never returns WouldBlock) still applies the
                    // pending resize and keeps the grid attached to the window.
                    #[cfg(unix)]
                    {
                        drain_bytes += n;
                        if drain_bytes >= MAX_DRAIN_BYTES {
                            break;
                        }
                    }

                    // Loop back to read() — no parking, no cloning, no render_ready check.
                    // Lock contention is expected under load: the reader will block
                    // on the mutex while the main thread holds it during render.
                    // This is intentional mechanical backpressure.
                }
                Err(err) => {
                    // Windows: `wake_reader` aborts the blocking ConPTY read via
                    // `CancelSynchronousIo`; the aborted `ReadFile` returns
                    // `ERROR_OPERATION_ABORTED` (995). That is a resize wake, not a
                    // fatal error — break to the drain boundary so the pending
                    // resize is applied. (On Unix `raw_os_error` can never be 995,
                    // so this branch is inert there.)
                    if err.raw_os_error() == Some(ERROR_OPERATION_ABORTED) {
                        break;
                    }
                    let guard = status_cb.lock().unwrap_or_else(|err| err.into_inner());
                    if let Some(ref cb) = *guard
                        && !exited_emitted.swap(true, Ordering::AcqRel)
                    {
                        cb(crate::PtyStatus::Exited);
                    }
                    break 'reader;
                }
            }
            // (Windows) one blocking read per outer iteration (no non-blocking drain
            // until the ConPTY handle is pollable — resizes apply at this boundary).
            #[cfg(windows)]
            {
                break;
            }
        }
        // DRAIN BOUNDARY — pipe empty (or starvation bound): apply any pending
        // resize here, so the grid is reflowed and SIGWINCH is delivered only
        // when the shell is not mid-write.
        let new_size = pending_resize
            .lock()
            .unwrap_or_else(|err| err.into_inner())
            .take();
        if let Some(new_size) = new_size {
            apply_resize(new_size, &shared_parser, &tracker, &master, &size);
        }
    }
}

/// Apply a drain-synchronized resize on the reader thread: reflow the vt100
/// grid (with the shrink `ESC[S` cursor push), update the tracker and the shared
/// size, then issue the OS resize (`ioctl` / SIGWINCH) — all so the grid width
/// never changes mid-shell-write.
fn apply_resize(
    new_size: PtySize,
    shared_parser: &Arc<Mutex<term_wm_vt100::Parser>>,
    tracker: &Arc<crate::PtyStateTracker>,
    master: &Arc<Mutex<Box<dyn MasterPty + Send>>>,
    size: &Arc<Mutex<PtySize>>,
) {
    let old_rows = {
        let parser = shared_parser.lock().unwrap_or_else(|err| err.into_inner());
        parser.screen().size().0
    };
    let mut guard = shared_parser.lock().unwrap_or_else(|err| err.into_inner());
    if new_size.rows < old_rows && !tracker.has_custom_margins() {
        let (cursor_row, _) = guard.screen().cursor_position();
        if cursor_row >= new_size.rows {
            let scroll_lines = cursor_row - new_size.rows + 1;
            let seq = format!("\x1b[{scroll_lines}S");
            guard.process(seq.as_bytes());
        }
    }
    guard.screen_mut().set_size(new_size.rows, new_size.cols);
    drop(guard);
    tracker.resize(new_size.rows);
    *size.lock().unwrap_or_else(|err| err.into_inner()) = new_size;
    if let Err(e) = master
        .lock()
        .unwrap_or_else(|err| err.into_inner())
        .resize(new_size)
    {
        tracing::warn!("drain-sync PTY resize failed: {e}");
    }
}

fn wrap_err<E: std::fmt::Display>(
    stage: &'static str,
    err: E,
) -> Box<dyn std::error::Error + Send + Sync> {
    Box::new(std::io::Error::other(format!("pty {stage} failed: {err}")))
}

fn bytes_to_debug_text(bytes: &[u8], max_len: usize) -> String {
    let mut out = String::new();
    for &b in bytes.iter().take(max_len) {
        match b {
            b'\r' => out.push_str("\\r"),
            b'\n' => out.push_str("\\n"),
            b'\t' => out.push_str("\\t"),
            0x20..=0x7e => out.push(b as char),
            _ => out.push_str(&format!("\\x{:02x}", b)),
        }
    }
    out
}

/// Get the process name for a given PID. On macOS uses `proc_name` from
/// libproc. On Linux reads `/proc/<pid>/comm`. On other platforms returns None.
#[cfg(target_os = "macos")]
fn get_process_name(pid: u32) -> Option<String> {
    let mut name = [0u8; PROC_NAME_BUF_SIZE];
    let result = unsafe {
        libc::proc_name(
            pid as libc::c_int,
            name.as_mut_ptr() as *mut libc::c_void,
            name.len() as u32,
        )
    };
    if result > 0 {
        let len = name.iter().position(|&b| b == 0).unwrap_or(name.len());
        Some(String::from_utf8_lossy(&name[..len]).into_owned())
    } else {
        None
    }
}

#[cfg(target_os = "linux")]
fn get_process_name(pid: u32) -> Option<String> {
    let path = format!("/proc/{pid}/comm");
    std::fs::read_to_string(&path)
        .ok()
        .map(|s| s.trim().to_string())
}

#[cfg(windows)]
fn get_process_name(pid: u32) -> Option<String> {
    use std::ffi::OsString;
    use std::os::windows::ffi::OsStringExt;

    const PROCESS_QUERY_LIMITED_INFORMATION: u32 = 0x1000;
    let handle = unsafe { kernel32::OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
    if handle == 0 {
        return None;
    }

    let mut buf = [0u16; 260];
    let mut size = buf.len() as u32;
    let result =
        unsafe { kernel32::QueryFullProcessImageNameW(handle, 0, buf.as_mut_ptr(), &mut size) };
    unsafe {
        kernel32::CloseHandle(handle);
    }

    if result == 0 {
        return None;
    }
    let path = OsString::from_wide(&buf[..size as usize]);
    std::path::Path::new(&path)
        .file_stem()
        .map(|s| s.to_string_lossy().into_owned())
}

#[cfg(windows)]
fn find_foreground_process_windows(shell_pid: u32) -> Option<u32> {
    let snapshot = unsafe { kernel32::CreateToolhelp32Snapshot(0x00000002, 0) };
    if snapshot == kernel32::INVALID_HANDLE_VALUE {
        return None;
    }

    let mut children: Vec<(u32, u32)> = Vec::new();
    let mut entry = std::mem::MaybeUninit::<kernel32::PROCESSENTRY32W>::zeroed();

    unsafe {
        (*entry.as_mut_ptr()).dwSize = std::mem::size_of::<kernel32::PROCESSENTRY32W>() as u32;
        if kernel32::Process32FirstW(snapshot, entry.as_mut_ptr()) != 0 {
            loop {
                let e = entry.assume_init();
                children.push((e.th32ProcessID, e.th32ParentProcessID));
                if kernel32::Process32NextW(snapshot, entry.as_mut_ptr()) == 0 {
                    break;
                }
            }
        }
        kernel32::CloseHandle(snapshot);
    }

    let mut current = shell_pid;
    loop {
        let next = children
            .iter()
            .find(|&&(pid, parent)| parent == current && pid != current)
            .map(|&(pid, _)| pid);
        match next {
            Some(next) => current = next,
            None => break,
        }
    }

    Some(current)
}

#[cfg(windows)]
mod kernel32 {
    pub const INVALID_HANDLE_VALUE: isize = -1;

    #[repr(C)]
    #[derive(Copy, Clone)]
    #[allow(non_snake_case)]
    pub struct PROCESSENTRY32W {
        pub dwSize: u32,
        pub cntUsage: u32,
        pub th32ProcessID: u32,
        pub th32DefaultHeapID: usize,
        pub th32ModuleID: u32,
        pub cntThreads: u32,
        pub th32ParentProcessID: u32,
        pub pcPriClassBase: i32,
        pub dwFlags: u32,
        pub szExeFile: [u16; 260],
    }

    #[allow(non_snake_case)]
    unsafe extern "system" {
        pub fn CreateToolhelp32Snapshot(dwFlags: u32, th32ProcessID: u32) -> isize;
        pub fn Process32FirstW(hSnapshot: isize, lppe: *mut PROCESSENTRY32W) -> i32;
        pub fn Process32NextW(hSnapshot: isize, lppe: *mut PROCESSENTRY32W) -> i32;
        pub fn CloseHandle(hObject: isize) -> i32;
        pub fn OpenProcess(dwDesiredAccess: u32, bInheritHandle: i32, dwProcessId: u32) -> isize;
        pub fn QueryFullProcessImageNameW(
            hProcess: isize,
            dwFlags: u32,
            lpExeName: *mut u16,
            lpdwSize: *mut u32,
        ) -> i32;
        /// Abort pending synchronous I/O issued by a thread — used to wake the
        /// reader out of a blocking ConPTY read on a resize request.
        pub fn CancelSynchronousIo(hThread: *mut std::ffi::c_void) -> i32;
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pty::StatusCallback;
    use std::io;
    #[cfg(windows)]
    use std::io::Cursor;
    use std::io::Write;
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
    use std::sync::{Arc, Mutex, RwLock};

    /// Returns a platform-appropriate dummy executable for PTY plumbing tests.
    /// On Unix, `cat` blocks on stdin and echoes output. On Windows, `cmd.exe`
    /// blocks on stdin and keeps the ConPTY alive.
    fn get_test_executable() -> &'static str {
        #[cfg(target_os = "windows")]
        {
            "cmd.exe"
        }
        #[cfg(not(target_os = "windows"))]
        {
            "cat"
        }
    }

    /// Locate the `term-session-mock` binary so the Job Object test can spawn
    /// a child that itself forks a grandchild. Resolution is delegated to the
    /// shared helper in the mock crate's library (see
    /// `term_session_mock::get_mock_bin`), which is a dev-dependency of this
    /// crate so the binary is always built for tests.
    #[cfg(windows)]
    fn get_mock_bin() -> std::path::PathBuf {
        term_session_mock::get_mock_bin()
    }

    // ── bytes_to_debug_text ──────────────────────────────────────────

    #[test]
    fn bytes_to_debug_text_empty() {
        assert_eq!(bytes_to_debug_text(b"", 32), "");
    }

    #[test]
    fn bytes_to_debug_text_printable_passthrough() {
        assert_eq!(bytes_to_debug_text(b"hello world", 32), "hello world");
    }

    #[test]
    fn bytes_to_debug_text_encodes_control_and_nonprint() {
        let data = b"a\nb\tc\r\x01\xff";
        let s = bytes_to_debug_text(data, 32);
        assert!(s.contains("a\\nb\\tc\\r"));
        assert!(s.contains("\\x01"));
        assert!(s.contains("\\xff"));
    }

    #[test]
    fn bytes_to_debug_text_truncates_at_max_len() {
        let long = b"abcdefghijklmnopqrstuvwxyz";
        assert_eq!(bytes_to_debug_text(long, 5).len(), 5);
    }

    #[test]
    fn bytes_to_debug_text_short_max_len() {
        let s = bytes_to_debug_text(b"hello", 0);
        assert_eq!(s, "");
    }

    #[test]
    fn bytes_to_debug_text_all_control_chars() {
        let data: Vec<u8> = (0..32).collect();
        let s = bytes_to_debug_text(&data, 64);
        // Characters 0x00-0x08, 0x0b-0x1f use \xNN; 0x09=\t, 0x0a=\n, 0x0d=\r
        for i in 0..32u8 {
            let expected = match i {
                0x09 => 't',
                0x0a => 'n',
                0x0d => 'r',
                _ => continue,
            };
            assert!(
                s.contains(&format!("\\{}", expected)),
                "missing named escape for 0x{i:02x}"
            );
        }
        // Verify a few non-special controls use \xNN format
        assert!(s.contains("\\x00"));
        assert!(s.contains("\\x01"));
        assert!(s.contains("\\x1b"));
        assert!(s.contains("\\x1f"));
    }

    // ── parser_read_loop ─────────────────────────────────────────────
    fn make_parser_test_args(payload: &[u8]) -> ParserReadLoopArgs {
        // A real PTY is required so the drain-synchronized reader loop can poll
        // the master fd. On Unix the payload is produced by a `printf` child
        // written to the slave (child output direction → master reader), which
        // then exits to EOF the loop. On Windows the loop is the non-polling
        // fallback, so a synchronous Cursor reader works.
        let pty_system = native_pty_system();
        let pair = pty_system
            .openpty(PtySize {
                rows: 24,
                cols: 80,
                pixel_width: 0,
                pixel_height: 0,
            })
            .expect("openpty");
        #[cfg(unix)]
        let reader = {
            // Escape the payload for `sh -c 'printf …'` so it is written to the
            // slave verbatim; the child exits immediately afterward.
            let mut escaped = String::from("printf '");
            for &b in payload {
                match b {
                    b'\'' => escaped.push_str("'\\''"),
                    0x1b => escaped.push_str("\\033"),
                    b'\n' => escaped.push_str("\\n"),
                    b'\r' => escaped.push_str("\\r"),
                    b'\t' => escaped.push_str("\\t"),
                    0x20..=0x7e => escaped.push(b as char),
                    _ => escaped.push_str(&format!("\\{:03o}", b)),
                }
            }
            escaped.push('\'');
            let mut builder = CommandBuilder::new("sh");
            builder.arg("-c");
            builder.arg(escaped);
            let _child = pair
                .slave
                .spawn_command(builder)
                .expect("spawn printf child");
            pair.master.try_clone_reader().expect("reader")
        };
        #[cfg(windows)]
        let reader = Box::new(Cursor::new(payload.to_vec()));
        let master = Arc::new(Mutex::new(pair.master));
        drop(pair.slave);
        #[cfg(unix)]
        let wake_read_fd = {
            // Keep the wake pipe alive for the reader's poll set; dropping it
            // here would close the fd and make `poll` return POLLNVAL (busy-spin).
            let wake = Box::leak(Box::new(ResizeWake::new().expect("resize wake")));
            wake.read_fd()
        };
        ParserReadLoopArgs {
            reader,
            pending: Arc::new(Mutex::new(Vec::new())),
            bytes_received: Arc::new(AtomicUsize::new(0)),
            last_bytes: Arc::new(Mutex::new(Vec::new())),
            dsr_requested: Arc::new(AtomicBool::new(false)),
            shared_parser: Arc::new(Mutex::new(term_wm_vt100::Parser::new(24, 80, 0))),
            dirty: Arc::new(AtomicBool::new(false)),
            dirty_cond: Arc::new((Mutex::new(()), Condvar::new())),
            pending_title: Arc::new(Mutex::new(None)),
            status_cb: Arc::new(Mutex::new(None)),
            scrollback_len: 0,
            exited_emitted: Arc::new(AtomicBool::new(false)),
            osc52_text: None,
            clipboard: None,
            tracker: std::sync::Arc::new(crate::PtyStateTracker::new(24)),
            master,
            size: Arc::new(Mutex::new(PtySize {
                rows: 24,
                cols: 80,
                pixel_width: 0,
                pixel_height: 0,
            })),
            pending_resize: Arc::new(Mutex::new(None)),
            #[cfg(unix)]
            wake_read_fd,
            shutdown: Arc::new(AtomicBool::new(false)),
        }
    }

    #[test]
    fn parser_read_loop_reads_and_sets_pending_and_last() {
        let payload = b"hello\r\n\x1b[6nworld";
        let args = make_parser_test_args(payload);
        let pending = Arc::clone(&args.pending);
        let bytes_received = Arc::clone(&args.bytes_received);
        let last_bytes = Arc::clone(&args.last_bytes);
        let dsr_requested = Arc::clone(&args.dsr_requested);
        let dirty = Arc::clone(&args.dirty);

        parser_read_loop(args);

        let p = pending.lock().unwrap();
        assert!(!p.is_empty());
        assert!(bytes_received.load(Ordering::Relaxed) > 0);
        let last = last_bytes.lock().unwrap();
        assert!(!last.is_empty());
        assert!(dsr_requested.load(Ordering::Relaxed));
        assert!(dirty.load(Ordering::Relaxed));
    }

    #[test]
    fn parser_read_loop_empty_input() {
        let args = make_parser_test_args(b"");
        let pending = Arc::clone(&args.pending);
        let bytes_received = Arc::clone(&args.bytes_received);
        let last_bytes = Arc::clone(&args.last_bytes);
        let dsr_requested = Arc::clone(&args.dsr_requested);
        let dirty = Arc::clone(&args.dirty);

        parser_read_loop(args);

        let p = pending.lock().unwrap();
        assert!(p.is_empty());
        assert_eq!(bytes_received.load(Ordering::Relaxed), 0);
        let last = last_bytes.lock().unwrap();
        assert!(last.is_empty());
        assert!(!dsr_requested.load(Ordering::Relaxed));
        assert!(!dirty.load(Ordering::Relaxed));
    }

    /// Regression: the emulator term-wm builds against must honor DECAWM
    /// (`ESC[?7l`, autowrap off). Feeding `\x1b[?7l` + 85 chars through the
    /// production ingestion loop (`parser_read_loop`) must clamp the cursor to
    /// the right margin instead of wrapping onto the next row. Guards the
    /// workspace-level integration point: without DECAWM support the emulator
    /// would ignore the toggle and wrap the 81st character to row 1, failing
    /// these assertions.
    #[test]
    fn parser_read_loop_decawn_off_does_not_wrap() {
        let mut payload = Vec::new();
        payload.extend_from_slice(b"\x1b[?7l");
        payload.extend_from_slice(&[b'x'; 85]);
        let args = make_parser_test_args(&payload);
        let shared = Arc::clone(&args.shared_parser);

        parser_read_loop(args);

        let parser = shared.lock().unwrap();
        let screen = parser.screen();
        assert_eq!(
            screen.cursor_position(),
            (0, 79),
            "DECAWM off must clamp the cursor to the right margin"
        );
        assert_eq!(
            screen.cell(0, 79).unwrap().contents(),
            "x",
            "the 85th char must overwrite the margin cell, not wrap"
        );
        assert!(
            (0..80).all(|col| screen
                .cell(1, col)
                .is_none_or(|cell| cell.contents().is_empty())),
            "row 1 must remain empty (no wrap)"
        );
    }

    /// Regression: pico inserts characters mid-line using IRM insert mode
    /// (`CSI 4 h` ... char ... `CSI 4 l`). If the emulator ignores insert mode,
    /// the char OVERWRITES the existing cell instead of shifting the row right
    /// ("types over existing characters" on a wrapped line). Replay pico's
    /// exact insert sequence through the production ingestion loop.
    #[test]
    fn parser_read_loop_insert_mode_inserts() {
        // "hello", move to col 2 (1-based) → (0,1) 0-based, enable IRM, insert 'X'.
        let args = make_parser_test_args(b"hello\x1b[1;2H\x1b[4hX\x1b[4l");
        let shared = Arc::clone(&args.shared_parser);

        parser_read_loop(args);

        let parser = shared.lock().unwrap();
        let screen = parser.screen();
        assert_eq!(screen.cell(0, 1).unwrap().contents(), "X", "inserted char");
        assert_eq!(
            screen.cell(0, 2).unwrap().contents(),
            "e",
            "existing text must shift right, not be overwritten"
        );
        assert_eq!(
            screen.cell(0, 5).unwrap().contents(),
            "o",
            "row tail preserved"
        );
    }

    #[test]
    fn parser_read_loop_status_callback_called_when_set() {
        let args = make_parser_test_args(b"data");
        let woke = Arc::new(AtomicBool::new(false));
        let woke_clone = Arc::clone(&woke);
        if let Ok(mut guard) = args.status_cb.lock() {
            *guard = Some(Box::new(move |status| {
                if status == crate::PtyStatus::Wakeup {
                    woke_clone.store(true, Ordering::Relaxed);
                }
            }));
        }

        parser_read_loop(args);

        assert!(
            woke.load(Ordering::Relaxed),
            "status callback must be invoked on wakeup"
        );
    }

    #[test]
    fn parser_read_loop_tracks_tail_for_cross_boundary_dsr() {
        let args = make_parser_test_args(b"XX\x1b[6nYY");
        let dsr_requested = Arc::clone(&args.dsr_requested);

        parser_read_loop(args);

        assert!(
            dsr_requested.load(Ordering::Relaxed),
            "DSR in combined data must be detected"
        );
    }

    #[test]
    fn parser_read_loop_relays_osc52_to_isolated_clipboard_and_hook() {
        // Inject a headless clipboard backed by an isolated shared in-memory
        // buffer so the relay is deterministic and the real system clipboard
        // / process-global default buffer are never touched.
        let shared = Arc::new(RwLock::new(None));
        let mut args = make_parser_test_args(&term_clipboard::format_osc52_bytes("clip via pty"));
        args.clipboard = Some(Clipboard::with_shared_buffer(Arc::clone(&shared)));
        let captured = Arc::new(Mutex::new(None));
        args.osc52_text = Some(Arc::clone(&captured));

        parser_read_loop(args);

        let captured = captured.lock().unwrap();
        assert_eq!(
            captured.as_deref(),
            Some("clip via pty"),
            "osc52_text hook must capture the relayed payload"
        );
        // The shared buffer must hold the relayed text, proving set() ran
        // without touching the real system clipboard.
        assert_eq!(
            *shared.read().unwrap(),
            Some("clip via pty".to_string()),
            "relayed set() must have written the shared in-memory buffer"
        );
    }

    #[test]
    fn set_status_callback_fires_from_spawn() {
        // Use cat, which blocks on input, so we control when output happens.
        // Portability: `cat` exists on Unix; on Windows the test is skipped.
        let cmd = CommandBuilder::new(get_test_executable());
        let size = PtySize {
            rows: 24,
            cols: 80,
            pixel_width: 0,
            pixel_height: 0,
        };
        let mut pty = Pty::spawn_with_scrollback(cmd, size, 100).expect("spawn_with_scrollback");

        let woke = Arc::new(AtomicBool::new(false));
        let woke_cb = Arc::clone(&woke);
        pty.set_status_callback(Some(Box::new(move |status| {
            if status == crate::PtyStatus::Wakeup {
                woke_cb.store(true, Ordering::Relaxed);
            }
        })));

        // Write to the PTY — terminal echo triggers a read on the master
        // side, which the reader thread processes and fires the callback.
        let _ = pty.write_str("hello\n");

        // Wait for callback with timeout (up to 5s)
        for _ in 0..250 {
            if woke.load(Ordering::Relaxed) {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(20));
        }

        // Clean up
        if let Some(child) = pty.child.as_mut() {
            let _ = child.kill();
        }

        assert!(
            woke.load(Ordering::Relaxed),
            "status callback must fire on Wakeup when PTY outputs data"
        );
    }

    #[test]
    #[cfg(windows)]
    fn spawn_assigns_job_object_containing_child() {
        // The Windows child must be contained in a Job Object so kill paths
        // terminate the whole tree (grandchildren included), not just the
        // session leader. We spawn the mock in `spawn_child` mode: it forks a
        // grandchild (another mock instance in `sleep` mode) and prints
        // `GRANDCHILD_PID:<n>` to stdout. We read that PID, confirm the
        // grandchild is alive, kill the child via `kill_child` (which calls
        // `TerminateJobObject`), and confirm the grandchild died too — the
        // whole-tree guarantee.
        let mock = get_mock_bin();
        let mut cmd = CommandBuilder::new(mock);
        cmd.arg("spawn_child");
        cmd.arg("60000");
        let size = PtySize {
            rows: 24,
            cols: 80,
            pixel_width: 0,
            pixel_height: 0,
        };
        let mut pty = Pty::spawn_with_scrollback(cmd, size, 100).expect("spawn_with_scrollback");

        assert!(
            pty.job.is_some(),
            "spawned child must be contained in a Job Object on Windows"
        );

        // Poll `screen()` — which answers the child's startup DSR
        // cursor-position request — while accumulating output until the
        // `GRANDCHILD_PID:` marker appears.
        let mut accumulated = Vec::new();
        let start = std::time::Instant::now();
        let grandchild = loop {
            pty.screen();
            accumulated.extend_from_slice(&pty.drain_pending());
            if let Some(idx) = accumulated
                .windows(b"GRANDCHILD_PID:".len())
                .position(|w| w == b"GRANDCHILD_PID:")
            {
                let rest = &accumulated[idx + b"GRANDCHILD_PID:".len()..];
                let pid_str: String = rest
                    .iter()
                    .take_while(|b| b.is_ascii_digit())
                    .map(|b| *b as char)
                    .collect();
                break pid_str
                    .parse()
                    .unwrap_or_else(|_| panic!("invalid grandchild PID in {rest:?}"));
            }
            assert!(
                start.elapsed() < std::time::Duration::from_secs(5),
                "mock spawn_child should print a grandchild PID; got {accumulated:?}"
            );
            std::thread::sleep(std::time::Duration::from_millis(20));
        };

        // The grandchild must be alive before the kill.
        assert!(
            term_session_mock::process_is_alive(grandchild),
            "grandchild {grandchild} should be alive before kill_child"
        );

        // kill_child must consume the job (its Drop then fires
        // KILL_ON_JOB_CLOSE for any stragglers) and reap the child.
        pty.kill_child().expect("kill_child");
        assert!(pty.job.is_none(), "job must be taken on kill_child");
        assert!(pty.child.is_none(), "child must be reaped on kill_child");
        assert!(pty.exited, "pty must be marked exited after kill_child");

        // The grandchild must die with the tree — the whole point of the
        // Job Object containment. Poll briefly since termination is async.
        let start = std::time::Instant::now();
        while term_session_mock::process_is_alive(grandchild) {
            assert!(
                start.elapsed() < std::time::Duration::from_secs(5),
                "grandchild {grandchild} should be dead after kill_child"
            );
            std::thread::sleep(std::time::Duration::from_millis(20));
        }
    }

    #[test]
    fn has_exited_fires_exited_callback_when_child_dies() {
        let cmd = CommandBuilder::new(get_test_executable());
        let size = PtySize {
            rows: 24,
            cols: 80,
            pixel_width: 0,
            pixel_height: 0,
        };
        let mut pty = Pty::spawn_with_scrollback(cmd, size, 100).expect("spawn_with_scrollback");

        let exited_fired = Arc::new(AtomicBool::new(false));
        let exited_cb = Arc::clone(&exited_fired);
        pty.set_status_callback(Some(Box::new(move |status| {
            if status == crate::PtyStatus::Exited {
                exited_cb.store(true, Ordering::Relaxed);
            }
        })));

        // Kill the child so try_wait returns Ok(Some(...))
        if let Some(child) = pty.child.as_mut() {
            let _ = child.kill();
        }

        // Wait for child to be reaped
        for _ in 0..250 {
            if pty.has_exited() {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(20));
        }

        assert!(
            exited_fired.load(Ordering::Relaxed),
            "has_exited() must fire PtyStatus::Exited callback when child dies"
        );
    }

    #[test]
    fn has_exited_idempotent_after_child_exits() {
        let cmd = CommandBuilder::new(get_test_executable());
        let size = PtySize {
            rows: 24,
            cols: 80,
            pixel_width: 0,
            pixel_height: 0,
        };
        let mut pty = Pty::spawn_with_scrollback(cmd, size, 100).expect("spawn_with_scrollback");

        let exit_count = Arc::new(AtomicUsize::new(0));
        let count_cb = Arc::clone(&exit_count);
        pty.set_status_callback(Some(Box::new(move |status| {
            if status == crate::PtyStatus::Exited {
                count_cb.fetch_add(1, Ordering::Relaxed);
            }
        })));

        // Kill the child
        if let Some(child) = pty.child.as_mut() {
            let _ = child.kill();
        }

        // Wait for first has_exited to succeed
        for _ in 0..250 {
            if pty.has_exited() {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(20));
        }

        // Record count after has_exited() first returned true
        let count_after_first = exit_count.load(Ordering::Relaxed);

        // Call has_exited() again — must NOT fire the callback
        assert!(pty.has_exited(), "second call must also return true");

        std::thread::sleep(std::time::Duration::from_millis(100));
        let count_after_second = exit_count.load(Ordering::Relaxed);
        assert_eq!(
            count_after_first, count_after_second,
            "has_exited() must not re-fire the Exited callback after returning true"
        );
    }

    // ── set_status_callback with pre-exited child ────────────────────

    #[test]
    fn set_status_callback_fires_when_child_already_exited() {
        let cmd = CommandBuilder::new(get_test_executable());
        let size = PtySize {
            rows: 24,
            cols: 80,
            pixel_width: 0,
            pixel_height: 0,
        };
        let mut pty = Pty::spawn_with_scrollback(cmd, size, 100).expect("spawn_with_scrollback");

        // Kill and reap the child process, consuming the latch via has_exited().
        if let Some(child) = pty.child.as_mut() {
            let _ = child.kill();
        }
        for _ in 0..250 {
            if pty.has_exited() {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(20));
        }

        let exited_fired = Arc::new(AtomicBool::new(false));
        let exited_cb = Arc::clone(&exited_fired);

        // Register a new callback — must fire immediately (self.exited branch
        // with latch reset).
        pty.set_status_callback(Some(Box::new(move |status| {
            if status == PtyStatus::Exited {
                exited_cb.store(true, Ordering::Relaxed);
            }
        })));

        assert!(
            exited_fired.load(Ordering::Relaxed),
            "set_status_callback must fire PtyStatus::Exited when child already exited"
        );
    }

    #[test]
    fn set_status_callback_fires_via_try_wait_after_direct_kill() {
        let cmd = CommandBuilder::new(get_test_executable());
        let size = PtySize {
            rows: 24,
            cols: 80,
            pixel_width: 0,
            pixel_height: 0,
        };
        let mut pty = Pty::spawn_with_scrollback(cmd, size, 100).expect("spawn_with_scrollback");

        // Kill the child but do NOT call has_exited() — let the try_wait()
        // path in set_status_callback detect the exit.
        if let Some(child) = pty.child.as_mut() {
            let _ = child.kill();
        }
        for _ in 0..250 {
            if let Some(Ok(Some(_))) = pty.child.as_mut().map(|c| c.try_wait()) {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(20));
        }

        let exited_fired = Arc::new(AtomicBool::new(false));
        let exited_cb = Arc::clone(&exited_fired);

        pty.set_status_callback(Some(Box::new(move |status| {
            if status == PtyStatus::Exited {
                exited_cb.store(true, Ordering::Relaxed);
            }
        })));

        assert!(
            exited_fired.load(Ordering::Relaxed),
            "set_status_callback must fire PtyStatus::Exited via try_wait() when child killed"
        );
    }

    // ── screen / set_scrollback / into_parts / Drop ─────────────────
    //
    // These tests exercise the shared-parser screen sharing path (sync
    // with dirty=true), the set_scrollback mutation path, the into_parts()
    // shutdown signaling, and the Drop impl.  They use a real Pty spawned
    // with `cat` so the reader thread is alive.

    #[test]
    fn screen_loads_from_shared_parser_when_dirty() {
        let cmd = CommandBuilder::new(get_test_executable());
        let size = PtySize {
            rows: 24,
            cols: 80,
            pixel_width: 0,
            pixel_height: 0,
        };
        let mut pty = Pty::spawn_with_scrollback(cmd, size, 100).expect("spawn_with_scrollback");

        // Initially dirty is false — sync clears it.
        pty.screen();

        // Simulate reader thread publishing a new screen via shared parser.
        let mut new_parser = term_wm_vt100::Parser::new(24, 80, 100);
        new_parser.process(b"hello world");
        {
            let mut shared = pty.shared_parser.lock().unwrap();
            *shared = new_parser;
        }
        pty.dirty.store(true, Ordering::Release);

        // screen() should clear dirty.
        pty.screen();

        // Verify content is from the new screen by reading directly from the parser.
        {
            let parser = pty.shared_parser.lock().unwrap();
            if let Some(cell) = parser.screen().cell(0, 0) {
                let contents = cell.contents();
                assert!(
                    contents.contains('h'),
                    "expected 'h' from new screen, got {contents:?}"
                );
            }
        }

        assert!(!pty.dirty.load(Ordering::Acquire), "dirty must be cleared");

        // Clean up: kill child so the reader thread exits.
        if let Some(child) = pty.child.as_mut() {
            let _ = child.kill();
        }
    }

    #[test]
    fn screen_syncs_from_shared_parser() {
        let cmd = CommandBuilder::new(get_test_executable());
        let size = PtySize {
            rows: 24,
            cols: 80,
            pixel_width: 0,
            pixel_height: 0,
        };
        let mut pty = Pty::spawn_with_scrollback(cmd, size, 100).expect("spawn_with_scrollback");

        // Publish a new screen via shared parser.
        let mut new_parser = term_wm_vt100::Parser::new(24, 80, 100);
        new_parser.process(b"content");
        {
            let mut shared = pty.shared_parser.lock().unwrap();
            *shared = new_parser;
        }
        pty.dirty.store(true, Ordering::Release);

        // Sync dirty state.
        pty.screen();

        // Verify content from the new screen is accessible via the shared parser.
        {
            let parser = pty.shared_parser.lock().unwrap();
            let cell = parser.screen().cell(0, 0);
            assert!(cell.is_some(), "expected a cell at (0,0)");
            assert_eq!(cell.unwrap().contents(), "c");
        }

        // Clean up.
        if let Some(child) = pty.child.as_mut() {
            let _ = child.kill();
        }
    }

    #[test]
    fn set_scrollback_mutation_visible_through_scrollback_and_screen() {
        // Regression test: set_scrollback must mutate the shared parser's screen,
        // and scrollback() must read from the same parser.
        //
        // Generate enough output (30 lines in a 24-row terminal) to fill the
        // scrollback buffer so that set_scrollback(N) isn't clamped to 0.
        let cmd = CommandBuilder::new(get_test_executable());
        let size = PtySize {
            rows: 24,
            cols: 80,
            pixel_width: 0,
            pixel_height: 0,
        };
        let mut pty = Pty::spawn_with_scrollback(cmd, size, 100).expect("spawn_with_scrollback");

        // Consume any initial dirty.
        pty.screen();

        // Publish a screen with enough content to fill scrollback.
        // 30 lines in a 24-row terminal → 6 lines in the scrollback buffer.
        let mut lines = Vec::new();
        for i in 0..30 {
            writeln!(lines, "line {}", i).unwrap();
        }
        let mut parser = term_wm_vt100::Parser::new(24, 80, 100);
        parser.process(&lines);
        {
            let mut shared = pty.shared_parser.lock().unwrap();
            *shared = parser;
        }
        pty.dirty.store(true, Ordering::Release);

        // Sync.
        pty.screen();

        // Start at bottom (scrollback == 0).
        assert_eq!(pty.scrollback(), 0);

        // set_scrollback mutates the shared parser's screen directly.
        let sb_available = pty.max_scrollback();
        assert!(
            sb_available >= 3,
            "need at least 3 scrollback lines, got {sb_available}"
        );
        pty.set_scrollback(3);

        // scrollback() reads from the shared parser — must see the mutation.
        assert_eq!(
            pty.scrollback(),
            3,
            "scrollback() must reflect set_scrollback"
        );

        // Verify the shared parser's screen reflects the mutation.
        {
            let shared = pty.shared_parser.lock().unwrap();
            assert_eq!(
                shared.screen().scrollback(),
                3,
                "shared parser's screen must reflect set_scrollback"
            );
        }

        // Mutation survives subsequent sync calls.
        pty.screen();
        assert_eq!(
            pty.scrollback(),
            3,
            "mutation must survive repeated screen() calls without new data"
        );

        // New shared parser data replaces the mutation (expected).
        let mut parser2 = term_wm_vt100::Parser::new(24, 80, 100);
        parser2.process(b"fresh output");
        {
            let mut shared = pty.shared_parser.lock().unwrap();
            *shared = parser2;
        }
        pty.dirty.store(true, Ordering::Release);
        pty.screen();

        assert_eq!(
            pty.scrollback(),
            0,
            "new screen data must reset scrollback to its value"
        );

        // Clean up.
        if let Some(child) = pty.child.as_mut() {
            let _ = child.kill();
        }
    }

    #[test]
    fn set_scrollback_and_scrollback_consistent() {
        // set_scrollback() and scrollback() both operate on the shared parser.
        // Mutations via set_scrollback must be visible through scrollback().
        let cmd = CommandBuilder::new(get_test_executable());
        let size = PtySize {
            rows: 24,
            cols: 80,
            pixel_width: 0,
            pixel_height: 0,
        };
        let mut pty = Pty::spawn_with_scrollback(cmd, size, 100).expect("spawn_with_scrollback");

        // Sync.
        pty.screen();

        // Publish and load a screen with scrollback content (30 lines).
        let mut lines = Vec::new();
        for i in 0..30 {
            writeln!(lines, "line {}", i).unwrap();
        }
        let mut parser = term_wm_vt100::Parser::new(24, 80, 100);
        parser.process(&lines);
        {
            let mut shared = pty.shared_parser.lock().unwrap();
            *shared = parser;
        }
        pty.dirty.store(true, Ordering::Release);
        pty.screen();

        assert!(
            pty.max_scrollback() >= 3,
            "need enough scrollback for this test"
        );

        // Mutate via set_scrollback.
        pty.set_scrollback(3);

        // scrollback() must see the mutation.
        assert_eq!(
            pty.scrollback(),
            3,
            "scrollback() must see mutation made via set_scrollback"
        );

        // Mutate again.
        pty.set_scrollback(5);

        assert_eq!(
            pty.scrollback(),
            5,
            "scrollback() must see mutation made via set_scrollback"
        );

        // Clean up.
        if let Some(child) = pty.child.as_mut() {
            let _ = child.kill();
        }
    }

    #[test]
    fn into_parts_takes_child_and_reader() {
        let cmd = CommandBuilder::new(get_test_executable());
        let size = PtySize {
            rows: 24,
            cols: 80,
            pixel_width: 0,
            pixel_height: 0,
        };
        let mut pty = Pty::spawn_with_scrollback(cmd, size, 100).expect("spawn_with_scrollback");

        assert!(
            pty.reader_is_alive(),
            "reader should be alive before into_parts"
        );

        let parts = pty.into_parts();
        assert!(parts.child.is_some(), "child should be taken");
        assert!(
            parts.reader_handle.is_some(),
            "reader handle should be taken"
        );
        assert!(
            !pty.reader_is_alive(),
            "reader should be dead after into_parts"
        );
        assert!(pty.child.is_none(), "child should be None after into_parts");
    }

    #[test]
    fn set_status_callback_with_existing_reader_does_not_panic() {
        let cmd = CommandBuilder::new(get_test_executable());
        let size = PtySize {
            rows: 24,
            cols: 80,
            pixel_width: 0,
            pixel_height: 0,
        };
        let mut pty = Pty::spawn_with_scrollback(cmd, size, 100).expect("spawn_with_scrollback");

        pty.set_status_callback(Some(Box::new(|_| {})));

        // Also test clearing the callback.
        pty.set_status_callback(None);

        if let Some(child) = pty.child.as_mut() {
            let _ = child.kill();
        }
    }

    // ── wrap_err ────────────────────────────────────────────────────

    #[test]
    fn wrap_err_with_string() {
        let e = wrap_err("openpty", "permission denied");
        let s = format!("{}", e);
        assert!(s.contains("pty openpty failed: permission denied"));
    }

    #[test]
    fn wrap_err_with_io_error() {
        let io_err = io::Error::new(io::ErrorKind::NotFound, "file not found");
        let e = wrap_err("resize", io_err);
        let s = format!("{}", e);
        assert!(s.contains("pty resize failed"));
        assert!(s.contains("file not found"));
    }

    #[test]
    fn wrap_err_with_integer() {
        let e = wrap_err("spawn_command", 42);
        let s = format!("{}", e);
        assert!(s.contains("pty spawn_command failed: 42"));
    }

    #[test]
    fn take_pending_title_clones_foreground_not_consumes() {
        let cmd = CommandBuilder::new(get_test_executable());
        let size = PtySize {
            rows: 24,
            cols: 80,
            pixel_width: 0,
            pixel_height: 0,
        };
        let mut pty = Pty::spawn_with_scrollback(cmd, size, 100).expect("spawn");

        *pty.foreground_title.lock().unwrap() = Some("vim".to_string());

        assert_eq!(pty.take_pending_title(), Some("vim".to_string()));
        assert_eq!(pty.take_pending_title(), Some("vim".to_string()));

        if let Some(child) = pty.child.as_mut() {
            let _ = child.kill();
        }
    }

    #[test]
    fn take_pending_title_purges_stale_osc_when_fg_present() {
        let cmd = CommandBuilder::new(get_test_executable());
        let size = PtySize {
            rows: 24,
            cols: 80,
            pixel_width: 0,
            pixel_height: 0,
        };
        let mut pty = Pty::spawn_with_scrollback(cmd, size, 100).expect("spawn");

        *pty.foreground_title.lock().unwrap() = Some("vim".to_string());
        *pty.pending_title.lock().unwrap() = Some("user@host".to_string());

        assert_eq!(pty.take_pending_title(), Some("vim".to_string()));
        assert_eq!(
            *pty.pending_title.lock().unwrap(),
            None,
            "stale OSC title must be purged"
        );

        if let Some(child) = pty.child.as_mut() {
            let _ = child.kill();
        }
    }

    #[test]
    fn take_pending_title_falls_back_to_osc_when_no_fg() {
        let cmd = CommandBuilder::new(get_test_executable());
        let size = PtySize {
            rows: 24,
            cols: 80,
            pixel_width: 0,
            pixel_height: 0,
        };
        let mut pty = Pty::spawn_with_scrollback(cmd, size, 100).expect("spawn");

        *pty.foreground_title.lock().unwrap() = None;
        *pty.pending_title.lock().unwrap() = Some("user@host".to_string());

        assert_eq!(pty.take_pending_title(), Some("user@host".to_string()));
        assert_eq!(
            *pty.pending_title.lock().unwrap(),
            None,
            "OSC title must be consumed"
        );

        if let Some(child) = pty.child.as_mut() {
            let _ = child.kill();
        }
    }

    #[test]
    fn take_pending_title_returns_none_when_both_empty() {
        let cmd = CommandBuilder::new(get_test_executable());
        let size = PtySize {
            rows: 24,
            cols: 80,
            pixel_width: 0,
            pixel_height: 0,
        };
        let mut pty = Pty::spawn_with_scrollback(cmd, size, 100).expect("spawn");

        *pty.foreground_title.lock().unwrap() = None;
        *pty.pending_title.lock().unwrap() = None;

        assert_eq!(pty.take_pending_title(), None);

        if let Some(child) = pty.child.as_mut() {
            let _ = child.kill();
        }
    }

    // ── resize / set_size ──────────────────────────────────────────

    #[test]
    fn history_replay_corrupts_percent_lines_via_ansi_cursor_movements() {
        // The old resize replayed ALL accumulated history through a new
        // parser at the smaller width.  The raw PTY byte stream from a real
        // session contains ANSI escape sequences (cursor positioning, clear
        // screen, scroll regions) that were generated at the old width.
        //
        // When replayed at a smaller width, long lines wrap to multiple rows,
        // shifting everything after them.  Absolute cursor positioning that
        // was correct at the old width now lands on wrong rows, causing the
        // SAME `%` character to appear at multiple screen positions.
        // set_size avoids this by operating on the existing cell grid.

        // Simulate command output: each iteration writes a long line (with
        // `%`) at a specific absolute row using \x1b[row;colH.  At 80 cols
        // each line fits on one row.  At 30 cols each line wraps to ~3 rows,
        // so the absolute row positions overlap with prior wrapped content.
        let mut history = Vec::new();
        for i in 0..5 {
            // Place a 65-char line with `%` at absolute row i+1.
            // When replayed at 30 cols this wraps to 3 rows,
            // pushing subsequent content down.
            writeln!(history, "\x1b[{};1Hline {}: {} %", i + 1, i, "x".repeat(52)).unwrap();
        }

        // ── OLD: create parser at 30 cols, replay all history ──
        let mut old = term_wm_vt100::Parser::new(24, 30, 100);
        old.process(&history);
        let old_text = old.screen().contents();

        // ── NEW: process at 80 cols, then set_size to 30 ──
        let mut new = term_wm_vt100::Parser::new(24, 80, 100);
        new.process(&history);
        new.screen_mut().set_size(24, 30);
        let new_text = new.screen().contents();

        // History-replay re-interprets cursor positioning at 30 cols where
        // each line wraps to ~3 rows.  Absolute references like \x1b[2;1H
        // land inside wrapped continuations, jamming all 5 lines into 1 row.
        assert_eq!(
            old_text.lines().count(),
            1,
            "history-replay must collapse all lines into one row"
        );
        assert_eq!(
            new_text.lines().count(),
            5,
            "set_size must preserve all 5 logical lines (via reflow)"
        );
    }

    #[test]
    fn reflow_preserves_scrollback_content_on_width_shrink() {
        // Reflow must preserve previously-buffered scrollback content when the
        // terminal width shrinks (the non-alt-screen resize case), instead of
        // truncating the wrapped rows of a long line.
        //
        // The reflow logic lives in the `term-wm-vt100` fork, whose own test
        // suite (including `reflow_preserves_scrollback_content`) runs in that
        // fork's repository, not here. This test is a local regression guard
        // against a future version of the fork losing the behavior.
        let mut parser = term_wm_vt100::Parser::new(24, 80, 2000);
        let long_line = "x".repeat(200);
        for i in 0..40 {
            parser.process(format!("line {i}: {}\r\n", long_line).as_bytes());
        }

        // Count every written character across the whole scrollback + screen.
        let count_chars =
            |parser: &mut term_wm_vt100::Parser| -> std::collections::BTreeMap<char, usize> {
                let (rows, cols) = parser.screen().size();
                parser.screen_mut().set_scrollback(usize::MAX);
                let sb = parser.screen().scrollback();
                let mut map = std::collections::BTreeMap::new();
                for i in 0..sb {
                    parser.screen_mut().set_scrollback(sb - i);
                    for c in 0..cols {
                        if let Some(cell) = parser.screen().cell(0, c) {
                            for ch in cell.contents().chars() {
                                *map.entry(ch).or_insert(0) += 1;
                            }
                        }
                    }
                }
                parser.screen_mut().set_scrollback(0);
                for r in 0..rows {
                    for c in 0..cols {
                        if let Some(cell) = parser.screen().cell(r, c) {
                            for ch in cell.contents().chars() {
                                *map.entry(ch).or_insert(0) += 1;
                            }
                        }
                    }
                }
                parser.screen_mut().set_scrollback(0);
                map
            };

        let before = count_chars(&mut parser);
        parser.screen_mut().set_size(24, 40);
        let after = count_chars(&mut parser);

        assert_eq!(
            before, after,
            "width shrink must not lose scrollback content"
        );
    }

    #[test]
    fn test_exited_callback_atomic_latch_under_contention() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
        use std::thread;

        let call_count = Arc::new(AtomicUsize::new(0));
        let count_clone = Arc::clone(&call_count);

        let cb: StatusCallback = Arc::new(std::sync::Mutex::new(Some(Box::new(move |status| {
            if matches!(status, crate::PtyStatus::Exited) {
                count_clone.fetch_add(1, Ordering::SeqCst);
            }
        }))));

        let exited_emitted = Arc::new(AtomicBool::new(false));

        let handles: Vec<_> = (0..10)
            .map(|_| {
                let cb = Arc::clone(&cb);
                let emitted = Arc::clone(&exited_emitted);
                thread::spawn(move || {
                    if !emitted.swap(true, Ordering::AcqRel)
                        && let Ok(guard) = cb.lock()
                        && let Some(ref f) = *guard
                    {
                        f(crate::PtyStatus::Exited);
                    }
                })
            })
            .collect();

        for h in handles {
            h.join().unwrap();
        }

        assert_eq!(
            call_count.load(Ordering::SeqCst),
            1,
            "Exited callback must execute exactly once under thread contention"
        );
    }

    #[test]
    fn cursor_bounded_shrink_preserves_bottom_when_cursor_at_bottom() {
        let mut parser = term_wm_vt100::Parser::new(30, 80, 200);
        for i in 0..30 {
            parser.process(format!("line {}\r\n", i).as_bytes());
        }
        parser.process(b"LASTLINE");

        let (cursor_row, _) = parser.screen().cursor_position();
        let new_rows: u16 = 24;
        assert_eq!(cursor_row, 29, "cursor at bottom");

        let scroll_lines = cursor_row - new_rows + 1;
        assert_eq!(scroll_lines, 6);
        parser.process(format!("\x1b[{}S", scroll_lines).as_bytes());
        parser.screen_mut().set_size(new_rows, 80);

        assert!(
            parser.screen().contents().contains("LASTLINE"),
            "bottom content preserved when cursor at bottom"
        );
        assert_eq!(parser.screen().size(), (24, 80));
    }

    #[test]
    fn cursor_bounded_shrink_skips_when_cursor_above_new_height() {
        let mut parser = term_wm_vt100::Parser::new(30, 80, 200);
        for i in 0..10 {
            parser.process(format!("line {}\r\n", i).as_bytes());
        }
        parser.process(b"MIDLINE");

        let (cursor_row, _) = parser.screen().cursor_position();
        assert!(
            cursor_row < 24,
            "cursor ({cursor_row}) above new viewport height"
        );

        parser.screen_mut().set_size(24, 80);
        assert!(
            parser.screen().contents().contains("MIDLINE"),
            "content preserved without any SU shift"
        );
        assert_eq!(parser.screen().size(), (24, 80));
    }

    // ── Environment sanitization ─────────────────────────────────────

    fn fresh_cmd() -> CommandBuilder {
        CommandBuilder::new("true")
    }

    #[test]
    fn sanitize_sets_multiplexer_safe_term() {
        let mut cmd = fresh_cmd();
        sanitize_child_environment_with_lc_ctype(&mut cmd, None);
        assert_eq!(
            cmd.get_env("TERM").and_then(|v| v.to_str()),
            Some(expected_child_term())
        );
    }

    #[test]
    fn sanitize_sets_truecolor() {
        let mut cmd = fresh_cmd();
        sanitize_child_environment_with_lc_ctype(&mut cmd, None);
        assert_eq!(
            cmd.get_env("COLORTERM").and_then(|v| v.to_str()),
            Some("truecolor")
        );
    }

    #[test]
    fn sanitize_strips_invalid_lc_ctype_utf8() {
        let mut cmd = fresh_cmd();
        // Simulate the invalid `LC_CTYPE=UTF-8` macOS/OrbStack SSH hop injects.
        cmd.env("LC_CTYPE", "UTF-8");
        sanitize_child_environment_with_lc_ctype(&mut cmd, Some("UTF-8"));
        assert!(
            cmd.get_env("LC_CTYPE").is_none(),
            "invalid LC_CTYPE=UTF-8 must be stripped"
        );
    }

    #[test]
    fn sanitize_keeps_valid_lc_ctype() {
        let mut cmd = fresh_cmd();
        cmd.env("LC_CTYPE", "en_US.UTF-8");
        sanitize_child_environment_with_lc_ctype(&mut cmd, Some("en_US.UTF-8"));
        assert_eq!(
            cmd.get_env("LC_CTYPE").and_then(|v| v.to_str()),
            Some("en_US.UTF-8"),
            "valid locale must be preserved"
        );
    }

    /// End-to-end: the child spawned via the real `Pty` launcher must see the
    /// sanitized environment. We write a child that prints its `TERM`,
    /// `COLORTERM`, and `LC_CTYPE` (or its absence) and assert on the output.
    #[test]
    #[cfg(unix)]
    fn spawned_child_receives_sanitized_environment() {
        // `sh` is POSIX-standard; on Windows this test is skipped.
        let script = indoc::indoc! {r#"
            TERM_VAL="${TERM:-<unset>}"
            COLORTERM_VAL="${COLORTERM:-<unset>}"
            LC_CTYPE_VAL="${LC_CTYPE:-<unset>}"
            printf 'TERM=%s\nCOLORTERM=%s\nLC_CTYPE=%s\n' \
              "$TERM_VAL" "$COLORTERM_VAL" "$LC_CTYPE_VAL"
        "#};
        let mut cmd = CommandBuilder::new("sh");
        cmd.arg("-c");
        cmd.arg(script);
        let size = PtySize {
            rows: 24,
            cols: 80,
            pixel_width: 0,
            pixel_height: 0,
        };
        let mut pty = Pty::spawn_with_scrollback(cmd, size, 0).expect("spawn");

        let mut accumulated = Vec::new();
        let start = std::time::Instant::now();
        loop {
            pty.screen();
            accumulated.extend_from_slice(&pty.drain_pending());
            let out = String::from_utf8_lossy(&accumulated);
            if out.contains("LC_CTYPE=") {
                break;
            }
            assert!(
                start.elapsed() < std::time::Duration::from_secs(5),
                "child never printed sanitized env; got {out}"
            );
            std::thread::sleep(std::time::Duration::from_millis(20));
        }
        if let Some(child) = pty.child.as_mut() {
            let _ = child.kill();
        }

        let out = String::from_utf8_lossy(&accumulated);
        assert!(
            out.contains(&format!("TERM={}", expected_child_term())),
            "expected TERM={}, got {out}",
            expected_child_term()
        );
        assert!(
            out.contains("COLORTERM=truecolor"),
            "expected COLORTERM=truecolor, got {out}"
        );
        assert!(
            !out.contains("LC_CTYPE=UTF-8"),
            "invalid LC_CTYPE=UTF-8 must not reach the child, got {out}"
        );
    }

    /// Mirrors the platform-specific `CHILD_TERM` so tests assert the value the
    /// sanitizer actually applies on this platform.
    fn expected_child_term() -> &'static str {
        CHILD_TERM
    }
}