quadraui 0.6.1

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
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
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
//! PTY + vt100 + scrollback engine for embedded terminal emulators.
//!
//! Provides [`TerminalSession`] (single pane) and [`TerminalManager`]
//! (multi-tab) that own the PTY process, background reader thread,
//! vt100 screen parser, and scrollback ring buffer. Paint output is a
//! [`crate::Terminal`] snapshot — directly consumable by the existing
//! [`crate::tui::draw_terminal`] / `Backend::draw_terminal` rasterisers.
//!
//! # Feature gate
//!
//! This module is compiled only when the `terminal` Cargo feature is
//! enabled. The rasteriser lives in [`crate::primitives::terminal`] and
//! is always available (no extra feature needed to paint snapshots you
//! obtained elsewhere).
//!
//! # Quick start
//!
//! ```ignore
//! use quadraui::terminal_engine::{TerminalSession, default_shell};
//!
//! let cwd = std::env::current_dir()?;
//! let mut session =
//!     TerminalSession::spawn(80, 24, &default_shell(), &cwd, 5_000)?;
//!
//! // In your event loop tick():
//! if session.poll() {
//!     let sb = session.scrollbar_state(None);
//!     let snapshot = session.to_terminal(WidgetId::new("term:0"), Some(sb));
//!     // pass snapshot to Backend::draw_terminal(rect, &snapshot)
//! }
//!
//! // Forward keyboard input:
//! session.write_input(b"ls\n");
//!
//! // Resize on layout change:
//! session.resize(120, 40);
//! ```
//!
//! # Multi-tab / multi-pane
//!
//! [`TerminalManager`] wraps a `Vec<TerminalSession>` and tracks the
//! active index. Tab-switching keybindings and split-pane layouts are
//! the **consuming app's** responsibility — this type exposes only the
//! data-management API.
//!
//! # Design decisions
//!
//! - The vt100 parser is always kept at `scrollback = 0` (live view).
//!   Lines that scroll off the screen are captured into a private
//!   [`VecDeque`] ring buffer instead — this avoids fighting with the
//!   vt100 crate's own bounded scrollback buffer and gives us full
//!   control over the history capacity.
//! - [`TerminalSession::to_terminal`] is the only public snapshot
//!   builder. Find-match overlays (`is_find_match`, `is_find_active`)
//!   are left as `false` — callers that implement in-terminal search
//!   can post-process the returned `Terminal::cells`.
//! - The cross-backend portability commitment: `TerminalSession` is
//!   backend-agnostic. The GTK backend can call `to_terminal()` just
//!   as easily as the TUI backend.

use std::collections::VecDeque;
use std::io::Write;
use std::path::Path;
use std::sync::mpsc::{self, Receiver};

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

use crate::event::{Key, MouseButton, NamedKey};
use crate::primitives::terminal::{Terminal, TerminalCell, TerminalCursorShape, TerminalScrollbar};
use crate::types::{Color, Modifiers, WidgetId};

// ── Internal history cell ─────────────────────────────────────────────────────

/// A single captured terminal cell in the scrollback ring buffer.
///
/// Uses `vt100::Color` directly to defer RGB resolution until paint time,
/// matching the approach used by downstream terminal-history cell types.
///
/// `text` carries the cell's full grapheme cluster (base character plus
/// any combining marks), mirroring [`TerminalCell::text`] — no longer
/// `Copy` since `String` isn't.
#[derive(Clone)]
struct HistCell {
    text: String,
    fg: vt100::Color,
    bg: vt100::Color,
    bold: bool,
    italic: bool,
    underline: bool,
    /// SGR 2 (faint/dim) — `vt100::Cell::dim()`, tracked since vt100
    /// 0.16.
    dim: bool,
}

impl Default for HistCell {
    fn default() -> Self {
        HistCell {
            text: " ".to_string(),
            fg: vt100::Color::Default,
            bg: vt100::Color::Default,
            bold: false,
            italic: false,
            underline: false,
            dim: false,
        }
    }
}

// ── Selection ─────────────────────────────────────────────────────────────────

/// Mouse text-selection state for a terminal pane.
///
/// All coordinates are 0-based into the **visible grid** (not into history).
/// End-column is inclusive.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TerminalSelection {
    pub start_row: u16,
    pub start_col: u16,
    pub end_row: u16,
    pub end_col: u16,
}

/// Normalise a selection so `(r0, c0) ≤ (r1, c1)` in reading order.
fn normalize_selection(sel: &TerminalSelection) -> (u16, u16, u16, u16) {
    if (sel.start_row, sel.start_col) <= (sel.end_row, sel.end_col) {
        (sel.start_row, sel.start_col, sel.end_row, sel.end_col)
    } else {
        (sel.end_row, sel.end_col, sel.start_row, sel.start_col)
    }
}

// ── Colour helpers ────────────────────────────────────────────────────────────

/// Map a `vt100::Color` to an RGB triple.
///
/// `Default` resolves to dark-theme terminal defaults matching a
/// common OneDark-style baseline (`#e5e5e5` fg, `#1e1e1e` bg). Callers
/// that want theme-aware colours should post-process cells after
/// calling [`TerminalSession::to_terminal`].
fn map_vt100_color(color: vt100::Color, is_bg: bool) -> (u8, u8, u8) {
    match color {
        vt100::Color::Default => {
            if is_bg {
                (30, 30, 30) // terminal background (~#1e1e1e)
            } else {
                (229, 229, 229) // terminal foreground (~#e5e5e5)
            }
        }
        vt100::Color::Rgb(r, g, b) => (r, g, b),
        vt100::Color::Idx(n) => xterm_256_color(n),
    }
}

/// Standard xterm 256-colour palette lookup.
fn xterm_256_color(n: u8) -> (u8, u8, u8) {
    // System colours 0-15.
    const SYSTEM: [(u8, u8, u8); 16] = [
        (0, 0, 0),
        (128, 0, 0),
        (0, 128, 0),
        (128, 128, 0),
        (0, 0, 128),
        (128, 0, 128),
        (0, 128, 128),
        (192, 192, 192),
        (128, 128, 128),
        (255, 0, 0),
        (0, 255, 0),
        (255, 255, 0),
        (0, 0, 255),
        (255, 0, 255),
        (0, 255, 255),
        (255, 255, 255),
    ];
    if n < 16 {
        return SYSTEM[n as usize];
    }
    // 6×6×6 colour cube: indices 16-231.
    if n < 232 {
        let idx = n - 16;
        let b = idx % 6;
        let g = (idx / 6) % 6;
        let r = idx / 36;
        let to_byte = |v: u8| if v == 0 { 0 } else { 55 + v * 40 };
        return (to_byte(r), to_byte(g), to_byte(b));
    }
    // Greyscale ramp: indices 232-255.
    let gray = 8 + (n - 232) * 10;
    (gray, gray, gray)
}

// ── Mouse → PTY encoding (SGR-1006) ──────────────────────────────────────────

/// Mouse event kinds that can be forwarded to a PTY child via SGR-1006.
///
/// Mirrors the granularity an embedded terminal needs to dispatch: button
/// press/release, motion (with a button held, per DEC 1002), and wheel.
/// Wheel direction is encoded in the kind because wheel events have no
/// matching `MouseButton` in [`crate::event::MouseButton`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TerminalMouseKind {
    /// Button press.
    Press,
    /// Button release.
    Release,
    /// Cursor motion. For SGR-1006 the `button` field still indicates which
    /// (if any) button is being held; pass [`MouseButton::Left`] with no
    /// button-down state if the caller can't disambiguate.
    Move,
    /// Mouse wheel scrolled up (toward the top of content).
    WheelUp,
    /// Mouse wheel scrolled down (toward the bottom of content).
    WheelDown,
}

/// Encode a mouse event as SGR-1006 bytes ready to write to a PTY.
///
/// Format: `ESC [ < Cb ; Cx ; Cy M` (press / wheel / motion) or
/// `ESC [ < Cb ; Cx ; Cy m` (release). Coordinates in the output are 1-based;
/// the `col` / `row` inputs are **0-based** cell indices.
///
/// The `Cb` byte packs button identity + modifier state + motion bit:
///
/// | bits      | meaning                                              |
/// |-----------|------------------------------------------------------|
/// | 0–1       | button low bits (0=left, 1=middle, 2=right)          |
/// | 2 (= 4)   | shift                                                |
/// | 3 (= 8)   | alt / meta                                           |
/// | 4 (= 16)  | ctrl                                                 |
/// | 5 (= 32)  | motion event                                         |
/// | 6 (= 64)  | wheel (combined with bits 0–1 for direction)         |
/// | 7 (= 128) | extra button (X1 → 128, X2 → 129)                    |
///
/// Wheel events always use the `M` terminator (they have no release).
/// [`MouseButton::Other(n)`] forwards `n` directly into the low button bits.
pub fn encode_mouse_sgr(
    kind: TerminalMouseKind,
    button: MouseButton,
    col: u16,
    row: u16,
    modifiers: Modifiers,
) -> Vec<u8> {
    // Wheel codes are independent of `button`.
    let mut cb: u32 = match kind {
        TerminalMouseKind::WheelUp => 64,
        TerminalMouseKind::WheelDown => 65,
        TerminalMouseKind::Press | TerminalMouseKind::Release | TerminalMouseKind::Move => {
            match button {
                MouseButton::Left => 0,
                MouseButton::Middle => 1,
                MouseButton::Right => 2,
                MouseButton::X1 => 128,
                MouseButton::X2 => 129,
                MouseButton::Other(n) => n as u32,
            }
        }
    };

    if matches!(kind, TerminalMouseKind::Move) {
        cb |= 32; // motion bit
    }
    if modifiers.shift {
        cb |= 4;
    }
    if modifiers.alt {
        cb |= 8;
    }
    if modifiers.ctrl {
        cb |= 16;
    }

    let terminator = match kind {
        TerminalMouseKind::Release => b'm',
        // Press / Move / WheelUp / WheelDown all use uppercase 'M'.
        _ => b'M',
    };

    // Convert 0-based cell to 1-based protocol coordinates. Saturate at u16::MAX.
    let cx = col.saturating_add(1);
    let cy = row.saturating_add(1);

    format!("\x1b[<{cb};{cx};{cy}{}", terminator as char).into_bytes()
}

/// Encode pasted `text` as PTY input bytes.
///
/// When `bracketed` is `true`, wraps `text` in bracketed-paste markers
/// (`ESC[200~ ... ESC[201~`, DEC private mode 2004) so a program that
/// understands them (readline-based shells, `vim`, `claude`, ...) can
/// tell pasted text apart from typed text. When `bracketed` is `false`,
/// returns `text`'s raw UTF-8 bytes unchanged — wrapping unconditionally
/// would leak literal escape bytes into programs that never asked for
/// bracketed paste and don't know to strip them (e.g. `cat`, `less`).
///
/// Pulled out as a standalone function (rather than inlined into
/// [`TerminalSession::paste`]) so the encoding itself is unit-testable
/// without spawning a PTY — see the `tests` module below.
fn encode_paste(text: &str, bracketed: bool) -> Vec<u8> {
    if bracketed {
        let mut bytes = Vec::with_capacity(text.len() + 12);
        bytes.extend_from_slice(b"\x1b[200~");
        bytes.extend_from_slice(text.as_bytes());
        bytes.extend_from_slice(b"\x1b[201~");
        bytes
    } else {
        text.as_bytes().to_vec()
    }
}

// ── Keyboard → PTY encoding ───────────────────────────────────────────────────
//
// Lifted out of `examples/common/terminal_app.rs` into the engine
// so every embedded consumer (vimcode-tui, a future GTK
// standalone app, ...) gets the same VT100/xterm key encoding instead of
// re-implementing or copying it. `TerminalSession::encode_key` is the
// entry point most callers want — it reads `application_cursor_keys()`
// internally. [`key_to_pty_bytes`] is exposed as a free function for
// callers that want to encode without a live session (e.g. tests).

/// Convert a [`Key`] + [`Modifiers`] to the byte sequence sent to the PTY.
///
/// `app_cursor` should be `true` when the child has enabled DECCKM
/// (application-cursor-keys mode, `ESC [ ? 1 h`). In that mode, unmodified
/// arrow keys and Home/End are encoded as SS3 sequences (`ESC O A…D/H/F`)
/// rather than the normal CSI sequences. Obtain the flag from
/// [`TerminalSession::application_cursor_keys`], or use
/// [`TerminalSession::encode_key`], which reads it for you.
///
/// Covers the common VT100 / xterm-256color escape sequences. Keys that
/// have no meaningful PTY encoding (e.g. CapsLock) return `None`.
pub fn key_to_pty_bytes(key: Key, mods: Modifiers, app_cursor: bool) -> Option<Vec<u8>> {
    match key {
        Key::Char(ch) => {
            if mods.ctrl {
                // Ctrl+A-Z → bytes 0x01..0x1A.
                let c = ch.to_ascii_uppercase();
                if c.is_ascii_alphabetic() {
                    return Some(vec![c as u8 - b'@']);
                }
                // Ctrl+[ → ESC, Ctrl+\ → FS, Ctrl+] → GS, Ctrl+^ → RS, Ctrl+_ → US.
                match ch {
                    '[' => return Some(vec![0x1b]),
                    '\\' => return Some(vec![0x1c]),
                    ']' => return Some(vec![0x1d]),
                    '^' => return Some(vec![0x1e]),
                    '_' => return Some(vec![0x1f]),
                    _ => {}
                }
            }
            // Regular printable character — encode as UTF-8.
            let mut buf = [0u8; 4];
            let s = ch.encode_utf8(&mut buf);
            Some(s.as_bytes().to_vec())
        }

        Key::Named(named) => named_key_bytes(named, mods, app_cursor),
    }
}

/// Map named keys to their VT100 escape sequences.
///
/// `app_cursor` enables DECCKM encoding: unmodified arrow keys and Home/End
/// emit SS3 sequences (`ESC O x`) rather than CSI sequences (`ESC [ x`).
/// When a modifier is present the CSI form is always used regardless of mode.
fn named_key_bytes(key: NamedKey, mods: Modifiers, app_cursor: bool) -> Option<Vec<u8>> {
    // Modifier prefix for xterm sequences: 1=plain 2=shift 3=alt 4=shift+alt
    // 5=ctrl 6=shift+ctrl 7=alt+ctrl 8=shift+alt+ctrl.
    let mod_param = modifier_param(mods);

    match key {
        NamedKey::Enter => Some(b"\r".to_vec()),
        NamedKey::Tab => {
            if mods.shift {
                Some(b"\x1b[Z".to_vec()) // Back-tab
            } else {
                Some(b"\t".to_vec())
            }
        }
        NamedKey::BackTab => Some(b"\x1b[Z".to_vec()),
        NamedKey::Backspace => Some(b"\x7f".to_vec()),
        NamedKey::Delete => Some(xterm_seq(b"3", mod_param)),
        NamedKey::Escape => Some(b"\x1b".to_vec()),
        // ── Arrow keys: SS3 in application-cursor mode (no modifier), CSI otherwise
        NamedKey::Up => {
            if app_cursor && mod_param.is_none() {
                Some(ss3_seq(b'A'))
            } else {
                Some(xterm_cursor_seq(b"A", mod_param))
            }
        }
        NamedKey::Down => {
            if app_cursor && mod_param.is_none() {
                Some(ss3_seq(b'B'))
            } else {
                Some(xterm_cursor_seq(b"B", mod_param))
            }
        }
        NamedKey::Right => {
            if app_cursor && mod_param.is_none() {
                Some(ss3_seq(b'C'))
            } else {
                Some(xterm_cursor_seq(b"C", mod_param))
            }
        }
        NamedKey::Left => {
            if app_cursor && mod_param.is_none() {
                Some(ss3_seq(b'D'))
            } else {
                Some(xterm_cursor_seq(b"D", mod_param))
            }
        }
        // ── Home/End: SS3 in application-cursor mode (no modifier), tilde-CSI otherwise
        NamedKey::Home => {
            if app_cursor && mod_param.is_none() {
                Some(ss3_seq(b'H'))
            } else {
                Some(xterm_seq(b"1", mod_param))
            }
        }
        NamedKey::End => {
            if app_cursor && mod_param.is_none() {
                Some(ss3_seq(b'F'))
            } else {
                Some(xterm_seq(b"4", mod_param))
            }
        }
        // PageUp/PageDown are not affected by DECCKM.
        NamedKey::Insert => Some(xterm_seq(b"2", mod_param)),
        NamedKey::PageUp => Some(xterm_seq(b"5", mod_param)),
        NamedKey::PageDown => Some(xterm_seq(b"6", mod_param)),
        NamedKey::F(n) => f_key_bytes(n, mod_param),
        // Keys with no PTY mapping.
        NamedKey::CapsLock | NamedKey::NumLock | NamedKey::ScrollLock | NamedKey::Menu => None,
    }
}

/// Build an SS3 sequence: `ESC O <letter>`.
///
/// Used for application-cursor-keys mode (DECCKM on): unmodified arrows emit
/// `ESC O A/B/C/D` and Home/End emit `ESC O H/F` instead of CSI sequences.
fn ss3_seq(letter: u8) -> Vec<u8> {
    vec![0x1b, b'O', letter]
}

/// Build an xterm modifier parameter (1-based; plain = `None`).
fn modifier_param(mods: Modifiers) -> Option<u8> {
    // mod_param = 1 + shift + 2*alt + 4*ctrl
    let n: u8 = 1
        + if mods.shift { 1 } else { 0 }
        + if mods.alt { 2 } else { 0 }
        + if mods.ctrl { 4 } else { 0 };
    if n == 1 {
        None
    } else {
        Some(n)
    }
}

/// Build `\x1b[<code>~` or `\x1b[<code>;<mod>~` for tilde-terminated sequences.
///
/// Per xterm conventions, the modifier parameter follows the code (separated by `;`)
/// for tilde-terminated sequences (Home, End, Insert, Delete, PageUp, PageDown, F5–F12).
/// Cursor-letter sequences use the `1;<mod>` prefix instead — see [`xterm_cursor_seq`].
fn xterm_seq(code: &[u8], mod_param: Option<u8>) -> Vec<u8> {
    let mut v = b"\x1b[".to_vec();
    v.extend_from_slice(code);
    if let Some(m) = mod_param {
        v.push(b';');
        v.push(b'0' + m);
    }
    v.push(b'~');
    v
}

/// Build cursor-movement sequences: `\x1b[<letter>` or `\x1b[1;<mod><letter>`.
fn xterm_cursor_seq(letter: &[u8], mod_param: Option<u8>) -> Vec<u8> {
    match mod_param {
        None => {
            let mut v = b"\x1b[".to_vec();
            v.extend_from_slice(letter);
            v
        }
        Some(m) => {
            let mut v = b"\x1b[1;".to_vec();
            v.push(b'0' + m);
            v.extend_from_slice(letter);
            v
        }
    }
}

/// Function-key byte sequences (xterm encoding).
fn f_key_bytes(n: u8, mod_param: Option<u8>) -> Option<Vec<u8>> {
    // F1-F4 use SS3 sequences when unmodified (\x1bOP…\x1bOS).
    // When a modifier is present they fall back to CSI: \x1b[1;<mod>P…S.
    // F5-F12 always use tilde-terminated CSI sequences.
    let bytes = match n {
        1 => {
            if mod_param.is_none() {
                b"\x1bOP".to_vec()
            } else {
                xterm_cursor_seq(b"P", mod_param)
            }
        }
        2 => {
            if mod_param.is_none() {
                b"\x1bOQ".to_vec()
            } else {
                xterm_cursor_seq(b"Q", mod_param)
            }
        }
        3 => {
            if mod_param.is_none() {
                b"\x1bOR".to_vec()
            } else {
                xterm_cursor_seq(b"R", mod_param)
            }
        }
        4 => {
            if mod_param.is_none() {
                b"\x1bOS".to_vec()
            } else {
                xterm_cursor_seq(b"S", mod_param)
            }
        }
        5 => xterm_seq(b"15", mod_param),
        6 => xterm_seq(b"17", mod_param),
        7 => xterm_seq(b"18", mod_param),
        8 => xterm_seq(b"19", mod_param),
        9 => xterm_seq(b"20", mod_param),
        10 => xterm_seq(b"21", mod_param),
        11 => xterm_seq(b"23", mod_param),
        12 => xterm_seq(b"24", mod_param),
        _ => return None, // F13+ not commonly used
    };
    Some(bytes)
}

// ── TerminalSession ───────────────────────────────────────────────────────────

/// Longest [`TerminalSession::resize`] waits for the child to *begin* its
/// post-SIGWINCH redraw — i.e. for the **first** byte to arrive.
const RESIZE_SETTLE_FIRST: std::time::Duration = std::time::Duration::from_millis(80);

/// Once the child's redraw is *flowing*, an idle gap this long means it has
/// finished. Consuming stops here so a subsequent resize can't reparse the
/// redraw against a grid whose width has since changed.
const RESIZE_SETTLE_IDLE: std::time::Duration = std::time::Duration::from_millis(8);

/// Absolute cap on total settle time, so a continuously chatty child
/// (e.g. `yes`) that never goes idle can't stall the UI indefinitely.
const RESIZE_SETTLE_MAX: std::time::Duration = std::time::Duration::from_millis(120);

/// Block for the child's post-SIGWINCH redraw and return the chunks it produced,
/// in arrival order.
fn collect_post_resize_output(rx: &Receiver<Vec<u8>>) -> Vec<Vec<u8>> {
    use std::sync::mpsc::RecvTimeoutError;
    use std::time::Instant;

    let start = Instant::now();
    let hard_deadline = start + RESIZE_SETTLE_MAX;
    let first_deadline = start + RESIZE_SETTLE_FIRST;
    let mut chunks: Vec<Vec<u8>> = Vec::new();
    loop {
        let now = Instant::now();
        let cap = hard_deadline.saturating_duration_since(now);
        if cap.is_zero() {
            break;
        }
        // Phase 1 (nothing captured yet): wait up to RESIZE_SETTLE_FIRST for the
        // child to *begin* redrawing. Phase 2 (redraw flowing): wait only for
        // the short idle gap that marks it complete. Both clamped to the cap.
        let wait = if chunks.is_empty() {
            first_deadline.saturating_duration_since(now)
        } else {
            RESIZE_SETTLE_IDLE
        }
        .min(cap);
        if wait.is_zero() {
            break;
        }
        match rx.recv_timeout(wait) {
            Ok(data) => chunks.push(data),
            // Timeout → phase 1: child never reacted; phase 2: redraw done.
            // Disconnected → child gone. Either way we are settled.
            Err(RecvTimeoutError::Timeout) | Err(RecvTimeoutError::Disconnected) => break,
        }
    }
    chunks
}

/// Re-wrap a vt100 parser's visible screen to a new size, preserving on-screen
/// content across a **width** change.
fn reflow_screen<CB: vt100::Callbacks>(parser: &mut vt100::Parser<CB>, rows: u16, cols: u16) {
    let (cur_rows, cur_cols) = parser.screen().size();
    if (rows, cols) == (cur_rows, cur_cols) {
        return;
    }
    // Height-only change, or a self-repainting full-screen app: use the plain
    // non-reflow resize. (`alternate_screen()` reads the parser immutably; the
    // borrow ends before the `screen_mut()` below.)
    if cols == cur_cols || parser.screen().alternate_screen() {
        set_size_without_orphaning_wide_cells(parser, rows, cols);
        return;
    }
    // Width change on the normal screen: snapshot → resize → replay so each
    // logical line re-wraps at the new width instead of being truncated.
    // The snapshot is taken *before* the scrub inside the resize below, so a
    // wide glyph the scrub has to erase is still carried across and re-wrapped
    // at the new width rather than lost.
    let dump = parser.screen().contents_formatted();
    set_size_without_orphaning_wide_cells(parser, rows, cols);
    parser.process(&dump);
}

/// [`vt100::Screen::set_size`], plus the repair vt100 0.16.2 forgets to make
/// when a **width shrink** cuts a double-width glyph in half.
///
/// vt100 stores a wide glyph as two cells: a first half (`Cell::is_wide()`) and
/// a continuation half (`Cell::is_wide_continuation()`). `Grid::set_size`
/// narrows each row with a plain `Vec::resize`, which simply drops the cells
/// past the new width — unlike `Row::truncate`, which clears a first half whose
/// partner it is about to drop. So shrinking to a width that lands exactly
/// *between* a wide glyph's two halves leaves a first half orphaned at the new
/// final column with nothing after it.
///
/// That cell is then a landmine, and every route out of it is an upstream
/// `unwrap()` on an out-of-range column:
///
/// - writing a character over it panics at `screen.rs:870` (it looks for the
///   continuation half at `col + 1` to blank it), and
/// - *erasing* it panics too (`Row::clear_wide` indexes the same `col + 1`), so
///   it cannot be cleaned up after the fact — not even by `ED`/`EL`, which is
///   exactly what replaying a `contents_formatted` dump starts with. That is
///   why [`reflow_screen`]'s snapshot→resize→replay was affected as well as the
///   plain height-only / alternate-screen path.
///
/// The fix is therefore to *prevent* the orphan rather than repair it: while
/// both halves are still in range, erase (`CSI X`) any first half sitting on
/// the column that is about to become the last one. The shrink then truncates a
/// blank pair instead of splitting a glyph. `DECSC`/`DECRC` bracket the scrub so
/// the cursor position, origin mode and pending-wrap state survive it.
///
/// Costs nothing in the common case: the scan is skipped entirely unless the
/// width is actually shrinking, and no bytes are fed to the parser unless a
/// glyph really does straddle the new boundary.
fn set_size_without_orphaning_wide_cells<CB: vt100::Callbacks>(
    parser: &mut vt100::Parser<CB>,
    rows: u16,
    cols: u16,
) {
    let (cur_rows, cur_cols) = parser.screen().size();
    // Growing (or keeping) the width can never split a glyph; rows are dropped
    // whole, so a height change is safe too.
    // (`checked_sub` rather than `cols - 1`: a zero width is already fatal
    // one line down inside vt100 — see `MIN_VT100_COLS` — but this helper
    // must not be the thing that panics first, and there is no boundary
    // cell to scrub when there is no last column.)
    if let Some(last_col) = cols.checked_sub(1).filter(|_| cols < cur_cols) {
        let mut scrub = Vec::new();
        for row in 0..cur_rows {
            let straddles = parser
                .screen()
                .cell(row, last_col)
                .is_some_and(vt100::Cell::is_wide);
            if straddles {
                // CUP to (row, new last column), then ECH 1. Both 1-based.
                scrub.extend_from_slice(format!("\x1b[{};{}H\x1b[X", row + 1, cols).as_bytes());
            }
        }
        if !scrub.is_empty() {
            let mut bytes = b"\x1b7".to_vec();
            bytes.append(&mut scrub);
            bytes.extend_from_slice(b"\x1b8");
            parser.process(&bytes);
        }
    }
    parser.screen_mut().set_size(rows, cols);
}

/// Floor for `rows` handed to `vt100::Parser::new`/`Screen::set_size`.
///
/// vt100 0.16.2 panics (`attempt to subtract with overflow`, `grid.rs:683`)
/// constructing or resizing a grid with `rows < 2` — an upstream bug, not
/// anything this file does wrong. A terminal pane's rect can legitimately
/// shrink to a single visible row — or momentarily to zero, before a
/// drag-resize settles — so every caller-supplied `rows` is floored to
/// this at both call sites that construct/resize the parser
/// ([`TerminalSession::spawn`], [`TerminalSession::resize`]) rather than
/// trusted. Found by this file's own `vt100_parser_never_panics`
/// property test before any real caller ever hit it.
const MIN_VT100_ROWS: u16 = 2;

/// Floor for `cols`, for the same reason as [`MIN_VT100_ROWS`] but a
/// different upstream panic site (`attempt to subtract with overflow`,
/// `screen.rs:730`, reachable with `cols == 1` and certain multi-byte
/// input regardless of `rows`) — found by the same property test.
const MIN_VT100_COLS: u16 = 2;

/// Floor a caller-supplied `(cols, rows)` pair to the smallest grid vt100
/// can construct or resize to without panicking.
///
/// Both [`TerminalSession::spawn`] and [`TerminalSession::resize`] funnel
/// their dimensions through this before anything reaches
/// `vt100::Parser::new`/`Screen::set_size`; see
/// [`MIN_VT100_ROWS`]/[`MIN_VT100_COLS`] for which upstream panic each
/// bound dodges. Pulled out as a standalone function so the floor itself
/// is testable on every platform — the end-to-end `spawn`/`resize`
/// assertions need a real PTY child and so are `cfg(unix)`-only.
fn clamp_vt100_size(cols: u16, rows: u16) -> (u16, u16) {
    (cols.max(MIN_VT100_COLS), rows.max(MIN_VT100_ROWS))
}

/// [`vt100::Callbacks`] implementation that records OSC 0/2 window-title
/// requests and DECSCUSR cursor-shape requests instead of discarding
/// them.
///
/// vt100 0.16.2 reports the title via a callback method rather than
/// storing it on [`vt100::Screen`] itself (see `set_window_title`/
/// `set_window_icon_name` in the upstream `Callbacks` trait); it doesn't
/// track DECSCUSR (`ESC [ Ps SP q`) at all — that sequence has an
/// intermediate byte (`SP`, `0x20`) vt100's own `csi_dispatch` doesn't
/// recognise for any final byte, so it falls through to
/// [`unhandled_csi`](vt100::Callbacks::unhandled_csi) instead.
/// [`TerminalSession`] carries one of these alongside
/// its parser and reads both back after each [`poll`](TerminalSession::poll)
/// via [`TerminalSession::title`]/[`TerminalSession::cursor_shape`]/
/// [`TerminalSession::cursor_blinking`].
///
/// `set_window_title` only overrides for OSC 0/2 — a bare OSC 1
/// (icon-name-only) sequence calls `set_window_icon_name` instead, which
/// this type doesn't override, so it is intentionally *not* captured
/// here.
///
/// Tracks a dirty flag for the title so callers can cheaply ask "did the
/// title change since I last looked?" without diffing strings themselves
/// — see [`TerminalSession::take_title_changed`]. The cursor fields have
/// no such flag: they're read fresh every [`TerminalSession::to_terminal`]
/// call, which is cheap (two field reads), unlike a title-driven native
/// window retitle.
#[derive(Debug, Default)]
struct EngineCallbacks {
    /// Most recent window title set via OSC 0 or OSC 2. `None` until the
    /// child program sets one.
    title: Option<String>,
    /// `true` when [`title`](Self::title) has changed since the last
    /// [`TerminalSession::take_title_changed`] call.
    changed: bool,
    /// Most recent DECSCUSR shape. Defaults to
    /// [`TerminalCursorShape::Block`] — DECSCUSR's own `Ps` values `0`/`1`
    /// both mean "blinking block", which is also the sequence-free
    /// starting state real terminals use.
    cursor_shape: TerminalCursorShape,
    /// Most recent DECSCUSR blink flag (`Ps` odd = blinking, even =
    /// steady). Defaults to `false` (steady) — unlike real terminals'
    /// blinking-block default, a child that never sends DECSCUSR at all
    /// gets a steady cursor here so a driver/test harness with no PTY
    /// churn doesn't have to fight a wall-clock blink toggle to see a
    /// stable snapshot.
    cursor_blinking: bool,
}

impl vt100::Callbacks for EngineCallbacks {
    fn set_window_title(&mut self, _screen: &mut vt100::Screen, title: &[u8]) {
        let title = String::from_utf8_lossy(title).into_owned();
        if self.title.as_deref() != Some(title.as_str()) {
            self.title = Some(title);
            self.changed = true;
        }
    }

    fn unhandled_csi(
        &mut self,
        _screen: &mut vt100::Screen,
        i1: Option<u8>,
        _i2: Option<u8>,
        params: &[&[u16]],
        c: char,
    ) {
        // DECSCUSR: `ESC [ Ps SP q` — intermediate byte is a literal
        // space (0x20), final byte `q`. `Ps` defaults to `0` when
        // omitted (a bare `ESC [ SP q`), matching every other ANSI/DEC
        // parameter default.
        if i1 == Some(b' ') && c == 'q' {
            let ps = params.first().and_then(|p| p.first()).copied().unwrap_or(0);
            if let Some((shape, blinking)) = decscusr_shape(ps) {
                self.cursor_shape = shape;
                self.cursor_blinking = blinking;
            }
            // An out-of-range `Ps` (7+) is left as a no-op — xterm itself
            // ignores DECSCUSR values it doesn't recognise rather than
            // resetting to a default, and there's no signal here that
            // distinguishes "child sent garbage" from "child sent a
            // future extension this crate doesn't know about" — either
            // way, keeping the last-known-good shape is the safer guess.
        }
    }
}

/// Map a DECSCUSR `Ps` value to `(shape, blinking)`, per the standard
/// six-value table (`ESC [ Ps SP q`, xterm `Ss` extension — the same
/// table [`ratatui::crossterm::cursor::SetCursorStyle`]'s `Display` impl
/// writes out) plus `Ps = 0`, which xterm defines as identical to `Ps =
/// 1`. Returns `None` for any other value — see the `unhandled_csi`
/// call site's doc for why those are ignored rather than reset to a
/// default.
fn decscusr_shape(ps: u16) -> Option<(TerminalCursorShape, bool)> {
    match ps {
        0 | 1 => Some((TerminalCursorShape::Block, true)),
        2 => Some((TerminalCursorShape::Block, false)),
        3 => Some((TerminalCursorShape::Underline, true)),
        4 => Some((TerminalCursorShape::Underline, false)),
        5 => Some((TerminalCursorShape::Bar, true)),
        6 => Some((TerminalCursorShape::Bar, false)),
        _ => None,
    }
}

/// Pure decision logic behind
/// [`TerminalSession::respond_to_terminal_queries`](TerminalSession::respond_to_terminal_queries):
/// scans a raw, not-yet-parsed PTY byte stream for VT query sequences a
/// real terminal emulator is expected to answer, and returns the bytes
/// that should be written back to the PTY (empty if none were found).
///
/// Factored out so the escape-sequence scanning itself is directly
/// testable without a real PTY — the Windows-gated integration tests in
/// `TerminalSession`'s own test module cover the end-to-end "a real ConPTY
/// session unblocks" behaviour this exists to fix; the tests below cover
/// the scanning logic itself, on every platform.
///
/// `cursor` is `(row, col)`, 0-based, matching
/// [`vt100::Screen::cursor_position`]'s own convention — converted to the
/// 1-based form the Cursor Position Report wire format uses.
///
/// Recognises:
/// - `ESC[6n` (Device Status Report: cursor position query) →
///   `ESC[{row};{col}R`.
/// - `ESC[c` / `ESC[0c` (Primary Device Attributes query) → `ESC[?1;0c`
///   ("VT101, no extensions" — matching the floor of what `vt100::Parser`
///   itself understands).
///
/// Any other CSI sequence — including the `>` / `?` private-marker forms —
/// is left unanswered.
fn terminal_query_replies(data: &[u8], cursor: (u16, u16)) -> Vec<u8> {
    let (row, col) = cursor;
    let mut reply = Vec::new();
    let mut i = 0;
    while i < data.len() {
        // Look for the start of a CSI sequence: ESC '['.
        if data[i] != 0x1b || i + 1 >= data.len() || data[i + 1] != b'[' {
            i += 1;
            continue;
        }
        // Scan past the parameter bytes (digits, ';', and the private
        // markers '?' / '>') up to the single final byte that ends a CSI
        // sequence.
        let mut j = i + 2;
        while j < data.len() && matches!(data[j], b'0'..=b'9' | b';' | b'?' | b'>') {
            j += 1;
        }
        let Some(&final_byte) = data.get(j) else {
            // Incomplete sequence split across reads — nothing more to
            // scan in this chunk.
            break;
        };
        let params = &data[i + 2..j];
        match (final_byte, params) {
            (b'n', b"6") => {
                reply.extend(format!("\x1b[{};{}R", row + 1, col + 1).into_bytes());
            }
            (b'c', b"" | b"0") => {
                reply.extend_from_slice(b"\x1b[?1;0c");
            }
            _ => {}
        }
        i = j + 1;
    }
    reply
}

/// A single PTY-backed terminal session: PTY process, reader thread,
/// vt100 parser, and scrollback ring buffer.
///
/// Call [`poll`](Self::poll) each frame tick to drain PTY output, then
/// [`to_terminal`](Self::to_terminal) to build a paint snapshot.
///
/// ## Scrollback model
///
/// The vt100 parser is kept at `scrollback = 0` (live view) at all
/// times. Lines that scroll off the live screen are captured into an
/// internal [`VecDeque`] ring. Calling
/// [`scroll_up`](Self::scroll_up) / [`scroll_down`](Self::scroll_down)
/// adjusts `scroll_offset`; the snapshot builder blends history rows
/// and live rows accordingly.
pub struct TerminalSession {
    /// VT100 screen parser — always at `scrollback = 0` (live view).
    ///
    /// Carries an [`EngineCallbacks`] so OSC 0/2 window-title requests and
    /// DECSCUSR cursor-shape requests are captured; read back via
    /// [`title()`](Self::title) / [`take_title_changed()`](Self::take_title_changed) /
    /// [`cursor_shape()`](Self::cursor_shape) / [`cursor_blinking()`](Self::cursor_blinking).
    parser: vt100::Parser<EngineCallbacks>,
    /// Write half of the PTY master — sends keyboard input to the shell.
    writer: Box<dyn Write + Send>,
    /// PTY master — kept alive for `resize()` calls (SIGWINCH).
    master: Box<dyn MasterPty + Send>,
    /// Child shell process.
    child: Box<dyn Child + Send + Sync>,
    /// PTY output bytes from the background reader thread.
    rx: Receiver<Vec<u8>>,
    /// Current terminal width in columns.
    ///
    /// Read via [`cols()`](Self::cols); change only through [`resize()`](Self::resize)
    /// to keep the vt100 parser and PTY master in sync.
    cols: u16,
    /// Current terminal height in rows.
    ///
    /// Read via [`rows()`](Self::rows); change only through [`resize()`](Self::resize).
    rows: u16,
    /// Mouse text selection, if any.
    pub selection: Option<TerminalSelection>,
    /// `true` once the child process has exited.
    ///
    /// Read via [`is_exited()`](Self::is_exited). Set only by [`poll()`](Self::poll)
    /// when `child.try_wait()` returns a status — setting it externally would
    /// desynchronise the exit-code state.
    exited: bool,
    /// Exit code of the child process once it has exited, or `None` while
    /// still running. `0` conventionally means success.
    exit_code: Option<u32>,
    /// How many rows above the live bottom the user has scrolled.
    /// `0` = live view; maximum = `history.len()`.
    ///
    /// Read via [`scroll_offset()`](Self::scroll_offset); change through
    /// [`set_scroll_offset()`](Self::set_scroll_offset) /
    /// [`scroll_up()`](Self::scroll_up) / [`scroll_down()`](Self::scroll_down)
    /// so that `parser.set_scrollback(0)` is always called consistently.
    scroll_offset: usize,
    /// Scrollback ring buffer (oldest at index 0, newest at the back).
    history: VecDeque<Vec<HistCell>>,
    /// Maximum number of rows kept in `history` (`0` = unlimited — not
    /// recommended for long-lived sessions).
    history_capacity: usize,
}

impl TerminalSession {
    // ── Construction ─────────────────────────────────────────────────────────

    /// Spawn a new interactive shell session.
    ///
    /// - `cols`, `rows` — initial PTY dimensions.
    /// - `shell` — shell binary path (e.g. `"/bin/bash"`). Use
    ///   [`default_shell`] to pick a sensible default — it reads `$SHELL`
    ///   on Unix, and always returns `"powershell.exe"` on Windows.
    /// - `cwd` — working directory for the shell process.
    /// - `history_capacity` — maximum scrollback lines to retain.
    ///   `0` means unlimited (use a large finite value for production).
    pub fn spawn(
        cols: u16,
        rows: u16,
        shell: &str,
        cwd: &Path,
        history_capacity: usize,
    ) -> Result<Self, Box<dyn std::error::Error>> {
        Self::spawn_with_args(cols, rows, shell, &[], cwd, history_capacity)
    }

    /// [`spawn`](Self::spawn), plus extra argv entries passed straight to
    /// [`CommandBuilder::args`].
    ///
    /// Crate-private: not part of the public API surface a consuming app
    /// should build on — `spawn` covers every production call site, since a
    /// consumer picks its shell via [`default_shell`] and never needs to
    /// hand it flags. This exists so Windows-gated tests can start
    /// `powershell.exe` with `-NoLogo -NoProfile`, which removes two sources
    /// of real-hardware startup-time variance (the copyright banner, and a
    /// profile-script existence check across up to four disk paths) that
    /// have nothing to do with the behaviour those tests verify.
    pub(crate) fn spawn_with_args(
        cols: u16,
        rows: u16,
        shell: &str,
        args: &[&str],
        cwd: &Path,
        history_capacity: usize,
    ) -> Result<Self, Box<dyn std::error::Error>> {
        // See `MIN_VT100_ROWS`/`MIN_VT100_COLS`'s docs — vt100 panics below these.
        let (cols, rows) = clamp_vt100_size(cols, rows);
        let pty_system = native_pty_system();
        let pair = pty_system.openpty(PtySize {
            rows,
            cols,
            pixel_width: 0,
            pixel_height: 0,
        })?;

        let mut cmd = CommandBuilder::new(shell);
        cmd.args(args);
        cmd.env("TERM", "xterm-256color");
        // Present the embedded terminal as a clean, top-level terminal. When
        // the host app is itself launched from inside tmux,
        // the spawned shell would otherwise inherit $TMUX/$TMUX_PANE and any
        // tmux command run here would be treated as *nested* in the host's
        // outer session — e.g. `tmux attach-session` refuses ("sessions should
        // be nested with care") and `switch-client` hijacks the host's outer
        // client instead of rendering in this pane. Scrubbing them makes an
        // interactive session launched in this pane attach in-pane as expected.
        cmd.env_remove("TMUX");
        cmd.env_remove("TMUX_PANE");
        cmd.cwd(cwd);
        let child = pair.slave.spawn_command(cmd)?;

        let writer = pair.master.take_writer()?;
        let reader = pair.master.try_clone_reader()?;
        let master = pair.master;

        // Background reader thread: pushes PTY bytes to the main thread
        // via a channel without blocking the event loop.
        let (tx, rx) = mpsc::channel::<Vec<u8>>();
        std::thread::spawn(move || {
            use std::io::Read;
            let mut reader = reader;
            let mut buf = [0u8; 4096];
            loop {
                match reader.read(&mut buf) {
                    Ok(0) | Err(_) => break,
                    Ok(n) => {
                        if tx.send(buf[..n].to_vec()).is_err() {
                            break; // main thread dropped the session
                        }
                    }
                }
            }
        });

        // 1 000-line internal vt100 scrollback — used only to read back
        // the rows that just scrolled off the live screen into `history`.
        // We never call `set_scrollback()` for user-facing scrolling.
        let parser =
            vt100::Parser::new_with_callbacks(rows, cols, 1000, EngineCallbacks::default());

        Ok(Self {
            parser,
            writer,
            master,
            child,
            rx,
            cols,
            rows,
            selection: None,
            exited: false,
            exit_code: None,
            scroll_offset: 0,
            history: VecDeque::new(),
            history_capacity,
        })
    }

    // ── I/O ──────────────────────────────────────────────────────────────────

    /// Drain pending PTY output and feed it to the vt100 parser.
    ///
    /// Lines that scroll off the live screen are captured into the
    /// scrollback ring buffer. Also polls child-process exit status.
    ///
    /// Returns `true` when any new data was processed — the caller
    /// should trigger a repaint.
    pub fn poll(&mut self) -> bool {
        let mut changed = false;
        while let Ok(data) = self.rx.try_recv() {
            changed = true;
            self.ingest(&data);
        }
        if !self.exited {
            if let Ok(Some(status)) = self.child.try_wait() {
                self.exited = true;
                self.exit_code = Some(status.exit_code());
                changed = true;
            }
        }
        changed
    }

    /// Answer VT query sequences the child sends *to the terminal*, the way
    /// any real terminal emulator (xterm, Windows Terminal, iTerm) does.
    ///
    /// `vt100::Parser` is a pure renderer/state-tracker: it never writes
    /// back to the PTY on its own. That is invisible on Unix, where an
    /// interactive shell at a bare prompt doesn't query the terminal. It is
    /// fatal on Windows: the ConPTY console host performs a VT-identity
    /// handshake on startup — a cursor-position query and/or a Device
    /// Attributes query, see [`terminal_query_replies`] for exactly which
    /// sequences — and blocks all further output on this session until
    /// something answers. Confirmed on real ConPTY hardware: a freshly
    /// spawned `cmd.exe` session sends exactly `ESC[6n` and then produces
    /// nothing else — `full_text()` stays empty — until this function
    /// replies.
    ///
    /// The actual scanning/matching is [`terminal_query_replies`], a pure
    /// function of the raw byte stream and the current cursor position —
    /// this method only supplies that cursor position and performs the
    /// write. Operating on the raw, not-yet-parsed byte stream means this
    /// has no effect on parsing/painting: it only ever *writes*, never
    /// consumes, the data handed to
    /// [`process_with_capture`](Self::process_with_capture).
    fn respond_to_terminal_queries(&mut self, data: &[u8]) {
        let cursor = self.parser.screen().cursor_position();
        let reply = terminal_query_replies(data, cursor);
        if !reply.is_empty() {
            let _ = self.writer.write_all(&reply);
            let _ = self.writer.flush();
        }
    }

    /// Consume one chunk of child output: answer any terminal queries in
    /// it, then parse it into the screen and scrollback.
    ///
    /// Every path that drains `rx` must go through here, not straight to
    /// [`process_with_capture`](Self::process_with_capture). A query that
    /// is parsed but never answered is lost for good, and on Windows an
    /// unanswered start-up handshake (see
    /// [`respond_to_terminal_queries`](Self::respond_to_terminal_queries))
    /// leaves the session permanently blank — which is what a resize issued
    /// before the shell's first output would otherwise cause.
    fn ingest(&mut self, data: &[u8]) {
        self.respond_to_terminal_queries(data);
        self.process_with_capture(data);
    }

    /// Send raw bytes as keyboard input to the shell.
    ///
    /// The bytes are written directly to the PTY master write-end.
    /// Callers are responsible for encoding key presses into the
    /// appropriate escape sequences (see the `key_to_pty_bytes` helper
    /// in the `tui_terminal` example).
    pub fn write_input(&mut self, data: &[u8]) {
        let _ = self.writer.write_all(data);
        let _ = self.writer.flush();
    }

    /// Send a UTF-8 string as input to the shell.
    ///
    /// Convenience wrapper around [`write_input`](Self::write_input).
    /// A supervising process uses this to inject prompts programmatically.
    pub fn send_str(&mut self, s: &str) {
        self.write_input(s.as_bytes());
    }

    // ── Benchmark / test support ─────────────────────────────────────────────

    /// Feed raw bytes directly into the ingest path [`poll()`](Self::poll)
    /// uses — the private `process_with_capture` helper, including its
    /// `set_scrollback` capture dance for rows that scroll off screen —
    /// bypassing the PTY reader thread entirely.
    ///
    /// `poll()` only ever reads from the background thread's channel, which
    /// is fed by a real child process; there is no other way to reach the
    /// private ingest code from outside this module. This hook exists so a
    /// throughput benchmark (`benches/terminal_throughput.rs`) can drive that
    /// exact path with synthetic, reproducible byte streams at whatever rate
    /// it likes, instead of being at the mercy of a real shell's scheduling
    /// and output timing — "no real PTY needed" per the issue.
    ///
    /// `#[doc(hidden)]`: this is bench/test plumbing, not part of the public
    /// API surface a consuming app should build on. A real app always goes
    /// through `poll()`.
    #[doc(hidden)]
    pub fn feed_for_bench(&mut self, data: &[u8]) {
        self.process_with_capture(data);
    }

    // ── Exit status ───────────────────────────────────────────────────────────

    /// Current terminal width in columns.
    pub fn cols(&self) -> u16 {
        self.cols
    }

    /// Current terminal height in rows.
    pub fn rows(&self) -> u16 {
        self.rows
    }

    /// `true` once the child process has exited.
    ///
    /// Use [`exit_code()`](Self::exit_code) for the numeric exit status.
    pub fn is_exited(&self) -> bool {
        self.exited
    }

    /// Current scroll offset (rows above the live bottom).
    ///
    /// `0` = live view; maximum = [`history_len()`](Self::history_len).
    /// Change via [`set_scroll_offset()`](Self::set_scroll_offset) /
    /// [`scroll_up()`](Self::scroll_up) / [`scroll_down()`](Self::scroll_down).
    pub fn scroll_offset(&self) -> usize {
        self.scroll_offset
    }

    /// Exit code of the child process, or `None` while still running.
    ///
    /// `0` conventionally means success. Populated by the first [`poll`](Self::poll)
    /// call that observes the child exiting. Check [`is_exited()`](Self::is_exited)
    /// first if you only need a boolean; this method returns the actual numeric code.
    pub fn exit_code(&self) -> Option<u32> {
        self.exit_code
    }

    // ── Window title (OSC 0/2) ────────────────────────────────────────────────

    /// The most recent window title set by the child program via an OSC 0 or
    /// OSC 2 escape sequence (e.g. `vim`, `tmux`, or a shell's own prompt
    /// hook), or `None` if it has never set one.
    pub fn title(&self) -> Option<&str> {
        self.parser.callbacks().title.as_deref()
    }

    /// `true` exactly once per title change: returns whether
    /// [`title()`](Self::title) has changed since the last call to this
    /// method, clearing the dirty flag as a side effect.
    ///
    /// Call this once per [`poll()`](Self::poll)-driven frame; a caller
    /// (e.g. the GTK runner) can use it to cheaply gate a native window
    /// title update instead of setting it on every frame.
    pub fn take_title_changed(&mut self) -> bool {
        std::mem::take(&mut self.parser.callbacks_mut().changed)
    }

    /// Returns `true` when the cursor should be rendered visible.
    ///
    /// The cursor is suppressed when:
    /// - The child process has exited ([`exited`](Self::exited) is `true`), or
    /// - The view is scrolled into history (`scroll_offset > 0`).
    ///
    /// Use this to gate cursor rendering in the app layer instead of
    /// relying on cell-level `is_cursor` flags alone.
    pub fn cursor_visible(&self) -> bool {
        !self.exited && self.scroll_offset == 0
    }

    // ── Cursor shape (DECSCUSR) ──────────────────────────────────────────────

    /// The child program's most recent DECSCUSR (`ESC [ Ps SP q`) cursor
    /// shape request — `Block` until the child sends one. `vim`/`zsh`
    /// and other readline-style line editors switch this to `Bar` on
    /// entering insert mode and back to `Block` on returning to normal
    /// mode; see [`decscusr_shape`] for the full `Ps` → shape table.
    ///
    /// [`to_terminal()`](Self::to_terminal) stamps this onto the cursor
    /// cell's [`TerminalCell::cursor_shape`](crate::TerminalCell::cursor_shape)
    /// automatically — most callers don't need to read this directly
    /// unless they're also steering a real hardware cursor
    /// (`Backend::set_caret_shape`) outside the cell-grid paint path.
    pub fn cursor_shape(&self) -> TerminalCursorShape {
        self.parser.callbacks().cursor_shape
    }

    /// Whether the child's most recent DECSCUSR request asked for a
    /// *blinking* cursor variant (odd `Ps`) rather than steady (even
    /// `Ps`) — `false` (steady) until the child sends a DECSCUSR
    /// sequence at all. See [`TerminalCell::cursor_blinking`](crate::TerminalCell::cursor_blinking)'s
    /// doc for how rasterisers use this.
    pub fn cursor_blinking(&self) -> bool {
        self.parser.callbacks().cursor_blinking
    }

    // ── Text scrape ───────────────────────────────────────────────────────────

    /// Extract the current vt100 live screen as plain text.
    ///
    /// Returns one line per screen row, trailing whitespace stripped.
    /// Completely blank rows at the **bottom** of the screen are omitted.
    /// This is the "what does the visible terminal look like right now?"
    /// getter — useful for programmatic drivers that need to scrape output
    /// (e.g. detecting a shell prompt line) without maintaining a full
    /// cell snapshot.
    pub fn screen_text(&self) -> String {
        let screen = self.parser.screen();
        let mut lines: Vec<String> = (0..self.rows)
            .map(|r| {
                let mut line = String::new();
                for c in 0..self.cols {
                    if let Some(cell) = screen.cell(r, c) {
                        let s = cell.contents();
                        if s.is_empty() {
                            line.push(' ');
                        } else {
                            line.push_str(s);
                        }
                    } else {
                        line.push(' ');
                    }
                }
                line.trim_end().to_string()
            })
            .collect();
        // Drop trailing blank rows.
        while lines.last().is_some_and(|l: &String| l.is_empty()) {
            lines.pop();
        }
        lines.join("\n")
    }

    /// Returns `true` when the child has enabled bracketed-paste mode
    /// (`ESC[?2004h`).
    ///
    /// Interactive programs (e.g. `claude`, shells with line editors) turn
    /// this mode on once their input prompt is live and ready to accept
    /// keystrokes, so it doubles as a reliable **input-readiness signal**
    /// for programmatic drivers: wait for this to flip `true` before
    /// injecting a bracketed paste, otherwise early bytes are silently
    /// dropped. Backed by vt100's tracking of the DEC private mode `2004`.
    pub fn bracketed_paste_enabled(&self) -> bool {
        self.parser.screen().bracketed_paste()
    }

    /// Send pasted text to the shell — the single paste entry point every
    /// paste source (GTK Ctrl-V/Ctrl-Shift-V, GTK middle-click PRIMARY
    /// selection, TUI crossterm bracketed paste) should call instead of
    /// hand-rolling the bracketed-paste wrap. Also the
    /// natural entry point for a future supervising process that wants to
    /// inject text programmatically, though nothing wires that up today.
    ///
    /// Wraps `text` in bracketed-paste markers (`ESC[200~ ... ESC[201~`)
    /// when the child has enabled bracketed-paste mode
    /// ([`bracketed_paste_enabled`](Self::bracketed_paste_enabled)), so
    /// programs that understand it (readline-based shells, `vim`, `claude`,
    /// ...) can tell pasted text apart from typed text — most importantly,
    /// so pasted newlines don't get interpreted as "run this line" one at a
    /// time. Sends `text` raw when the child hasn't enabled that mode,
    /// since wrapping unconditionally would leak literal escape bytes into
    /// programs that don't strip them (e.g. `cat`, `less`).
    ///
    /// Also resets the scroll offset to the live view — like ordinary
    /// keystroke input — so a paste is always visible immediately even if
    /// the user had scrolled into history first.
    pub fn paste(&mut self, text: &str) {
        self.scroll_reset();
        let bytes = encode_paste(text, self.bracketed_paste_enabled());
        self.write_input(&bytes);
    }

    /// Returns `true` when the child has enabled application-cursor-keys mode
    /// (DECCKM, DEC private mode `?1h` / `ESC [ ? 1 h`).
    ///
    /// In this mode, **unmodified** arrow keys and Home/End must be encoded as
    /// SS3 sequences (`ESC O A`…`ESC O D`, `ESC O H`, `ESC O F`) rather than
    /// the normal CSI sequences (`ESC [ A`…`ESC [ 4 ~`). Modifier combinations
    /// (e.g. Ctrl+Up) continue to use the CSI form regardless of this flag.
    ///
    /// Full-TUI programs — `vim`, `neovim`, `claude`, `htop` — set DECCKM when
    /// active. Without honouring it, navigation inside those programs silently
    /// stops working. [`encode_key`](Self::encode_key) queries this flag for
    /// you each keystroke; call this directly only if you're hand-rolling the
    /// encoding.
    ///
    /// Backed by [`vt100::Screen::application_cursor`].
    pub fn application_cursor_keys(&self) -> bool {
        self.parser.screen().application_cursor()
    }

    // ── Keyboard → PTY encoding ───────────────────────────────────────────────

    /// Encode a key press as PTY bytes, reading the child's DECCKM
    /// (application-cursor-keys) state internally so callers don't have to
    /// thread [`application_cursor_keys`](Self::application_cursor_keys)
    /// through themselves.
    ///
    /// Returns `None` for keys with no meaningful PTY encoding (e.g.
    /// CapsLock) — callers should treat that as "swallow this keystroke",
    /// not as an error.
    ///
    /// This is the read-only half; most callers want
    /// [`write_key`](Self::write_key), which also writes the bytes and
    /// resets the scroll offset the same way [`paste`](Self::paste) does.
    pub fn encode_key(&self, key: Key, mods: Modifiers) -> Option<Vec<u8>> {
        key_to_pty_bytes(key, mods, self.application_cursor_keys())
    }

    /// Encode a key press with [`encode_key`](Self::encode_key) and write it
    /// to the PTY, resetting the scroll offset to the live view first (like
    /// [`paste`](Self::paste) and ordinary character input) so a keystroke
    /// is always visible immediately even if the user had scrolled into
    /// history. Returns `true` when bytes were written.
    ///
    /// Callers embedding a full interactive shell (arrows, F-keys,
    /// modifiers, Ctrl-combos) should route `UiEvent::KeyPressed` here
    /// instead of hand-rolling the escape-sequence encoding — see
    /// `examples/common/terminal_app.rs` for the reference wiring.
    pub fn write_key(&mut self, key: Key, mods: Modifiers) -> bool {
        match self.encode_key(key, mods) {
            Some(bytes) => {
                self.scroll_reset();
                self.write_input(&bytes);
                true
            }
            None => false,
        }
    }

    // ── Alt-screen + mouse reporting state ───────────────────────────────────

    /// `true` when the child is currently rendering on the alternate screen
    /// (DEC private mode `1047` / `1049`, or legacy `47`).
    pub fn on_alt_screen(&self) -> bool {
        self.parser.screen().alternate_screen()
    }

    /// `true` when the child has enabled any xterm mouse-reporting mode
    /// (DEC private modes `1000` / `1002` / `1003`). Independent of the
    /// `1006` (SGR) encoding bit, which selects the wire format but doesn't
    /// turn reporting on or off.
    ///
    /// Used by [`should_forward_wheel`](Self::should_forward_wheel) and
    /// [`forward_mouse`](Self::forward_mouse) to decide whether mouse events
    /// belong to the child rather than our local UI (selection, scrollback).
    pub fn mouse_reporting_enabled(&self) -> bool {
        self.parser.screen().mouse_protocol_mode() != vt100::MouseProtocolMode::None
    }

    /// Whether wheel scroll events should be forwarded to the PTY child
    /// rather than handled locally.
    pub fn should_forward_wheel(&self) -> bool {
        self.mouse_reporting_enabled() || self.on_alt_screen()
    }

    // ── Mouse → PTY forwarding ────────────────────────────────────────────────

    /// Encode a mouse event as SGR-1006 PTY bytes, **without** writing it.
    ///
    /// Returns `None` when the engine has determined the event should not be
    /// reported to the child:
    ///
    /// - Wheel events are gated on
    ///   [`should_forward_wheel`](Self::should_forward_wheel).
    /// - Press / Release / Move are gated on
    ///   [`mouse_reporting_enabled`](Self::mouse_reporting_enabled).
    ///
    /// Callers that want to bypass the gate (e.g. for testing) can call the
    /// free function [`encode_mouse_sgr`] directly.
    pub fn encode_mouse(
        &self,
        kind: TerminalMouseKind,
        button: MouseButton,
        col: u16,
        row: u16,
        modifiers: Modifiers,
    ) -> Option<Vec<u8>> {
        let allow = match kind {
            TerminalMouseKind::WheelUp | TerminalMouseKind::WheelDown => {
                self.should_forward_wheel()
            }
            _ => self.mouse_reporting_enabled(),
        };
        if !allow {
            return None;
        }
        Some(encode_mouse_sgr(kind, button, col, row, modifiers))
    }

    /// Forward a mouse event to the PTY child as SGR-1006 bytes, gated on
    /// the current reporting / alt-screen state.
    ///
    /// Returns `true` when bytes were written. When `false`, the caller
    /// should fall back to local handling — wheel events scroll our own
    /// scrollback ([`scroll_up`](Self::scroll_up) / [`scroll_down`](Self::scroll_down)),
    /// clicks drive local selection, etc.
    pub fn forward_mouse(
        &mut self,
        kind: TerminalMouseKind,
        button: MouseButton,
        col: u16,
        row: u16,
        modifiers: Modifiers,
    ) -> bool {
        match self.encode_mouse(kind, button, col, row, modifiers) {
            Some(bytes) => {
                self.write_input(&bytes);
                true
            }
            None => false,
        }
    }

    /// Canonical wheel-notch policy: try to forward the wheel to the PTY
    /// child, and fall back to scrolling local scrollback when it doesn't
    /// take it.
    ///
    /// This is the forward-vs-scrollback composition every consumer was
    /// re-deriving by hand: "is the child on the alt-screen
    /// or reporting mouse events? If so, let it paginate itself. Otherwise
    /// scroll our own scrollback by `step` rows." Equivalent to:
    ///
    /// ```ignore
    /// let kind = if up { WheelUp } else { WheelDown };
    /// if !sess.forward_mouse(kind, MouseButton::Left, col, row, Modifiers::default()) {
    ///     if up { sess.scroll_up(step) } else { sess.scroll_down(step) }
    /// }
    /// ```
    ///
    /// `col`/`row` are the cell the pointer is over (0-based, clamped to
    /// the viewport by the caller). SGR-1006 always encodes the pointer
    /// position on the wire ([`encode_mouse_sgr`]), and real alt-screen
    /// consumers — tmux is the canonical example — use it to route wheel
    /// input to the pane under the cursor, so the caller must supply the
    /// real position rather than a fixed `(0, 0)`.
    ///
    /// Returns `true` when the event was written to the child (the caller
    /// must not also touch local scrollback), `false` when it fell back to
    /// [`scroll_up`](Self::scroll_up) / [`scroll_down`](Self::scroll_down).
    pub fn handle_wheel(&mut self, up: bool, step: usize, col: u16, row: u16) -> bool {
        let kind = if up {
            TerminalMouseKind::WheelUp
        } else {
            TerminalMouseKind::WheelDown
        };
        let forwarded = self.forward_mouse(kind, MouseButton::Left, col, row, Modifiers::default());
        if !forwarded {
            if up {
                self.scroll_up(step);
            } else {
                self.scroll_down(step);
            }
        }
        forwarded
    }

    /// Extract all captured scrollback history as plain text.
    ///
    /// Returns one line per history row (oldest first), trailing
    /// whitespace stripped, joined by newlines. Does **not** include the
    /// live screen — call [`screen_text`](Self::screen_text) for that, or
    /// [`full_text`](Self::full_text) for both together.
    pub fn scrollback_text(&self) -> String {
        let mut lines: Vec<String> = self
            .history
            .iter()
            .map(|row| {
                let mut line = String::new();
                for hc in row {
                    line.push_str(&hc.text);
                }
                line.trim_end().to_string()
            })
            .collect();
        // Drop trailing blank rows.
        while lines.last().is_some_and(|l: &String| l.is_empty()) {
            lines.pop();
        }
        lines.join("\n")
    }

    /// Concatenate [`scrollback_text`](Self::scrollback_text) and
    /// [`screen_text`](Self::screen_text) into a single string, separated
    /// by a newline when both are non-empty.
    ///
    /// Useful for programmatic scraping: scan `full_text()` for a prompt or
    /// completion marker after each `poll()` cycle.
    pub fn full_text(&self) -> String {
        let hist = self.scrollback_text();
        let live = self.screen_text();
        match (hist.is_empty(), live.is_empty()) {
            (true, _) => live,
            (_, true) => hist,
            _ => format!("{hist}\n{live}"),
        }
    }

    // ── Resize ───────────────────────────────────────────────────────────────

    /// Resize the PTY and update the vt100 parser dimensions.
    ///
    /// Sends SIGWINCH to the child process so running programs
    /// (e.g. `vim`, `htop`) re-layout their output.
    ///
    /// # Preserving content across a width change
    ///
    /// vt100 0.16's `set_size` does **not** reflow — it truncates each
    /// row on a column shrink and pads with blanks on a widen, so a naive
    /// shrink→expand drag loses text permanently. We restore logical-line
    /// reflow via [`reflow_screen`] (public-API snapshot → resize → replay),
    /// gated to genuine width changes on the normal screen. This runs in the
    /// shared engine, so **both** the TUI and GTK backends get it for free.
    ///
    /// # Closing the shell-redraw-vs-resize race
    ///
    /// The shared engine also guards against a *timing* bug in the resize
    /// sequence:
    pub fn resize(&mut self, cols: u16, rows: u16) {
        // See `MIN_VT100_ROWS`/`MIN_VT100_COLS`'s docs — vt100 panics below these.
        let (cols, rows) = clamp_vt100_size(cols, rows);
        // No-op guard: avoid a needless resize + SIGWINCH storm when the
        // caller re-sends the current size (common when a backend recomputes
        // the same cell dimensions every frame during a drag).
        if cols == self.cols && rows == self.rows {
            return;
        }
        // Drain + process any output queued at the *current* size before we
        // change dimensions, so in-flight redraws land on the grid they were
        // computed for rather than the one we are about to re-size to.
        while let Ok(data) = self.rx.try_recv() {
            self.ingest(&data);
        }
        self.cols = cols;
        self.rows = rows;
        // Re-wrap on-screen content to the new width instead of truncating it
        // (see [`reflow_screen`]); height-only / alt-screen changes fall back to
        // the plain non-reflow resize internally.
        reflow_screen(&mut self.parser, rows, cols);
        let _ = self.master.resize(PtySize {
            rows,
            cols,
            pixel_width: 0,
            pixel_height: 0,
        });
        // Consume the child's post-SIGWINCH redraw at *this* width before we
        // return, so a subsequent fast resize can't reparse it at a new width.
        self.settle_after_resize();
    }

    /// Consume the child's post-SIGWINCH redraw so a rapid follow-up resize
    /// can't reparse those cursor-relative bytes against a grid whose width has
    /// since changed.
    fn settle_after_resize(&mut self) {
        for chunk in collect_post_resize_output(&self.rx) {
            self.ingest(&chunk);
        }
    }

    // ── Scrollback ───────────────────────────────────────────────────────────

    /// Number of scrollback rows captured so far.
    pub fn history_len(&self) -> usize {
        self.history.len()
    }

    /// Set the scroll offset.
    ///
    /// `0` = live view. `history_len()` = oldest available row at the top.
    /// Clamped to `[0, history_len()]`.
    pub fn set_scroll_offset(&mut self, offset: usize) {
        self.scroll_offset = offset.min(self.history.len());
        // Keep the vt100 parser at the live view at all times.
        self.parser.screen_mut().set_scrollback(0);
    }

    /// Scroll up into history by `n` rows.
    pub fn scroll_up(&mut self, n: usize) {
        let new = self.scroll_offset.saturating_add(n);
        self.set_scroll_offset(new);
    }

    /// Scroll down toward the live view by `n` rows.
    pub fn scroll_down(&mut self, n: usize) {
        let new = self.scroll_offset.saturating_sub(n);
        self.set_scroll_offset(new);
    }

    /// Return to the live view (`scroll_offset = 0`).
    pub fn scroll_reset(&mut self) {
        self.set_scroll_offset(0);
    }

    // ── Selection helpers ─────────────────────────────────────────────────────

    /// Extract selected text, blending history and live screen correctly.
    ///
    /// Selection coordinates (`TerminalSelection`) are always in
    /// **display-row** space (0-based from the visible top), which is the
    /// same coordinate system `build_rows` uses.  This means the function
    /// works at any `scroll_offset`, including inside scrollback history.
    ///
    /// Returns `None` when there is no active selection.
    pub fn selected_text(&self) -> Option<String> {
        let sel = self.selection.as_ref()?;
        let (r0, c0, r1, c1) = normalize_selection(sel);
        let mut lines: Vec<String> = Vec::new();
        for row in r0..=r1 {
            let mut line = String::new();
            let col_start = if row == r0 { c0 } else { 0 };
            let col_end = if row == r1 {
                c1
            } else {
                self.cols.saturating_sub(1)
            };
            for col in col_start..=col_end {
                line.push_str(&self.cell_content_at_display_row(row as usize, col));
            }
            lines.push(line.trim_end().to_string());
        }
        Some(lines.join("\n"))
    }

    /// Return the text content of the cell at the given **display row** and
    /// column, resolving from `self.history` when
    /// `display_r < self.scroll_offset` or from the live vt100 screen
    /// otherwise.
    ///
    /// Returns a single space for empty or out-of-range cells, matching the
    /// convention used by [`selected_text`](Self::selected_text).  This is
    /// the canonical blending helper — both `selected_text` and `build_rows`
    /// use the same mapping so the two can never drift apart.
    fn cell_content_at_display_row(&self, display_r: usize, col: u16) -> String {
        let scroll_offset = self.scroll_offset;
        let hist_len = self.history.len();

        if display_r < scroll_offset {
            let hist_idx_signed = hist_len as isize - scroll_offset as isize + display_r as isize;
            if hist_idx_signed >= 0 {
                if let Some(hist_row) = self.history.get(hist_idx_signed as usize) {
                    return hist_row.get(col as usize).cloned().unwrap_or_default().text;
                }
            }
            " ".to_string()
        } else {
            let live_r = (display_r - scroll_offset) as u16;
            let screen = self.parser.screen();
            if let Some(cell) = screen.cell(live_r, col) {
                let s = cell.contents();
                if s.is_empty() {
                    " ".to_string()
                } else {
                    s.to_string()
                }
            } else {
                " ".to_string()
            }
        }
    }

    // ── Snapshot ──────────────────────────────────────────────────────────────

    /// Build a paint snapshot for [`Backend::draw_terminal`].
    ///
    /// Pass `Some(scrollbar)` (e.g. from [`scrollbar_state`](Self::scrollbar_state))
    /// to show a scrollbar when the history is non-empty.
    pub fn to_terminal(&self, id: WidgetId, scrollbar: Option<TerminalScrollbar>) -> Terminal {
        Terminal {
            id,
            cells: self.build_rows(true),
            scrollbar,
        }
    }

    /// Build a `TerminalScrollbar` reflecting the current scrollback state.
    ///
    /// - `scrollbar_width`: visual width in backend-native units.
    ///   `None` → backend default (1 TUI cell, ~8 px GTK).
    ///
    /// The scrollbar uses `inverted = true` so that offset `0` (live view)
    /// places the thumb at the track bottom, matching normal terminal UX.
    pub fn scrollbar_state(&self, scrollbar_width: Option<u16>) -> TerminalScrollbar {
        let total = self.history.len() + self.rows as usize;
        TerminalScrollbar {
            total_lines: total,
            visible_lines: self.rows as usize,
            scroll_offset: self.scroll_offset,
            inverted: true,
            width: scrollbar_width,
        }
    }

    // ── Private implementation ────────────────────────────────────────────────

    /// Process a data chunk, splitting at `rows`-newline boundaries so
    /// that each sub-chunk causes at most `rows` lines to scroll off
    /// the live screen — the safe maximum for vt100's scrollback read-back.
    fn process_with_capture(&mut self, data: &[u8]) {
        let max_nl = self.rows as usize;
        let mut start = 0;
        let mut nl_count = 0;

        for (i, &b) in data.iter().enumerate() {
            if b == b'\n' {
                nl_count += 1;
                if nl_count >= max_nl {
                    let chunk = &data[start..=i];
                    if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                        self.parser.process(chunk);
                    }))
                    .is_err()
                    {
                        crate::diagnostics::emit(
                            "quadraui: vt100 parser panic in process_with_capture; \
                             dropping chunk, session kept alive",
                        );
                    }
                    self.capture_scrolled_rows(nl_count);
                    start = i + 1;
                    nl_count = 0;
                }
            }
        }
        if start < data.len() {
            let chunk = &data[start..];
            let remaining_nl = chunk.iter().filter(|&&b| b == b'\n').count();
            if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                self.parser.process(chunk);
            }))
            .is_err()
            {
                crate::diagnostics::emit(
                    "quadraui: vt100 parser panic in process_with_capture; \
                     dropping chunk, session kept alive",
                );
            }
            if remaining_nl > 0 {
                self.capture_scrolled_rows(remaining_nl);
            }
        }
    }

    /// Read the rows that just scrolled off the live screen top and append
    /// them to `self.history`.
    ///
    /// Temporarily shifts the vt100 viewport to see the rows that just
    /// scrolled off (they're still in the vt100 internal scrollback at
    /// this point), reads them, then restores the live view.
    ///
    /// Skipped entirely while the child is on the alternate screen — vt100
    /// keeps a separate scrollback buffer for the alt grid and full-TUI
    /// apps re-render every frame, so capturing those rows would both leak
    /// frame churn into the shell's scrollback **and** read from the wrong
    /// grid. The check is evaluated *after* `parser.process(...)` so the
    /// mode-switch escape (`ESC[?1049h` / `ESC[?1049l`) takes effect first.
    fn capture_scrolled_rows(&mut self, n_newlines: usize) {
        if self.parser.screen().alternate_screen() {
            return;
        }
        let to_capture = n_newlines.min(self.rows as usize);
        self.parser.screen_mut().set_scrollback(to_capture);
        {
            let screen = self.parser.screen();
            for r in 0..to_capture as u16 {
                let row: Vec<HistCell> = (0..self.cols)
                    .map(|c| match screen.cell(r, c) {
                        Some(cell) => {
                            let raw = cell.contents();
                            HistCell {
                                // vt100's own convention for an empty /
                                // never-written cell (including a wide
                                // glyph's trailing spacer column) is
                                // `contents() == ""` — normalise that to
                                // a single space rather than storing an
                                // empty grapheme, so history playback
                                // still occupies its column
                                text: if raw.is_empty() {
                                    " ".to_string()
                                } else {
                                    raw.to_string()
                                },
                                fg: cell.fgcolor(),
                                bg: cell.bgcolor(),
                                bold: cell.bold(),
                                italic: cell.italic(),
                                underline: cell.underline(),
                                dim: cell.dim(),
                            }
                        }
                        None => HistCell::default(),
                    })
                    .collect();
                if self.history_capacity > 0 && self.history.len() >= self.history_capacity {
                    self.history.pop_front();
                }
                self.history.push_back(row);
            }
        }
        self.parser.screen_mut().set_scrollback(0);
    }

    /// Build the full cell grid for the current view.
    ///
    /// Blends history rows (when `scroll_offset > 0`) with live screen rows.
    /// `cursor_active` controls whether the vt100 cursor position is marked
    /// `is_cursor = true` in the snapshot.
    fn build_rows(&self, cursor_active: bool) -> Vec<Vec<TerminalCell>> {
        let screen = self.parser.screen();
        let (cursor_row, cursor_col) = screen.cursor_position();
        let rows_count = self.rows as usize;
        let cols_count = self.cols as usize;
        let scroll_offset = self.scroll_offset;
        let hist_len = self.history.len();
        // Read once per snapshot rather than per cell — the DECSCUSR
        // state applies to at most one cell (the cursor
        // cell, if any), same as `cursor_row`/`cursor_col` above.
        let cur_shape = self.cursor_shape();
        let cur_blinking = self.cursor_blinking();

        // Selection coordinates are always in display-row space (0 = visible
        let sel_bounds = self.selection.as_ref().map(normalize_selection);

        // Closure: is the cell at (display_r, cu) inside the selection?
        // Uses display-row coordinates throughout — no offset math needed.
        let is_selected = |display_r: usize, cu: u16| -> bool {
            sel_bounds.is_some_and(|(r0, c0, r1, c1)| {
                let dr = display_r as u16;
                if r0 == r1 {
                    dr == r0 && cu >= c0 && cu <= c1
                } else if dr == r0 {
                    cu >= c0
                } else if dr == r1 {
                    cu <= c1
                } else {
                    dr > r0 && dr < r1
                }
            })
        };

        (0..rows_count)
            .map(|display_r| {
                (0..cols_count)
                    .map(|c| {
                        let cu = c as u16;

                        let (text, fg, bg, bold, italic, underline, dim, is_cursor, selected) =
                            if display_r < scroll_offset {
                                // Row is in the scrollback history.
                                let hist_idx_signed =
                                    hist_len as isize - scroll_offset as isize + display_r as isize;
                                if hist_idx_signed >= 0 {
                                    if let Some(hist_row) =
                                        self.history.get(hist_idx_signed as usize)
                                    {
                                        let hc = hist_row.get(c).cloned().unwrap_or_default();
                                        (
                                            hc.text,
                                            map_vt100_color(hc.fg, false),
                                            map_vt100_color(hc.bg, true),
                                            hc.bold,
                                            hc.italic,
                                            hc.underline,
                                            hc.dim,
                                            false,
                                            is_selected(display_r, cu),
                                        )
                                    } else {
                                        (
                                            " ".to_string(),
                                            (229, 229, 229),
                                            (30, 30, 30),
                                            false,
                                            false,
                                            false,
                                            false,
                                            false,
                                            is_selected(display_r, cu),
                                        )
                                    }
                                } else {
                                    (
                                        " ".to_string(),
                                        (229, 229, 229),
                                        (30, 30, 30),
                                        false,
                                        false,
                                        false,
                                        false,
                                        false,
                                        false,
                                    )
                                }
                            } else {
                                // Row is in the live vt100 screen.
                                let live_r = (display_r - scroll_offset) as u16;
                                let (text, fg, bg, bold, italic, underline, dim) =
                                    if let Some(cell) = screen.cell(live_r, cu) {
                                        let contents = cell.contents();
                                        // Full grapheme cluster (base char
                                        // + any combining marks), not just
                                        // the first char — and vt100's
                                        // empty-string convention for a
                                        // blank / wide-glyph continuation
                                        // cell normalises to a single
                                        // space so it still occupies its
                                        // column.
                                        let text = if contents.is_empty() {
                                            " ".to_string()
                                        } else {
                                            contents.to_string()
                                        };
                                        (
                                            text,
                                            map_vt100_color(cell.fgcolor(), false),
                                            map_vt100_color(cell.bgcolor(), true),
                                            cell.bold(),
                                            cell.italic(),
                                            cell.underline(),
                                            cell.dim(),
                                        )
                                    } else {
                                        (
                                            " ".to_string(),
                                            (229, 229, 229),
                                            (30, 30, 30),
                                            false,
                                            false,
                                            false,
                                            false,
                                        )
                                    };

                                let is_cursor = !self.exited
                                    && scroll_offset == 0
                                    && cursor_active
                                    && live_r == cursor_row
                                    && cu == cursor_col;

                                (
                                    text,
                                    fg,
                                    bg,
                                    bold,
                                    italic,
                                    underline,
                                    dim,
                                    is_cursor,
                                    is_selected(display_r, cu),
                                )
                            };

                        TerminalCell {
                            text,
                            fg: Color::rgb(fg.0, fg.1, fg.2),
                            bg: Color::rgb(bg.0, bg.1, bg.2),
                            bold,
                            italic,
                            underline,
                            dim,
                            selected,
                            is_cursor,
                            is_find_match: false,
                            is_find_active: false,
                            cursor_shape: if is_cursor {
                                cur_shape
                            } else {
                                TerminalCursorShape::default()
                            },
                            cursor_blinking: is_cursor && cur_blinking,
                        }
                    })
                    .collect()
            })
            .collect()
    }
}

// ── TerminalManager ───────────────────────────────────────────────────────────

/// Multi-tab terminal manager.
///
/// Owns a `Vec<TerminalSession>` and tracks the active index. Provides
/// CRUD methods for sessions and a [`poll_all`](Self::poll_all) helper
/// for the event-loop tick.
///
/// ## Keybindings and coupling
///
/// Alt+1-9 tab switching, Ctrl+W close, and split-pane keybindings are
/// **not** part of this type. Consuming apps implement those in their
/// `AppLogic::handle` method and call the appropriate methods here.
pub struct TerminalManager {
    /// All open sessions.
    pub sessions: Vec<TerminalSession>,
    /// Index of the currently-active session.
    pub active: usize,
}

impl TerminalManager {
    /// Create a new manager with no open sessions.
    pub fn new() -> Self {
        Self {
            sessions: Vec::new(),
            active: 0,
        }
    }

    /// Reference to the active session, or `None` if empty.
    pub fn active_session(&self) -> Option<&TerminalSession> {
        self.sessions.get(self.active)
    }

    /// Mutable reference to the active session, or `None` if empty.
    pub fn active_session_mut(&mut self) -> Option<&mut TerminalSession> {
        self.sessions.get_mut(self.active)
    }

    /// Spawn a new session and make it active. Returns the new index.
    pub fn new_session(
        &mut self,
        cols: u16,
        rows: u16,
        shell: &str,
        cwd: &Path,
        history_capacity: usize,
    ) -> Result<usize, Box<dyn std::error::Error>> {
        let session = TerminalSession::spawn(cols, rows, shell, cwd, history_capacity)?;
        self.sessions.push(session);
        self.active = self.sessions.len() - 1;
        Ok(self.active)
    }

    /// Close the active session. The adjacent session becomes active;
    /// `active` is reset to `0` when the last session is removed.
    pub fn close_active(&mut self) {
        if self.sessions.is_empty() {
            return;
        }
        self.sessions.remove(self.active);
        if self.sessions.is_empty() {
            self.active = 0;
        } else {
            self.active = self.active.min(self.sessions.len() - 1);
        }
    }

    /// Switch to session `idx` (clamped to `[0, len-1]`).
    pub fn switch_to(&mut self, idx: usize) {
        if !self.sessions.is_empty() {
            self.active = idx.min(self.sessions.len() - 1);
        }
    }

    /// Poll every session for PTY output. Returns `true` when any
    /// session produced new data (the caller should schedule a repaint).
    pub fn poll_all(&mut self) -> bool {
        self.sessions.iter_mut().fold(false, |acc, s| {
            let changed = s.poll();
            acc || changed
        })
    }

    /// Number of open sessions.
    pub fn len(&self) -> usize {
        self.sessions.len()
    }

    /// `true` when there are no open sessions.
    pub fn is_empty(&self) -> bool {
        self.sessions.is_empty()
    }
}

impl Default for TerminalManager {
    fn default() -> Self {
        Self::new()
    }
}

// ── Utility ───────────────────────────────────────────────────────────────────

/// Return the user's preferred interactive shell, for spawning an
/// interactive [`TerminalSession`].
///
/// Reads `$SHELL` on Unix, falling back to `/bin/bash` when unset.
/// **Never reads `$SHELL` on Windows.** An interop tab (Git Bash, WSL)
/// can export a Unix-style `$SHELL` into a native Windows process's
/// environment even though the host itself has no such variable set —
/// handing that path straight to a native ConPTY spawn would be wrong
/// regardless of what else is going on in the spawn/poll path. The
/// Windows branch always returns `powershell.exe`, unconditionally.
pub fn default_shell() -> String {
    #[cfg(target_os = "windows")]
    {
        default_shell_for(ShellPlatform::Windows, None)
    }
    #[cfg(not(target_os = "windows"))]
    {
        default_shell_for(ShellPlatform::Unix, std::env::var("SHELL").ok())
    }
}

/// Pure decision logic behind [`default_shell`]: given the platform and
/// whatever `$SHELL` read produced (always `None` on the Windows branch —
/// see [`default_shell`]'s doc for why that read must never happen at
/// all), returns the interactive shell binary to spawn.
///
/// Factored out exactly like [`shell_command_for`], and for the
/// same reason: tests can cover both platform branches, and both
/// "env var set" / "env var unset" cases, from a single build without
/// mutating the process-global `$SHELL` state every other test in this
/// binary shares (see `shell_command_for`'s doc).
fn default_shell_for(platform: ShellPlatform, env_shell: Option<String>) -> String {
    match platform {
        ShellPlatform::Windows => "powershell.exe".to_string(),
        ShellPlatform::Unix => env_shell.unwrap_or_else(|| "/bin/bash".to_string()),
    }
}

/// Which "run a command string through the shell" convention applies.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ShellPlatform {
    #[cfg_attr(all(not(test), target_os = "windows"), allow(dead_code))]
    Unix,
    #[cfg_attr(not(any(test, target_os = "windows")), allow(dead_code))]
    Windows,
}

/// Pure decision logic behind [`shell_command`]: given the platform and the
/// already-read environment override (if any), returns `(shell, flag)`.
///
/// Factored out from [`shell_command`] so tests can cover both platform
/// branches and both "env var set" / "env var unset" cases without
/// mutating process-global `$SHELL` / `%COMSPEC%` state — that state is
/// shared with every other test in this binary (e.g.
/// `default_shell_is_nonempty` reads `$SHELL` too), so flipping it here
/// would race them under the default parallel test runner.
fn shell_command_for(platform: ShellPlatform, env_shell: Option<String>) -> (String, String) {
    match platform {
        ShellPlatform::Windows => (
            env_shell.unwrap_or_else(|| "cmd".to_string()),
            "/C".to_string(),
        ),
        ShellPlatform::Unix => (
            env_shell.unwrap_or_else(|| "sh".to_string()),
            "-c".to_string(),
        ),
    }
}

/// Returns the platform's shell binary plus its "run this command string"
/// flag, honouring `$SHELL` (Unix) / `%COMSPEC%` (Windows) where set —
/// the portable seam behind `Command::new(shell).arg(flag).arg(command)`.
///
/// Sibling of [`default_shell`]: `default_shell()` names a shell for an
/// *interactive* PTY session (used by [`TerminalSession::spawn`]);
/// `shell_command()` is for launching a single command string through
/// "the user's shell" — the case vimcode's `:!`, `:r !`, `!{motion}`
/// filters, and plugin async shells all hardcode as `Command::new("sh")`
/// today, with no Windows leg. `default_shell()`'s own
/// behaviour is unchanged by this function's addition.
///
/// Falls back to `("sh", "-c")` on Unix and `("cmd", "/C")` on Windows
/// when the relevant environment variable isn't set. Both fallbacks are
/// resolved via `PATH` by the process spawner (`std::process::Command`
/// / `portable_pty::CommandBuilder`), not by an absolute path, matching
/// `core/lsp_manager.rs`'s existing `cmd /C` vs `sh -c` split in vimcode.
///
/// # Example
///
/// ```
/// use quadraui::terminal_engine::shell_command;
///
/// let (shell, flag) = shell_command();
/// let mut cmd = std::process::Command::new(shell);
/// cmd.arg(flag).arg("echo hello");
/// ```
pub fn shell_command() -> (String, String) {
    #[cfg(target_os = "windows")]
    {
        shell_command_for(ShellPlatform::Windows, std::env::var("COMSPEC").ok())
    }
    #[cfg(not(target_os = "windows"))]
    {
        shell_command_for(ShellPlatform::Unix, std::env::var("SHELL").ok())
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

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

    // ── Regression: vt100 0.15.2 alt-screen resize cursor-clamp panic ─

    /// Reproduces the exact crash sequence from issue #397:
    #[test]
    fn vt100_alt_screen_resize_cursor_clamp_no_panic() {
        // 40-row × 80-col grid.  Row indices are 0-based inside vt100.
        let mut p = vt100::Parser::new(40, 80, 0);

        // Move cursor to row 35 (1-indexed: ESC[36;1H).
        // Row 35 ≥ the future 20-row height, so restoring it unpatched → OOB.
        p.process(b"\x1b[36;1H");
        let (row, col) = p.screen().cursor_position();
        assert_eq!(row, 35, "cursor must be at row 35 before alt-screen enter");
        assert_eq!(col, 0);

        // Enter alternate screen — DEC saves cursor (saves row=35).
        p.process(b"\x1b[?1049h");
        assert!(p.screen().alternate_screen(), "must be on alternate screen");

        // Resize to 20 rows.  On 0.15.2 saved_pos.row remains 35 — this is the bug.
        p.screen_mut().set_size(20, 80);

        // Exit alternate screen — restores saved cursor (row=35 on 0.15.2 → OOB panic).
        p.process(b"\x1b[?1049l");
        assert!(
            !p.screen().alternate_screen(),
            "must have left alternate screen"
        );

        // Print a printable byte.  On 0.15.2 this panics at Grid::drawing_cell.
        p.process(b"X"); // must not panic

        // The restored cursor row MUST be clamped inside the new 20-row grid.
        let (restored_row, _) = p.screen().cursor_position();
        assert!(
            restored_row < 20,
            "restored cursor row {restored_row} must be < 20 (new grid height)"
        );
    }

    /// The same #397 crash sequence, driven end-to-end through a **real
    /// `TerminalSession`** rather than a bare `vt100::Parser`.
    #[test]
    #[cfg(unix)]
    fn session_alt_screen_resize_cursor_clamp_no_panic() {
        let cwd = std::env::temp_dir();
        // 40 rows: tall enough to park the cursor at row 35, well below the
        // 20-row height we shrink to mid-alt-screen.
        let mut sess =
            TerminalSession::spawn(80, 40, "/bin/sh", &cwd, 1000).expect("failed to spawn /bin/sh");

        // Steps 1+2: park the cursor at row 35 (ESC[36;1H, 1-indexed) and enter
        // the alternate screen — vt100 DEC-saves the cursor, recording row 35.
        sess.send_str("printf '\\033[36;1H\\033[?1049h'\n");
        assert!(
            poll_until(&mut sess, 5000, |s| s.on_alt_screen()),
            "child should have entered the alternate screen"
        );

        // Step 3: the host shrinks the pane while the child is on the alt
        // screen. On vt100 0.15.2 this clamped `pos` but left `saved_pos.row`
        // at 35 — the bug.
        sess.resize(80, 20);
        assert_eq!(sess.rows(), 20, "resize should have taken effect");

        // Steps 4+5: leave the alternate screen (DEC-restores the saved cursor)
        // and print a byte at the restored position. On 0.15.2 the byte hit
        // `Grid::drawing_cell(35).unwrap()` → `None` → panic inside
        // `process_with_capture`.
        sess.send_str("printf '\\033[?1049lX'\n");
        assert!(
            poll_until(&mut sess, 5000, |s| !s.on_alt_screen()),
            "child should have left the alternate screen"
        );

        // The session must still be usable: if the parser had panicked, the
        // chunk would have been dropped — and a regression in the catch_unwind
        // wiring (e.g. swallowing all subsequent input) shows up right here.
        sess.send_str("echo still-alive\n");
        assert!(
            poll_until(&mut sess, 5000, |s| s.screen_text().contains("still-alive")),
            "session must still process input after the alt-screen resize round-trip"
        );
        assert!(!sess.is_exited(), "session must not have died");

        sess.send_str("exit\n");
    }

    // ── Regression: vt100 0.15.2 wide-char column-boundary panic ────────────

    /// Feed wide Unicode characters to the vt100 parser such that a 2-cell
    /// glyph straddles or lands exactly at the right column edge.  The
    /// patched vt100 must NOT panic; before the patch both `screen.rs:934`
    /// and `grid.rs:672` would fire `unwrap()` on `None`.
    ///
    /// We exercise three progressively harder layouts:
    ///  1. Glyphs that fill a row exactly (no boundary straddle).
    ///  2. A glyph whose first cell is the last column — forces `col_wrap`.
    ///  3. Many glyphs across multiple rows, interspersed with CR/LF, to
    ///     stress the scroll-path that triggers the grid.rs unwrap.
    #[test]
    fn vt100_wide_char_column_boundary_no_panic() {
        // '日' is U+65E5, width=2.  Three raw UTF-8 bytes: 0xe6 0x97 0xa5.
        let wide = "日";
        // '→' is U+2192, width=1 (sanity filler between wide chars).
        let narrow = "x";

        // Case 1: 10-column terminal, fill with exactly 5 wide chars (10 cols).
        {
            let mut p = vt100::Parser::new(3, 10, 0);
            let row: String = wide.repeat(5); // 10 cells, exactly full
            p.process(row.as_bytes());
            p.process(b"\r\n");
            p.process(row.as_bytes());
            // second row write must not panic even with a full-row wrap
            let _ = p.screen().cell(0, 0);
        }

        // Case 2: 10-column terminal, 4 wide chars (8 cells) then one more
        // wide char — the second cell of the 5th char would be col 9 → 10,
        // which is out of bounds, triggering col_wrap → drawing_row_mut.
        {
            let mut p = vt100::Parser::new(3, 10, 0);
            let four_wide: String = wide.repeat(4); // 8 cells
            p.process(four_wide.as_bytes());
            p.process(narrow.as_bytes()); // col 8, fills col 9 implicitly
                                          // Now feed a wide char starting at col 9 (last col) — the second
                                          // half would fall at col 10 → out of bounds → col_wrap fires.
            p.process(wide.as_bytes()); // must not panic
            let _ = p.screen().cell(0, 0);
        }

        // Case 3: stress-test with 80-column terminal and many wide chars
        // across scrolling rows (exit-repaint scenario).
        {
            let mut p = vt100::Parser::new(24, 80, 0);
            // 40 wide chars = 80 cells = exactly one full row
            let full_row: String = wide.repeat(40);
            for _ in 0..50 {
                p.process(full_row.as_bytes());
                p.process(b"\r\n");
            }
            // One more line where an odd wide char straddles the boundary.
            // 39 wide chars (78 cells) + 1 narrow (col 78) → next wide char
            // starts at col 79 (last col), second half would be at col 80.
            let boundary_line = format!("{}{}{}", wide.repeat(39), narrow, wide);
            p.process(boundary_line.as_bytes()); // must not panic
            let _ = p.screen().cell(0, 0);
        }
    }

    // ── Regression: vt100 rows<2 / cols<2 grid panics ───────────────────────
    //
    // Found by this file's `vt100_parser_never_panics*` property tests: vt100
    // 0.16.2 panics constructing or resizing a grid with `rows < 2`
    // (`grid.rs:683`, "attempt to subtract with overflow") *and*, via a
    // different code path, with `cols == 1` and certain multi-byte input
    // regardless of `rows` (`screen.rs:730`, same panic message).
    // `MIN_VT100_ROWS`/`MIN_VT100_COLS` floor every caller-supplied
    // dimension before it ever reaches vt100 — see their docs for why a
    // real caller can plausibly hit this (a pane dragged down to a single
    // row/column, or momentarily to zero mid-resize).
    //
    // Two tiers, because the clamp is portable but the proof that
    // `spawn`/`resize` actually apply it is not: `clamp_vt100_size` and the
    // bare-parser no-panic checks run on every platform, while the four
    // end-to-end `TerminalSession` tests need a real PTY child (`/bin/sh`)
    // and so are `cfg(unix)`, matching every other PTY test in this file.

    #[test]
    fn clamp_vt100_size_floors_degenerate_dimensions() {
        // Zero — the momentary size a pane can report mid-drag.
        assert_eq!(
            clamp_vt100_size(0, 0),
            (MIN_VT100_COLS, MIN_VT100_ROWS),
            "a zero-sized pane must be floored on both axes"
        );
        // One row / one column — the two distinct upstream panic sites.
        assert_eq!(clamp_vt100_size(80, 1), (80, MIN_VT100_ROWS));
        assert_eq!(clamp_vt100_size(1, 24), (MIN_VT100_COLS, 24));
        // At and above the floor the caller's request is passed through
        // untouched — the clamp must not quietly resize a healthy pane.
        assert_eq!(
            clamp_vt100_size(MIN_VT100_COLS, MIN_VT100_ROWS),
            (MIN_VT100_COLS, MIN_VT100_ROWS)
        );
        assert_eq!(clamp_vt100_size(200, 60), (200, 60));
    }

    /// The floor is only worth anything if vt100 survives *at* it: build and
    /// resize a parser at exactly `MIN_VT100_ROWS` x `MIN_VT100_COLS`, and
    /// feed it the multi-byte input that triggers the `cols == 1`
    /// `screen.rs:730` overflow. Bare parser, no PTY — runs everywhere.
    #[test]
    fn vt100_survives_at_the_clamped_floor() {
        let (cols, rows) = clamp_vt100_size(0, 0);
        let mut p = vt100::Parser::new(rows, cols, 0);
        p.process("あéa\r\n\u{1b}[31mx".as_bytes());
        p.screen_mut().set_size(rows, cols);
        p.process("あ".as_bytes());
        assert_eq!(
            p.screen().size(),
            (MIN_VT100_ROWS, MIN_VT100_COLS),
            "the floored grid must survive construction, resize and wide-char input"
        );
    }

    #[test]
    #[cfg(unix)]
    fn spawn_with_a_single_row_does_not_panic() {
        let cwd = std::env::current_dir().expect("cwd");
        let mut sess = TerminalSession::spawn(80, 1, "/bin/sh", &cwd, 1000)
            .expect("spawn must succeed even with rows clamped internally");
        // The clamp is real, not just "didn't crash": the live grid must
        // actually be `MIN_VT100_ROWS` rows, not the requested 1.
        assert_eq!(sess.rows(), MIN_VT100_ROWS);
        sess.send_str("exit\n");
    }

    #[test]
    #[cfg(unix)]
    fn spawn_with_a_single_column_does_not_panic() {
        let cwd = std::env::current_dir().expect("cwd");
        let mut sess = TerminalSession::spawn(1, 24, "/bin/sh", &cwd, 1000)
            .expect("spawn must succeed even with cols clamped internally");
        assert_eq!(sess.cols(), MIN_VT100_COLS);
        sess.send_str("exit\n");
    }

    #[test]
    #[cfg(unix)]
    fn resize_to_a_single_row_does_not_panic() {
        let cwd = std::env::current_dir().expect("cwd");
        let mut sess = TerminalSession::spawn(80, 24, "/bin/sh", &cwd, 1000).expect("spawn failed");
        sess.resize(80, 1);
        assert_eq!(sess.rows(), MIN_VT100_ROWS);
        sess.send_str("exit\n");
    }

    #[test]
    #[cfg(unix)]
    fn resize_to_a_single_column_does_not_panic() {
        let cwd = std::env::current_dir().expect("cwd");
        let mut sess = TerminalSession::spawn(80, 24, "/bin/sh", &cwd, 1000).expect("spawn failed");
        sess.resize(1, 24);
        assert_eq!(sess.cols(), MIN_VT100_COLS);
        sess.send_str("exit\n");
    }

    // ── Regression: destructive resize corrupts content ─────────────────────
    //
    // These drive the vendored vt100 parser's `set_size` directly (no PTY),
    // so they're deterministic. Before the reflow patch, shrinking the column
    // count truncated every row's cells and widening back padded with blanks
    // instead of restoring them — a shrink-then-expand window drag left the
    // shell output permanently truncated. The reflow re-wraps logical lines
    // so the round-trip is lossless.

    /// Collect the visible screen rows as trimmed strings.
    fn screen_lines(p: &vt100::Parser) -> Vec<String> {
        let (rows, _cols) = p.screen().size();
        (0..rows)
            .map(|r| {
                p.screen()
                    .rows(0, p.screen().size().1)
                    .nth(r as usize)
                    .unwrap_or_default()
                    .trim_end()
                    .to_string()
            })
            .collect()
    }

    #[test]
    fn resize_height_only_preserves_content() {
        // Upstream vt100 0.16 `set_size` does not reflow wrapped lines, but a
        // height-only change (same width) must still keep existing rows intact.
        let mut p = vt100::Parser::new(24, 80, 1000);
        p.process(b"hello world\r\nsecond line");
        p.screen_mut().set_size(40, 80); // taller, same width
        let lines = screen_lines(&p);
        assert!(lines.iter().any(|l| l == "hello world"));
        assert!(lines.iter().any(|l| l == "second line"));
    }

    // These drive `reflow_screen` — the public-API (snapshot → resize → replay)

    #[test]
    fn resize_no_op_when_width_unchanged() {
        // Height-only change routes through `reflow_screen`'s cheap non-reflow
        // path (same width) and must not corrupt content.
        let mut p = vt100::Parser::new(24, 80, 1000);
        p.process(b"hello world\r\nsecond line");
        reflow_screen(&mut p, 40, 80); // taller, same width
        let lines = screen_lines(&p);
        assert!(lines.iter().any(|l| l == "hello world"));
        assert!(lines.iter().any(|l| l == "second line"));
    }

    #[test]
    fn resize_shrink_wraps_without_losing_tail() {
        // A single line longer than the shrunk width must wrap, not truncate.
        let mut p = vt100::Parser::new(24, 100, 1000);
        let long = "0123456789ABCDEFGHIJ0123456789ABCDEFGHIJ0123456789ABCDEFGHIJ";
        p.process(long.as_bytes());
        reflow_screen(&mut p, 24, 20);
        // The full text must still be reconstructable from the wrapped rows.
        let joined: String = screen_lines(&p).join("");
        assert!(
            joined.contains("GHIJ0123456789ABCDEFGHIJ"),
            "tail of long line lost on shrink: {joined:?}"
        );
        // And expanding back restores the single unbroken line.
        reflow_screen(&mut p, 24, 100);
        assert!(
            screen_lines(&p).iter().any(|l| l == long),
            "long line not restored on expand: {:?}",
            screen_lines(&p)
        );
    }

    #[test]
    fn resize_preserves_wide_chars() {
        // Wide (CJK) glyphs must survive a reflow round-trip without being
        // split from their continuation cell. One logical line, so no row ever
        // scrolls into scrollback across the shrink.
        let mut p = vt100::Parser::new(24, 100, 1000);
        let line = "日本語テスト-CJK-日本語テスト-CJK-日本語テスト";
        p.process(line.as_bytes());
        reflow_screen(&mut p, 24, 30);
        reflow_screen(&mut p, 24, 100);
        assert!(
            screen_lines(&p).iter().any(|l| l == line),
            "wide-char line not restored across resize: {:?}",
            screen_lines(&p)
        );
    }

    /// Pinned regression for quadraui#1130: the shrink must not leave a
    /// double-width glyph's first half orphaned at the new final column.
    #[test]
    fn reflow_shrink_does_not_orphan_a_wide_glyph_at_the_boundary() {
        let mut p = vt100::Parser::new(2, 65, 0);
        let mut before = vec![b'\t'];
        before.extend_from_slice(&[b' '; 24]);
        before.extend_from_slice("\u{3000}".as_bytes());
        p.process(&before);
        assert!(
            p.screen().cell(0, 32).is_some_and(vt100::Cell::is_wide),
            "fixture drifted: the wide glyph must sit on the truncation boundary"
        );

        reflow_screen(&mut p, 2, 33);

        // The orphan is gone: the cell that survived the truncation is no
        // longer a first half missing its partner.
        let (_, cols) = p.screen().size();
        assert_eq!(cols, 33);
        for row in 0..2 {
            assert!(
                !p.screen()
                    .cell(row, cols - 1)
                    .is_some_and(vt100::Cell::is_wide),
                "row {row} still ends in an orphaned wide first half"
            );
        }
        // Writing over it must not panic.
        p.process(b"\x1b[1;33H ");
    }

    /// Same boundary, but on the **alternate** screen — `reflow_screen`
    /// deliberately skips the snapshot→replay reflow there (full-screen apps
    /// repaint themselves), so that branch needs its own coverage that the
    /// scrub still runs. quadraui#1130.
    #[test]
    fn reflow_shrink_does_not_orphan_a_wide_glyph_on_the_alternate_screen() {
        let mut p = vt100::Parser::new(2, 65, 0);
        p.process(b"\x1b[?1049h");
        let mut before = vec![b'\t'];
        before.extend_from_slice(&[b' '; 24]);
        before.extend_from_slice("\u{3000}".as_bytes());
        p.process(&before);
        assert!(p.screen().alternate_screen());

        reflow_screen(&mut p, 2, 33);

        let (_, cols) = p.screen().size();
        assert!(
            !p.screen()
                .cell(0, cols - 1)
                .is_some_and(vt100::Cell::is_wide),
            "alternate screen still ends in an orphaned wide first half"
        );
        p.process(b"\x1b[1;33H ");
    }

    /// The scrub is not allowed to move the cursor: it brackets its repair
    /// with DECSC/DECRC precisely so a resize stays invisible to the child.
    #[test]
    fn reflow_shrink_scrub_restores_the_cursor() {
        let mut p = vt100::Parser::new(4, 65, 0);
        let mut before = vec![b'\t'];
        before.extend_from_slice(&[b' '; 24]);
        before.extend_from_slice("\u{3000}".as_bytes());
        p.process(&before);
        // Park the cursor somewhere the scrub would clobber if it leaked.
        p.process(b"\x1b[3;5H");
        assert_eq!(p.screen().cursor_position(), (2, 4));

        reflow_screen(&mut p, 4, 33);

        assert_eq!(
            p.screen().cursor_position(),
            (2, 4),
            "resize must not move the cursor"
        );
    }

    #[test]
    fn resize_shrink_then_expand_preserves_content() {
        // Several full-width lines. Shrink hard on width, then expand back —
        // every line must survive. The shrunk grid is kept tall enough that no
        // wrapped row scrolls into scrollback (the public-API reflow only
        // covers the visible screen; see `reflow_screen`'s doc comment).
        let mut p = vt100::Parser::new(24, 100, 1000);
        for i in 1..=6 {
            let line = format!("ROW{i:02}-abcdefghijklmnopqrstuvwxyz-0123456789-END\r\n");
            p.process(line.as_bytes());
        }
        for i in 1..=6 {
            let needle = format!("ROW{i:02}-abcdefghijklmnopqrstuvwxyz-0123456789-END");
            assert!(
                screen_lines(&p).iter().any(|l| l == &needle),
                "line {i} missing before resize"
            );
        }

        // Shrink width to 40 (each 47-char line wraps to 2 rows → 12 rows); keep
        // 20 rows so nothing scrolls off. Then expand back to the original size.
        reflow_screen(&mut p, 20, 40);
        reflow_screen(&mut p, 24, 100);

        for i in 1..=6 {
            let needle = format!("ROW{i:02}-abcdefghijklmnopqrstuvwxyz-0123456789-END");
            assert!(
                screen_lines(&p).iter().any(|l| l == &needle),
                "line {i} lost across shrink→expand round-trip: {:?}",
                screen_lines(&p)
            );
        }
    }

    #[test]
    fn resize_multistep_drag_leaves_no_ghost_rows() {
        // A window drag fires many intermediate resizes (shrink then expand).
        let mut p = vt100::Parser::new(14, 40, 1000);
        for i in 1..=4 {
            p.process(format!("unique_line_{i:02}_content\r\n").as_bytes());
        }
        p.process(b"prompt$ "); // fresh prompt, cursor after it
        let before = screen_lines(&p);

        // Multi-step drag: shrink through several widths (each 21-char line
        // wraps to at most 2 rows → ≤ 9 rows, well under the 10-row floor),
        // then expand back to the start size.
        for (rows, cols) in [(11, 30), (10, 22), (10, 20), (12, 26), (13, 34), (14, 40)] {
            reflow_screen(&mut p, rows, cols);
        }
        let after = screen_lines(&p);

        assert_eq!(
            before, after,
            "grid changed across a shrink→expand drag round-trip (ghost rows)"
        );
        // Belt-and-braces: no unique content line appears more than once.
        for i in 1..=4 {
            let needle = format!("unique_line_{i:02}_content");
            let count = after.iter().filter(|l| l.contains(&needle)).count();
            assert_eq!(count, 1, "line {i} duplicated across resize: {after:?}");
        }
    }

    // ── Regression: shell-redraw-vs-reflow race on fast resize ──────────────
    //
    // A fast resize drag reflows the grid to width N and SIGWINCHes the shell;
    // the shell redraws its prompt for width N (cursor-relative bytes queued in
    // the reader thread), then the drag reflows the grid *again* to width M
    // before those bytes are processed. Applying a width-N redraw to a width-M
    // grid scattered duplicated prompt fragments across the pane that stayed
    // stuck until the next resize — reproduced on both TUI and GTK, so the bug
    // was in this shared engine, not a backend paint path.
    //
    // `resize()` now drains + processes queued PTY output at the current size
    // before reflowing, so each redraw lands on the grid it was computed for.
    //
    // This test locks the fix's *contract* deterministically: output that is
    // already queued in the reader channel when `resize()` is called must be
    // parsed **before** the grid changes size. We prove it by leaving a known
    // sentinel line queued-but-unprocessed (write it, wait for the reader
    // thread to enqueue it, but never `poll()`), then calling `resize()` to a
    // new width. If `resize()` drains first, the sentinel is already on the
    // (old-width) grid and survives the reflow, so it is visible immediately —
    // with no intervening `poll()`. Before the fix, `resize()` reflowed without
    // draining, so the queued width-N bytes were only parsed by a later
    // `poll()` against the width-M grid — the corruption path. The absence of
    // a `poll()` between the wait and the assertion is what makes this a real
    // guard rather than a timing coincidence.
    #[test]
    fn resize_drains_queued_output_before_reflow() {
        use std::thread::sleep;
        use std::time::{Duration, Instant};

        let cwd = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("/"));
        let mut sess = match TerminalSession::spawn(80, 24, "/bin/bash", &cwd, 1000) {
            Ok(s) => s,
            // No PTY available (sandbox): skip rather than fail spuriously.
            Err(_) => return,
        };

        // Poll until `needle` shows up or we time out (drains + processes).
        fn wait_for(sess: &mut TerminalSession, needle: &str, ms: u64) -> bool {
            let deadline = Instant::now() + Duration::from_millis(ms);
            loop {
                sess.poll();
                if sess.screen_text().contains(needle) {
                    return true;
                }
                if Instant::now() >= deadline {
                    return false;
                }
                sleep(Duration::from_millis(5));
            }
        }

        // Quiet, fixed prompt and wait for the shell to be ready.
        sess.write_input(b"PS1='RDYMARK$ '\n");
        if !wait_for(&mut sess, "RDYMARK$", 4000) {
            return; // cold shell — don't assert
        }

        // Emit a unique sentinel, then wait for the reader thread to have it
        // enqueued WITHOUT processing it into the parser. We can't peek the
        // channel, so give it a generous, machine-load-robust window.
        sess.write_input(b"echo SENTINEL_QZX_9137\n");
        sleep(Duration::from_millis(400));

        // Precondition: the sentinel is NOT on the grid yet (still queued),
        // because we have not polled since writing it. If the shell were
        // somehow already drained, the test still holds but proves less; guard
        // against a flaky environment by only asserting the core property when
        // the sentinel is genuinely still queued.
        let queued = !sess.screen_text().contains("SENTINEL_QZX_9137");

        // The fix: resize() must drain + process the queued sentinel at the
        // current (80-col) width *before* reflowing to the new width. No poll()
        // is called here or before the assertion.
        sess.resize(50, 18);

        if queued {
            assert!(
                sess.screen_text().contains("SENTINEL_QZX_9137"),
                "resize() must drain queued PTY output before reflowing so \
                 in-flight redraws land on the width they were computed for \
                 (quadraui#437); sentinel was still queued yet resize() did not \
                 process it.\nscreen:\n{}",
                sess.screen_text()
            );
        }

        sess.write_input(b"exit\n");
    }

    #[test]
    fn resize_noop_same_size_is_cheap() {
        // Re-sending the current size must be a no-op (no reflow / SIGWINCH
        let cwd = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("/"));
        let mut sess = match TerminalSession::spawn(80, 24, "/bin/bash", &cwd, 100) {
            Ok(s) => s,
            Err(_) => return,
        };
        assert_eq!((sess.cols(), sess.rows()), (80, 24));
        sess.resize(80, 24); // no-op
        assert_eq!((sess.cols(), sess.rows()), (80, 24));
        sess.resize(100, 30);
        assert_eq!((sess.cols(), sess.rows()), (100, 30));
    }

    // These tests drive the rapid-resize guard: `resize()` waits for the
    #[test]
    fn resize_rapid_multistep_drag_leaves_no_ghosts() {
        use std::thread::sleep;
        use std::time::{Duration, Instant};

        let cwd = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("/"));
        let mut sess = match TerminalSession::spawn(80, 24, "/bin/bash", &cwd, 2000) {
            Ok(s) => s,
            Err(_) => return, // no PTY in sandbox — skip rather than fail
        };

        fn wait_for(sess: &mut TerminalSession, needle: &str, ms: u64) -> bool {
            let deadline = Instant::now() + Duration::from_millis(ms);
            loop {
                sess.poll();
                if sess.screen_text().contains(needle) {
                    return true;
                }
                if Instant::now() >= deadline {
                    return false;
                }
                sleep(Duration::from_millis(5));
            }
        }

        // Fixed, unique prompt so its redraw is what churns on SIGWINCH.
        sess.write_input(b"PS1='GHOSTMK> '\n");
        if !wait_for(&mut sess, "GHOSTMK>", 4000) {
            return; // cold shell — don't assert
        }

        // Emit a unique sentinel line, then let it land on the grid. The
        // sentinel is assembled by `printf` from two fragments so the literal
        // `GHOST_5571` appears ONLY in the command's *output*, never in the
        // typed command line the tty echoes back — otherwise the harmless
        // command echo would inflate the occurrence count and mask/forge a
        // ghost. Any extra copy on the grid is therefore a genuine duplication.
        let needle = "GHOST_5571";
        sess.write_input(b"printf 'GHO%s\\n' ST_5571\n");
        if !wait_for(&mut sess, needle, 4000) {
            return;
        }

        // The actual failure trigger: a rapid multi-step drag — several
        // resizes with NO settle time between the calls. `resize()` itself is
        // responsible for consuming each width's redraw before returning.
        for (cols, rows) in [(60, 20), (48, 16), (40, 14), (52, 18), (68, 22), (80, 24)] {
            sess.resize(cols, rows);
        }

        // Drain anything still in flight and let the grid settle.
        for _ in 0..40 {
            sess.poll();
            sleep(Duration::from_millis(10));
        }

        // The output line must appear at most once.
        let screen = sess.screen_text();
        let count = screen.matches(needle).count();
        assert!(
            count <= 1,
            "rapid multi-step resize drag duplicated a unique line \
             ({count} copies) — the #437 resize ghost. screen:\n{screen}"
        );
        assert_eq!((sess.cols(), sess.rows()), (80, 24));

        sess.write_input(b"exit\n");
    }

    // ── Regression: the post-SIGWINCH settle timing policy (blocking #2) ─────
    //
    // The deterministic core of blocking #2, isolated from any shell. A rapid
    // resize drag corrupts the grid when a resize's SIGWINCH redraw is parsed
    // at a *later* width because the next resize changed the width before that
    // redraw was consumed. `resize()` closes the race by *waiting* (bounded)
    // for the child's post-SIGWINCH output before returning, via
    // `collect_post_resize_output`.
    //
    // These tests drive that timing policy against a synthetic
    // `std::sync::mpsc::channel` — no PTY, no shell. That matters: the previous
    // real-shell test relied on a bash `WINCH` trap firing during the resize,
    // but bash defers a user WINCH trap while sitting at the readline prompt
    // (it redraws the prompt line but runs the trap only after the next command
    // is submitted), so the trap output never arrived and the test was a flaky
    // false negative. The synthetic channel reproduces the exact bug — a child
    // that reacts to SIGWINCH *later than the idle gap* — deterministically.

    #[test]
    fn settle_waits_past_idle_gap_for_a_delayed_redraw() {
        use std::sync::mpsc::channel;
        use std::time::Duration;

        // The child reacts to SIGWINCH after `child_delay` — deliberately
        // *longer* than the idle gap (RESIZE_SETTLE_IDLE) so the ORIGINAL bug
        // (return after one idle gap having consumed nothing) is exercised, yet
        // comfortably *shorter* than the first-byte window (RESIZE_SETTLE_FIRST)
        // so the fix captures it. `sleep` only ever overshoots, so the "> idle"
        // side is unconditional; the margin below FIRST (4×) absorbs load.
        let child_delay = Duration::from_millis(20);
        assert!(
            RESIZE_SETTLE_IDLE < child_delay,
            "delay must exceed the idle gap"
        );
        assert!(
            child_delay * 3 < RESIZE_SETTLE_FIRST,
            "delay needs headroom below the first-byte window"
        );

        let (tx, rx) = channel::<Vec<u8>>();
        let sender = std::thread::spawn(move || {
            std::thread::sleep(child_delay);
            let _ = tx.send(b"post-winch-redraw".to_vec());
            // Keep the channel connected briefly so the drain phase ends on a
            // genuine idle gap (Timeout), not a Disconnected shortcut.
            std::thread::sleep(Duration::from_millis(40));
        });

        let chunks = collect_post_resize_output(&rx);
        sender.join().unwrap();

        assert_eq!(
            chunks.concat(),
            b"post-winch-redraw",
            "settle must wait past the initial idle gap for a child that reacts \
             to SIGWINCH slowly — the blocking #2 ghost bug"
        );
    }

    #[test]
    fn settle_returns_bounded_when_child_stays_silent() {
        use std::sync::mpsc::channel;
        use std::time::{Duration, Instant};

        // A child that ignores SIGWINCH (emits nothing). Settle must not hang:
        // it waits up to RESIZE_SETTLE_FIRST for a first byte, then gives up.
        // `_tx` is held so the channel is NOT disconnected — proving the return
        // is driven by the first-byte timeout, not a Disconnected shortcut.
        let (_tx, rx) = channel::<Vec<u8>>();

        let start = Instant::now();
        let chunks = collect_post_resize_output(&rx);
        let elapsed = start.elapsed();

        assert!(chunks.is_empty(), "silent child must yield no chunks");
        assert!(
            elapsed >= RESIZE_SETTLE_FIRST.saturating_sub(Duration::from_millis(10)),
            "settle must actually wait ~RESIZE_SETTLE_FIRST for a first byte \
             (waited {elapsed:?})"
        );
        assert!(
            elapsed <= RESIZE_SETTLE_MAX + Duration::from_millis(80),
            "settle must stay bounded and not hang (waited {elapsed:?})"
        );
    }

    #[test]
    fn settle_drains_a_multi_chunk_redraw_then_stops() {
        use std::sync::mpsc::channel;
        use std::time::Duration;

        // A redraw delivered as several chunks. Settle must capture ALL of them
        // in order and stop once the child goes quiet — not truncate mid-redraw.
        // The chunks are sent back-to-back (no inter-send sleep) so the test has
        // no dependence on a per-chunk gap staying under the idle window — the
        // only timing requirement is the final hold exceeding the idle gap.
        let (tx, rx) = channel::<Vec<u8>>();
        let sender = std::thread::spawn(move || {
            let _ = tx.send(b"aaa".to_vec());
            let _ = tx.send(b"bbb".to_vec());
            let _ = tx.send(b"ccc".to_vec());
            // Hold the channel open past the idle gap so the drain ends via a
            // Timeout (idle), not a Disconnected, exercising "redraw complete".
            std::thread::sleep(Duration::from_millis(40));
        });

        let chunks = collect_post_resize_output(&rx);
        sender.join().unwrap();

        assert_eq!(
            chunks.concat(),
            b"aaabbbccc",
            "settle must drain the whole multi-chunk redraw in arrival order"
        );
    }

    #[test]
    fn xterm_256_system_colors() {
        // Colour 0 = black.
        assert_eq!(xterm_256_color(0), (0, 0, 0));
        // Colour 15 = white.
        assert_eq!(xterm_256_color(15), (255, 255, 255));
    }

    #[test]
    fn xterm_256_cube_first() {
        // Colour 16: r=0, g=0, b=0 in the cube → (0, 0, 0).
        assert_eq!(xterm_256_color(16), (0, 0, 0));
    }

    #[test]
    fn xterm_256_cube_pure_red() {
        // r=5, g=0, b=0 → index 16 + 36*5 = 196.
        let (r, g, b) = xterm_256_color(196);
        assert_eq!(r, 55 + 5 * 40); // 255
        assert_eq!(g, 0);
        assert_eq!(b, 0);
    }

    #[test]
    fn xterm_256_greyscale() {
        // Colour 232 = darkest grey (8, 8, 8).
        assert_eq!(xterm_256_color(232), (8, 8, 8));
        // Colour 255 = lightest grey (238 = 8 + 23*10).
        assert_eq!(xterm_256_color(255), (238, 238, 238));
    }

    #[test]
    fn map_vt100_default_colors() {
        let (r, g, b) = map_vt100_color(vt100::Color::Default, false);
        assert_eq!((r, g, b), (229, 229, 229)); // fg default
        let (r, g, b) = map_vt100_color(vt100::Color::Default, true);
        assert_eq!((r, g, b), (30, 30, 30)); // bg default
    }

    #[test]
    fn map_vt100_rgb() {
        let (r, g, b) = map_vt100_color(vt100::Color::Rgb(1, 2, 3), false);
        assert_eq!((r, g, b), (1, 2, 3));
    }

    #[test]
    fn normalize_selection_already_ordered() {
        let sel = TerminalSelection {
            start_row: 1,
            start_col: 5,
            end_row: 3,
            end_col: 10,
        };
        assert_eq!(normalize_selection(&sel), (1, 5, 3, 10));
    }

    #[test]
    fn normalize_selection_reversed() {
        let sel = TerminalSelection {
            start_row: 3,
            start_col: 10,
            end_row: 1,
            end_col: 5,
        };
        assert_eq!(normalize_selection(&sel), (1, 5, 3, 10));
    }

    #[test]
    fn terminal_manager_new_is_empty() {
        let mgr = TerminalManager::new();
        assert!(mgr.is_empty());
        assert_eq!(mgr.len(), 0);
        assert!(mgr.active_session().is_none());
    }

    #[test]
    fn terminal_manager_close_active_on_empty_is_noop() {
        let mut mgr = TerminalManager::new();
        mgr.close_active(); // should not panic
        assert!(mgr.is_empty());
    }

    #[test]
    fn terminal_manager_switch_to_empty_is_noop() {
        let mut mgr = TerminalManager::new();
        mgr.switch_to(5); // should not panic
        assert_eq!(mgr.active, 0);
    }

    #[test]
    fn default_shell_is_nonempty() {
        let shell = default_shell();
        assert!(!shell.is_empty());
    }

    // ── default_shell_for ───────────────────────────────────────────────────

    #[test]
    fn default_shell_for_unix_honours_shell_env_var() {
        let shell = default_shell_for(ShellPlatform::Unix, Some("/bin/zsh".to_string()));
        assert_eq!(shell, "/bin/zsh");
    }

    #[test]
    fn default_shell_for_unix_falls_back_when_shell_env_var_unset() {
        let shell = default_shell_for(ShellPlatform::Unix, None);
        assert_eq!(shell, "/bin/bash");
    }

    /// A Unix-style `$SHELL` reaching the Windows branch (a Git Bash / WSL
    /// interop tab exporting one into a native Windows process's
    /// environment) must be ignored outright, not merely overridden by a
    /// later check. `default_shell()` itself enforces this by never calling
    /// `std::env::var("SHELL")` under `cfg(target_os = "windows")` at all;
    /// this test pins the pure decision function's behaviour even if a
    /// caller somehow passed one through.
    #[test]
    fn default_shell_for_windows_ignores_a_unix_style_shell_value() {
        let shell = default_shell_for(ShellPlatform::Windows, Some("/bin/bash".to_string()));
        assert_eq!(shell, "powershell.exe");
    }

    #[test]
    fn default_shell_for_windows_is_powershell_with_no_env_shell() {
        let shell = default_shell_for(ShellPlatform::Windows, None);
        assert_eq!(shell, "powershell.exe");
    }

    // ── shell_command / shell_command_for ─────────────────────────────────────

    #[test]
    fn shell_command_for_unix_honours_shell_env_var() {
        let (shell, flag) = shell_command_for(ShellPlatform::Unix, Some("/bin/zsh".to_string()));
        assert_eq!(shell, "/bin/zsh");
        assert_eq!(flag, "-c");
    }

    #[test]
    fn shell_command_for_unix_falls_back_when_shell_env_var_unset() {
        let (shell, flag) = shell_command_for(ShellPlatform::Unix, None);
        assert_eq!(shell, "sh");
        assert_eq!(flag, "-c");
    }

    #[test]
    fn shell_command_for_windows_honours_comspec_env_var() {
        let (shell, flag) = shell_command_for(
            ShellPlatform::Windows,
            Some(r"C:\Windows\System32\cmd.exe".to_string()),
        );
        assert_eq!(shell, r"C:\Windows\System32\cmd.exe");
        assert_eq!(flag, "/C");
    }

    #[test]
    fn shell_command_for_windows_falls_back_when_comspec_env_var_unset() {
        let (shell, flag) = shell_command_for(ShellPlatform::Windows, None);
        assert_eq!(shell, "cmd");
        assert_eq!(flag, "/C");
    }

    /// `shell_command()` itself (as opposed to the pure `shell_command_for`
    /// helper above) picks its platform branch via `cfg(target_os =
    /// "windows")`, so this only exercises whichever branch the current
    /// build host compiles — the platform-parameterised tests above are
    /// what cover both branches regardless of host OS.
    #[test]
    fn shell_command_returns_nonempty_pair() {
        let (shell, flag) = shell_command();
        assert!(!shell.is_empty());
        assert!(!flag.is_empty());
    }

    #[test]
    fn map_vt100_idx_196_is_pure_red() {
        // Colour index 196 = r=5,g=0,b=0 in the 6×6×6 cube → (255, 0, 0).
        let (r, g, b) = map_vt100_color(vt100::Color::Idx(196), false);
        assert_eq!((r, g, b), (255, 0, 0));
    }

    // ── cursor_visible integration tests (require a real PTY / Unix shell) ────

    /// After the child exits, `cursor_visible()` must return `false`
    /// regardless of the scroll offset.
    #[test]
    #[cfg(unix)]
    fn cursor_hidden_after_exit() {
        let cwd = std::env::temp_dir();
        let mut sess = TerminalSession::spawn(80, 24, "/bin/sh", &cwd, 1000).expect("spawn failed");

        // Verify cursor is visible before exit (scroll_offset = 0, not exited).
        assert!(
            sess.cursor_visible(),
            "cursor should be visible before exit"
        );

        // Exit the shell.
        sess.send_str("exit 0\n");
        let exited = poll_until(&mut sess, 5000, |s| s.exited);
        assert!(exited, "shell did not exit within timeout");

        // After exit, cursor must be hidden.
        assert!(
            !sess.cursor_visible(),
            "cursor should be hidden after shell exits"
        );
    }

    /// When scrolled into history, `cursor_visible()` returns `false`.
    #[test]
    #[cfg(unix)]
    fn cursor_hidden_when_scrolled() {
        let cwd = std::env::temp_dir();
        let mut sess = TerminalSession::spawn(80, 24, "/bin/sh", &cwd, 1000).expect("spawn failed");

        // Generate some history so we can scroll.
        for _ in 0..30 {
            sess.send_str("echo line\n");
        }
        let _ = poll_until(&mut sess, 5000, |s| s.history_len() > 0);

        // At live view (scroll_offset = 0), cursor should be visible.
        assert!(
            sess.cursor_visible(),
            "cursor should be visible at live view"
        );

        // Scroll up into history.
        sess.scroll_up(5);
        assert!(
            !sess.cursor_visible(),
            "cursor should be hidden when scrolled into history"
        );

        // Scroll back to live view.
        sess.scroll_reset();
        assert!(
            sess.cursor_visible(),
            "cursor should be visible again after scroll_reset"
        );

        sess.send_str("exit\n");
    }

    /// `TerminalSession::paste` resets the scroll offset back to the live
    /// view — mirroring ordinary keystroke input — so a paste is always
    /// visible immediately even if the user had scrolled into history.
    /// (Real-PTY test since `scroll_reset`/`cursor_visible` are session
    /// state, not the pure `encode_paste` byte-encoding covered above.)
    #[test]
    #[cfg(unix)]
    fn paste_resets_scroll_to_live_view() {
        let cwd = std::env::temp_dir();
        let mut sess = TerminalSession::spawn(80, 24, "/bin/sh", &cwd, 1000).expect("spawn failed");

        for _ in 0..30 {
            sess.send_str("echo line\n");
        }
        let _ = poll_until(&mut sess, 5000, |s| s.history_len() > 0);

        sess.scroll_up(5);
        assert!(
            !sess.cursor_visible(),
            "precondition: scrolled into history should hide the cursor"
        );

        sess.paste("hello");
        assert!(
            sess.cursor_visible(),
            "paste should reset scroll back to the live view"
        );

        sess.send_str("exit\n");
    }

    /// `bracketed_paste_enabled()` reflects the child's DEC private mode
    #[test]
    #[cfg(unix)]
    fn bracketed_paste_enabled_tracks_mode_2004() {
        let cwd = std::env::temp_dir();
        let mut sess =
            TerminalSession::spawn(80, 24, "/bin/sh", &cwd, 1000).expect("failed to spawn /bin/sh");

        // Off until the child enables it.
        assert!(!sess.bracketed_paste_enabled());

        // Emit ESC[?2004h from the child (as interactive programs do once
        // their input prompt is ready). `\033` is a POSIX printf octal escape.
        sess.send_str("printf '\\033[?2004h'\n");
        assert!(
            poll_until(&mut sess, 5000, |s| s.bracketed_paste_enabled()),
            "bracketed paste should be enabled after the child emits ESC[?2004h"
        );

        // And clears again on ESC[?2004l.
        sess.send_str("printf '\\033[?2004l'\n");
        assert!(
            poll_until(&mut sess, 5000, |s| !s.bracketed_paste_enabled()),
            "bracketed paste should be disabled after the child emits ESC[?2004l"
        );

        sess.send_str("exit\n");
    }

    /// [`TerminalSession::title`] tracks OSC 0/OSC 2 window-title requests,
    #[test]
    #[cfg(unix)]
    fn title_tracks_osc_0_and_take_title_changed_is_one_shot() {
        let cwd = std::env::temp_dir();
        let mut sess =
            TerminalSession::spawn(80, 24, "/bin/sh", &cwd, 1000).expect("failed to spawn /bin/sh");

        // No title until the child sets one.
        assert_eq!(sess.title(), None);
        assert!(!sess.take_title_changed());

        // OSC 0 sets the window title (`\033]0;<text>\007`) — same sequence
        // vim/tmux/shell prompt hooks emit. `\033` is a POSIX printf octal
        // escape.
        sess.send_str("printf '\\033]0;hello-quadraui\\007'\n");
        assert!(
            poll_until(&mut sess, 5000, |s| s.title() == Some("hello-quadraui")),
            "title() should track the child's OSC 0 sequence"
        );

        // The dirty flag fires exactly once per change...
        assert!(
            sess.take_title_changed(),
            "take_title_changed should report the change once"
        );
        // ...and is consumed by the read.
        assert!(
            !sess.take_title_changed(),
            "take_title_changed should not re-fire until the title changes again"
        );

        // Re-setting to a *different* title dirties it again.
        sess.send_str("printf '\\033]2;second-title\\007'\n");
        assert!(
            poll_until(&mut sess, 5000, |s| s.title() == Some("second-title")),
            "title() should track a later OSC 2 sequence too"
        );
        assert!(sess.take_title_changed());

        sess.send_str("exit\n");
    }

    // ── Integration tests (require a real PTY / Unix shell) ───────────────────

    /// Helper: poll `session` until `predicate(&session)` is true or
    /// `max_ms` milliseconds elapse. Returns whether the predicate was
    /// satisfied.
    ///
    /// Shared by both the `#[cfg(unix)]` PTY tests above/below and the
    /// `#[cfg(target_os = "windows")]` ConPTY tests further down —
    /// `TerminalSession::spawn`/`poll` are themselves platform-neutral
    /// (`portable_pty::native_pty_system()` already picks the Unix-PTY
    /// vs ConPTY backend), so only the *shell binary* each test spawns
    /// differs per platform, not this driver loop.
    #[cfg(any(unix, windows))]
    fn poll_until(
        sess: &mut TerminalSession,
        max_ms: u64,
        predicate: impl Fn(&TerminalSession) -> bool,
    ) -> bool {
        let start = std::time::Instant::now();
        let limit = std::time::Duration::from_millis(max_ms);
        while start.elapsed() < limit {
            sess.poll();
            if predicate(sess) {
                return true;
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        false
    }

    /// Spawn a session that runs an arithmetic-expansion `echo` and verify:
    ///   1. `screen_text()` eventually contains the *expanded* marker
    ///   2. The process exits with code 0
    ///   3. `exit_code()` returns `Some(0)` after exit
    ///
    /// The marker is `$((1+1))`, not a literal string: a raw literal would
    /// also appear in the console's echo of the *typed* input, so a test
    /// built that way can pass even if the command is never actually
    /// executed by the shell. `$((1+1))` only ever resolves to `2` after
    /// real shell arithmetic, so seeing `MARK_2_END` in `full_text()`
    /// proves the shell ran the command, not merely that input bytes were
    /// echoed back.
    #[test]
    #[cfg(unix)]
    fn session_send_str_screen_text_and_exit_code() {
        let cwd = std::env::temp_dir();
        // Use sh -c so we get a short-lived process with predictable output.
        let mut sess =
            TerminalSession::spawn(80, 24, "/bin/sh", &cwd, 1000).expect("failed to spawn /bin/sh");

        // Before process exits, exit_code is None.
        // Send a command whose output can only exist post-expansion, then exit.
        sess.send_str("echo MARK_$((1+1))_END\nexit 0\n");

        // Poll until the marker appears in the visible screen or history,
        // or the process exits — whichever comes first (max 5 s).
        let found = poll_until(&mut sess, 5000, |s| {
            s.full_text().contains("MARK_2_END") || s.exited
        });
        assert!(
            found,
            "marker 'MARK_2_END' never appeared in terminal output"
        );

        // Process should have exited with code 0.
        let exited = poll_until(&mut sess, 3000, |s| s.exited);
        assert!(exited, "process did not exit within timeout");
        assert_eq!(sess.exit_code(), Some(0), "expected exit code 0");

        // Verify the screen or scrollback text contained the expanded marker.
        let text = sess.full_text();
        assert!(
            text.contains("MARK_2_END"),
            "full_text() does not contain 'MARK_2_END'; got: {text:?}"
        );
    }

    /// Windows sibling of [`session_send_str_screen_text_and_exit_code`]
    /// above, against a real ConPTY. `TerminalSession::spawn` and `poll`
    /// have no Windows-specific code of their own — both go through
    /// `portable_pty::native_pty_system()`, which itself dispatches to the
    /// ConPTY backend on this target — so a Windows-gated test is the only
    /// way to exercise that dispatch against a live Windows host rather
    /// than merely type-check it.
    ///
    /// `send_line` must expand a marker that cannot exist in the console's
    /// raw-input echo of what was typed — only in the shell's own output
    /// once it has actually run the command — so a passing test proves
    /// execution, not merely that bytes were echoed back. Verifies:
    ///   1. Bytes from the child actually arrive — `full_text()` eventually
    ///      contains `expected_marker`.
    ///   2. The process exits, and `is_exited()` observes it.
    ///   3. `exit_code()` resolves to `Some(0)`.
    ///
    /// `args` is forwarded to [`TerminalSession::spawn_with_args`] — e.g.
    /// PowerShell's `-NoLogo -NoProfile` to cut two real-hardware sources of
    /// startup-time variance that have nothing to do with what this test
    /// verifies: the copyright banner, and an up-to-four-path profile-script
    /// existence check. `timeout_ms` is a *bounded* poll deadline, not a
    /// fixed sleep — `poll_until` below returns the moment the marker shows
    /// up, so a generous budget costs nothing on a fast run and only buys
    /// headroom on a loaded CI runner.
    ///
    /// Before sending `send_line`, this waits for a prompt (`>`) to appear
    /// in `full_text()`. Without that handshake, `send_str` races the
    /// shell's own startup: the bytes can land in the ConPTY input buffer
    /// before the shell has even started reading it, a failure mode that a
    /// longer `timeout_ms` budget alone does not close, since the race is
    /// about *order*, not *time*.
    #[cfg(target_os = "windows")]
    fn windows_conpty_spawn_echo_exit(
        shell: &str,
        args: &[&str],
        send_line: &str,
        expected_marker: &str,
        timeout_ms: u64,
    ) {
        let cwd = std::env::temp_dir();
        let mut sess = TerminalSession::spawn_with_args(80, 24, shell, args, &cwd, 1000)
            .unwrap_or_else(|e| panic!("failed to spawn {shell}: {e}"));

        // Wait for the shell's own prompt before sending any input, so
        // `send_str` below can never race the shell's startup: the ConPTY
        // input buffer only needs to hold bytes typed after the shell is
        // already reading from it.
        let ready = poll_until(&mut sess, timeout_ms, |s| {
            s.full_text().contains('>') || s.exited
        });
        assert!(
            ready,
            "{shell} did not show a ready prompt within {timeout_ms}ms"
        );

        // Every Windows console line editor (cmd.exe and powershell.exe
        // alike) wants a carriage return to submit a line, same as a real
        // Enter keypress — a bare `\n` alone is not guaranteed to flush the
        // console's input buffer.
        sess.send_str(send_line);

        // Poll until the marker appears in the visible screen or history,
        // or the process exits — whichever comes first.
        let found = poll_until(&mut sess, timeout_ms, |s| {
            s.full_text().contains(expected_marker) || s.exited
        });
        assert!(
            found,
            "marker {expected_marker:?} never appeared in {shell}'s terminal output within {timeout_ms}ms"
        );

        // Ask the shell to exit with a known code, then confirm `poll()`
        // observes the exit and resolves it correctly.
        sess.send_str("exit 0\r\n");
        let exited = poll_until(&mut sess, timeout_ms, |s| s.is_exited());
        assert!(exited, "{shell} did not exit within {timeout_ms}ms");
        assert_eq!(
            sess.exit_code(),
            Some(0),
            "expected exit code 0 from {shell}"
        );

        let text = sess.full_text();
        assert!(
            text.contains(expected_marker),
            "full_text() does not contain {expected_marker:?}; got: {text:?}"
        );
    }

    /// `cmd.exe` is always present on a Windows runner — no reliance on
    /// `$SHELL`/`default_shell()`, which is covered separately above. The
    /// marker expands via `%PROCESSOR_ARCHITECTURE%`, a cmd.exe builtin
    /// environment variable also visible to this test process itself (both
    /// run natively on the same Windows host), so the expected value is
    /// computed the same way on both sides rather than hardcoded.
    #[test]
    #[cfg(target_os = "windows")]
    fn windows_cmd_session_send_str_screen_text_and_exit_code() {
        let arch = std::env::var("PROCESSOR_ARCHITECTURE").unwrap_or_else(|_| "AMD64".to_string());
        let marker = format!("MARK_{arch}_END");
        windows_conpty_spawn_echo_exit(
            "cmd.exe",
            &[],
            "echo MARK_%PROCESSOR_ARCHITECTURE%_END\r\n",
            &marker,
            5_000,
        );
    }

    /// `default_shell()`'s own Windows branch — this is the shell
    /// `TerminalSession::spawn` actually receives in production, and the
    /// one `cmd.exe` coverage above cannot stand in for: VT mode
    /// initialisation and process start-up are slower and shaped
    /// differently than `cmd.exe`'s. PowerShell's variable
    /// syntax (`$env:NAME`) differs from cmd.exe's (`%NAME%`), so the send
    /// line is PowerShell-specific; the subexpression form
    /// `$($env:PROCESSOR_ARCHITECTURE)` avoids the string-interpolation
    /// variable-name ambiguity a bare `$env:PROCESSOR_ARCHITECTURE_END`
    /// would hit.
    ///
    /// `-NoLogo -NoProfile` strips two sources of real-hardware
    /// startup-time variance that are orthogonal to what this test checks:
    /// the copyright banner `full_text()` would otherwise have to scroll
    /// past, and a profile-script existence probe across up to four disk
    /// paths. Production still spawns bare `powershell.exe` — see
    /// `default_shell()` — this only tightens the *test's* variance, not
    /// the behaviour under test. A longer timeout than the `cmd.exe` case
    /// — still a bounded `poll_until` deadline, not a fixed sleep — covers
    /// what startup time remains on a loaded CI runner.
    #[test]
    #[cfg(target_os = "windows")]
    fn windows_powershell_session_send_str_screen_text_and_exit_code() {
        let arch = std::env::var("PROCESSOR_ARCHITECTURE").unwrap_or_else(|_| "AMD64".to_string());
        let marker = format!("MARK_{arch}_END");
        windows_conpty_spawn_echo_exit(
            "powershell.exe",
            &["-NoLogo", "-NoProfile"],
            "echo \"MARK_$($env:PROCESSOR_ARCHITECTURE)_END\"\r\n",
            &marker,
            30_000,
        );
    }

    /// A resize issued before the shell's first output must not swallow
    /// ConPTY's start-up handshake. `resize` drains pending output itself;
    /// if that drain parsed the `ESC[6n` query without answering it, the
    /// console host would wait for a reply forever and the session would
    /// never paint a prompt.
    #[test]
    #[cfg(target_os = "windows")]
    fn windows_resize_before_first_output_still_answers_startup_handshake() {
        let cwd = std::env::temp_dir();
        let mut sess = TerminalSession::spawn_with_args(80, 24, "cmd.exe", &[], &cwd, 1000)
            .unwrap_or_else(|e| panic!("failed to spawn cmd.exe: {e}"));
        sess.resize(78, 21);
        let ready = poll_until(&mut sess, 30_000, |s| {
            s.full_text().contains('>') || s.exited
        });
        assert!(
            ready && !sess.is_exited(),
            "cmd.exe never showed a prompt after an early resize: {:?}",
            sess.full_text()
        );
    }

    /// `feed_for_bench` must drive the exact same ingest path
    /// `poll()` uses — a bench shouldn't quietly be measuring a different,
    /// unrepresentative code path.
    ///
    /// Covers both halves: live-screen text updates (`process_with_capture`'s
    /// `parser.process()`), and the scrollback-capture dance
    /// (`capture_scrolled_rows`) for rows pushed off-screen — by feeding more
    /// newlines than the pane is tall. No PTY output is read at all (the
    /// shell is never sent anything); every byte in the session's screen and
    /// history comes from `feed_for_bench`.
    #[test]
    #[cfg(unix)]
    fn feed_for_bench_drives_process_with_capture_without_pty() {
        let cwd = std::env::temp_dir();
        // 3 rows tall: 5 lines guarantees at least 2 scroll off into history.
        let mut sess =
            TerminalSession::spawn(20, 3, "/bin/sh", &cwd, 100).expect("failed to spawn /bin/sh");

        sess.feed_for_bench(b"line1\nline2\nline3\nline4\nline5\n");

        assert!(
            sess.full_text().contains("line1"),
            "feed_for_bench should have scrolled 'line1' into history; got: {:?}",
            sess.full_text()
        );
        assert!(
            sess.full_text().contains("line5"),
            "feed_for_bench should have left 'line5' on the live screen; got: {:?}",
            sess.full_text()
        );
        assert!(
            sess.history_len() > 0,
            "lines scrolled off a 3-row screen must land in scrollback history"
        );
    }

    /// Verify that `send_str` is equivalent to `write_input` for ASCII text.
    #[test]
    #[cfg(unix)]
    fn send_str_is_write_input_for_ascii() {
        let cwd = std::env::temp_dir();
        let mut sess =
            TerminalSession::spawn(80, 10, "/bin/sh", &cwd, 100).expect("failed to spawn /bin/sh");

        // Both methods should deliver the same bytes to the PTY.
        // We test that send_str doesn't panic or error.
        sess.send_str("echo ok\n");
        let _ = poll_until(&mut sess, 2000, |s| {
            s.full_text().contains("ok") || s.exited
        });
        // Just verify no panic occurred and the session is still valid.
        assert!(sess.cols > 0 && sess.rows > 0);
        sess.send_str("exit\n");
    }

    // ── Mouse → PTY encoding (SGR-1006) ──────────────────────────────────────

    /// SGR-1006 left-button press at (col=0, row=0) → `ESC[<0;1;1M`.
    #[test]
    fn encode_mouse_sgr_left_press_origin() {
        let bytes = encode_mouse_sgr(
            TerminalMouseKind::Press,
            MouseButton::Left,
            0,
            0,
            Modifiers::default(),
        );
        assert_eq!(bytes, b"\x1b[<0;1;1M");
    }

    /// SGR-1006 left-button release uses lowercase `m` and reports the actual
    /// button (not the legacy `3` placeholder).
    #[test]
    fn encode_mouse_sgr_left_release_uses_lowercase_m() {
        let bytes = encode_mouse_sgr(
            TerminalMouseKind::Release,
            MouseButton::Left,
            4,
            9,
            Modifiers::default(),
        );
        assert_eq!(bytes, b"\x1b[<0;5;10m");
    }

    /// Right-button press at (col=11, row=4) with shift → `ESC[<6;12;5M`
    /// (button 2 | shift bit 4 = 6).
    #[test]
    fn encode_mouse_sgr_right_press_with_shift() {
        let bytes = encode_mouse_sgr(
            TerminalMouseKind::Press,
            MouseButton::Right,
            11,
            4,
            Modifiers {
                shift: true,
                ..Default::default()
            },
        );
        assert_eq!(bytes, b"\x1b[<6;12;5M");
    }

    /// Wheel-up event at (col=0, row=0) → `ESC[<64;1;1M`. Wheel always uses
    /// `M` (no matching release) regardless of `button`.
    #[test]
    fn encode_mouse_sgr_wheel_up() {
        let bytes = encode_mouse_sgr(
            TerminalMouseKind::WheelUp,
            MouseButton::Left,
            0,
            0,
            Modifiers::default(),
        );
        assert_eq!(bytes, b"\x1b[<64;1;1M");
    }

    /// Wheel-down event with ctrl modifier → `ESC[<81;1;1M` (65 | 16 = 81).
    #[test]
    fn encode_mouse_sgr_wheel_down_with_ctrl() {
        let bytes = encode_mouse_sgr(
            TerminalMouseKind::WheelDown,
            MouseButton::Left,
            0,
            0,
            Modifiers {
                ctrl: true,
                ..Default::default()
            },
        );
        assert_eq!(bytes, b"\x1b[<81;1;1M");
    }

    /// Wheel events encode the pointer's column/row on the wire just like
    /// clicks do — real alt-screen consumers (tmux is
    /// the canonical example) use this to route a wheel notch to the pane
    /// under the cursor, so a caller must never collapse it to `(0, 0)`.
    #[test]
    fn encode_mouse_sgr_wheel_up_encodes_nonzero_position() {
        let bytes = encode_mouse_sgr(
            TerminalMouseKind::WheelUp,
            MouseButton::Left,
            5,
            10,
            Modifiers::default(),
        );
        // 1-indexed on the wire: col 5 -> 6, row 10 -> 11.
        assert_eq!(bytes, b"\x1b[<64;6;11M");
    }

    /// Motion event with left button held → bit 5 (32) set + button 0 = 32.
    #[test]
    fn encode_mouse_sgr_motion_with_left() {
        let bytes = encode_mouse_sgr(
            TerminalMouseKind::Move,
            MouseButton::Left,
            7,
            2,
            Modifiers::default(),
        );
        assert_eq!(bytes, b"\x1b[<32;8;3M");
    }

    /// X1 extra-button press → `Cb = 128`.
    #[test]
    fn encode_mouse_sgr_x1_press() {
        let bytes = encode_mouse_sgr(
            TerminalMouseKind::Press,
            MouseButton::X1,
            0,
            0,
            Modifiers::default(),
        );
        assert_eq!(bytes, b"\x1b[<128;1;1M");
    }

    /// X2 extra-button press → `Cb = 129`.
    #[test]
    fn encode_mouse_sgr_x2_press() {
        let bytes = encode_mouse_sgr(
            TerminalMouseKind::Press,
            MouseButton::X2,
            0,
            0,
            Modifiers::default(),
        );
        assert_eq!(bytes, b"\x1b[<129;1;1M");
    }

    /// Middle button press → `Cb = 1` (lowercase `M` terminator).
    #[test]
    fn encode_mouse_sgr_middle_press() {
        let bytes = encode_mouse_sgr(
            TerminalMouseKind::Press,
            MouseButton::Middle,
            4,
            2,
            Modifiers::default(),
        );
        // col 4 + 1 = 5, row 2 + 1 = 3
        assert_eq!(bytes, b"\x1b[<1;5;3M");
    }

    /// Middle button release → `Cb = 1` with lowercase `m` terminator.
    #[test]
    fn encode_mouse_sgr_middle_release() {
        let bytes = encode_mouse_sgr(
            TerminalMouseKind::Release,
            MouseButton::Middle,
            4,
            2,
            Modifiers::default(),
        );
        assert_eq!(bytes, b"\x1b[<1;5;3m");
    }

    // ── Paste → PTY encoding ─────────────────────────────────────────────────

    /// Bracketed-paste mode on: `text` gets wrapped in `ESC[200~` /
    /// `ESC[201~` markers so the child can tell pasted text apart from
    /// typed text.
    #[test]
    fn encode_paste_wraps_when_bracketed() {
        let bytes = encode_paste("hello", true);
        assert_eq!(bytes, b"\x1b[200~hello\x1b[201~");
    }

    /// Bracketed-paste mode off: `text` is sent completely raw — no
    /// markers. Wrapping unconditionally would leak literal escape bytes
    /// into programs that never asked for bracketed paste.
    #[test]
    fn encode_paste_is_raw_when_not_bracketed() {
        let bytes = encode_paste("hello", false);
        assert_eq!(bytes, b"hello");
    }

    /// Multi-line paste (the case bracketed paste exists to protect —
    /// without it, a shell would try to run each line as it arrives)
    /// wraps the whole blob once, not per line.
    #[test]
    fn encode_paste_wraps_multiline_text_once() {
        let bytes = encode_paste("echo one\necho two\n", true);
        assert_eq!(bytes, b"\x1b[200~echo one\necho two\n\x1b[201~");
    }

    /// Non-ASCII UTF-8 text round-trips through the wrap byte-for-byte.
    #[test]
    fn encode_paste_preserves_utf8() {
        let bytes = encode_paste("日本語 🎉", true);
        let mut expected = b"\x1b[200~".to_vec();
        expected.extend_from_slice("日本語 🎉".as_bytes());
        expected.extend_from_slice(b"\x1b[201~");
        assert_eq!(bytes, expected);
    }

    /// Empty paste still gets wrapped (a paste of "nothing" is still a
    /// paste event as far as the child's bracketed-paste state machine is
    /// concerned) — no special-casing to drop the markers.
    #[test]
    fn encode_paste_wraps_empty_text() {
        let bytes = encode_paste("", true);
        assert_eq!(bytes, b"\x1b[200~\x1b[201~");
    }

    // ── Normal-mode key encoding (DECCKM off / app_cursor = false) ───────────

    #[test]
    fn ctrl_c_is_etx() {
        let bytes = key_to_pty_bytes(
            Key::Char('c'),
            Modifiers {
                ctrl: true,
                ..Default::default()
            },
            false,
        );
        assert_eq!(bytes, Some(vec![0x03])); // ETX
    }

    #[test]
    fn ctrl_d_is_eot() {
        let bytes = key_to_pty_bytes(
            Key::Char('d'),
            Modifiers {
                ctrl: true,
                ..Default::default()
            },
            false,
        );
        assert_eq!(bytes, Some(vec![0x04])); // EOT
    }

    #[test]
    fn printable_char_passes_through() {
        let bytes = key_to_pty_bytes(Key::Char('a'), Modifiers::default(), false).unwrap();
        assert_eq!(bytes, b"a");
    }

    #[test]
    fn enter_is_cr() {
        let bytes =
            key_to_pty_bytes(Key::Named(NamedKey::Enter), Modifiers::default(), false).unwrap();
        assert_eq!(bytes, b"\r");
    }

    #[test]
    fn up_arrow_plain() {
        // Normal mode (app_cursor = false) → CSI sequence.
        let bytes =
            key_to_pty_bytes(Key::Named(NamedKey::Up), Modifiers::default(), false).unwrap();
        assert_eq!(bytes, b"\x1b[A");
    }

    #[test]
    fn up_arrow_ctrl() {
        let bytes = key_to_pty_bytes(
            Key::Named(NamedKey::Up),
            Modifiers {
                ctrl: true,
                ..Default::default()
            },
            false,
        )
        .unwrap();
        // ctrl mod_param = 5 → "\x1b[1;5A"
        assert_eq!(bytes, b"\x1b[1;5A");
    }

    #[test]
    fn f1_plain() {
        // F1 unmodified must emit the SS3 sequence \x1bOP, NOT the CSI \x1b[P.
        let bytes =
            key_to_pty_bytes(Key::Named(NamedKey::F(1)), Modifiers::default(), false).unwrap();
        assert_eq!(bytes, b"\x1bOP");
    }

    #[test]
    fn f2_plain() {
        let bytes =
            key_to_pty_bytes(Key::Named(NamedKey::F(2)), Modifiers::default(), false).unwrap();
        assert_eq!(bytes, b"\x1bOQ");
    }

    #[test]
    fn f3_plain() {
        let bytes =
            key_to_pty_bytes(Key::Named(NamedKey::F(3)), Modifiers::default(), false).unwrap();
        assert_eq!(bytes, b"\x1bOR");
    }

    #[test]
    fn f4_plain() {
        let bytes =
            key_to_pty_bytes(Key::Named(NamedKey::F(4)), Modifiers::default(), false).unwrap();
        assert_eq!(bytes, b"\x1bOS");
    }

    #[test]
    fn f1_ctrl_uses_csi() {
        // Ctrl+F1 → \x1b[1;5P (CSI modifier form, not SS3).
        let bytes = key_to_pty_bytes(
            Key::Named(NamedKey::F(1)),
            Modifiers {
                ctrl: true,
                ..Default::default()
            },
            false,
        )
        .unwrap();
        assert_eq!(bytes, b"\x1b[1;5P");
    }

    #[test]
    fn delete_plain() {
        let bytes =
            key_to_pty_bytes(Key::Named(NamedKey::Delete), Modifiers::default(), false).unwrap();
        assert_eq!(bytes, b"\x1b[3~");
    }

    #[test]
    fn page_up_plain() {
        let bytes =
            key_to_pty_bytes(Key::Named(NamedKey::PageUp), Modifiers::default(), false).unwrap();
        assert_eq!(bytes, b"\x1b[5~");
    }

    #[test]
    fn delete_ctrl() {
        // Tilde-terminated keys with a modifier must use the form `\x1b[<code>;<mod>~`,
        // NOT `\x1b[1;<mod><code>~` (which is the cursor-letter form).
        let bytes = key_to_pty_bytes(
            Key::Named(NamedKey::Delete),
            Modifiers {
                ctrl: true,
                ..Default::default()
            },
            false,
        )
        .unwrap();
        assert_eq!(bytes, b"\x1b[3;5~");
    }

    #[test]
    fn page_up_ctrl() {
        let bytes = key_to_pty_bytes(
            Key::Named(NamedKey::PageUp),
            Modifiers {
                ctrl: true,
                ..Default::default()
            },
            false,
        )
        .unwrap();
        assert_eq!(bytes, b"\x1b[5;5~");
    }

    #[test]
    fn home_shift() {
        let bytes = key_to_pty_bytes(
            Key::Named(NamedKey::Home),
            Modifiers {
                shift: true,
                ..Default::default()
            },
            false,
        )
        .unwrap();
        // shift mod_param = 2 → "\x1b[1;2~"  (Home code = "1")
        assert_eq!(bytes, b"\x1b[1;2~");
    }

    #[test]
    fn end_alt() {
        let bytes = key_to_pty_bytes(
            Key::Named(NamedKey::End),
            Modifiers {
                alt: true,
                ..Default::default()
            },
            false,
        )
        .unwrap();
        // alt mod_param = 3 → "\x1b[4;3~"  (End code = "4")
        assert_eq!(bytes, b"\x1b[4;3~");
    }

    #[test]
    fn f5_ctrl() {
        // F5+ are tilde-terminated; Ctrl+F5 → \x1b[15;5~ (not \x1b[1;515~).
        let bytes = key_to_pty_bytes(
            Key::Named(NamedKey::F(5)),
            Modifiers {
                ctrl: true,
                ..Default::default()
            },
            false,
        )
        .unwrap();
        assert_eq!(bytes, b"\x1b[15;5~");
    }

    #[test]
    fn page_down_shift_ctrl() {
        let bytes = key_to_pty_bytes(
            Key::Named(NamedKey::PageDown),
            Modifiers {
                shift: true,
                ctrl: true,
                ..Default::default()
            },
            false,
        )
        .unwrap();
        // shift+ctrl mod_param = 6 → "\x1b[6;6~"  (PageDown code = "6")
        assert_eq!(bytes, b"\x1b[6;6~");
    }

    #[test]
    fn caps_lock_is_none() {
        let bytes = key_to_pty_bytes(Key::Named(NamedKey::CapsLock), Modifiers::default(), false);
        assert!(bytes.is_none());
    }

    // ── Application-cursor-keys mode (DECCKM on / app_cursor = true) ─────────

    /// In application-cursor mode, unmodified Up emits `ESC O A` (SS3).
    #[test]
    fn app_cursor_up_plain_is_ss3() {
        let bytes = key_to_pty_bytes(Key::Named(NamedKey::Up), Modifiers::default(), true).unwrap();
        assert_eq!(bytes, b"\x1bOA");
    }

    /// In application-cursor mode, unmodified Down emits `ESC O B`.
    #[test]
    fn app_cursor_down_plain_is_ss3() {
        let bytes =
            key_to_pty_bytes(Key::Named(NamedKey::Down), Modifiers::default(), true).unwrap();
        assert_eq!(bytes, b"\x1bOB");
    }

    /// In application-cursor mode, unmodified Right emits `ESC O C`.
    #[test]
    fn app_cursor_right_plain_is_ss3() {
        let bytes =
            key_to_pty_bytes(Key::Named(NamedKey::Right), Modifiers::default(), true).unwrap();
        assert_eq!(bytes, b"\x1bOC");
    }

    /// In application-cursor mode, unmodified Left emits `ESC O D`.
    #[test]
    fn app_cursor_left_plain_is_ss3() {
        let bytes =
            key_to_pty_bytes(Key::Named(NamedKey::Left), Modifiers::default(), true).unwrap();
        assert_eq!(bytes, b"\x1bOD");
    }

    /// In application-cursor mode, unmodified Home emits `ESC O H`.
    #[test]
    fn app_cursor_home_plain_is_ss3() {
        let bytes =
            key_to_pty_bytes(Key::Named(NamedKey::Home), Modifiers::default(), true).unwrap();
        assert_eq!(bytes, b"\x1bOH");
    }

    /// In application-cursor mode, unmodified End emits `ESC O F`.
    #[test]
    fn app_cursor_end_plain_is_ss3() {
        let bytes =
            key_to_pty_bytes(Key::Named(NamedKey::End), Modifiers::default(), true).unwrap();
        assert_eq!(bytes, b"\x1bOF");
    }

    /// Even in application-cursor mode, a modifier makes arrows fall back to
    /// the CSI form `ESC [ 1 ; <mod> A` — xterm does the same.
    #[test]
    fn app_cursor_up_ctrl_falls_back_to_csi() {
        let bytes = key_to_pty_bytes(
            Key::Named(NamedKey::Up),
            Modifiers {
                ctrl: true,
                ..Default::default()
            },
            true,
        )
        .unwrap();
        assert_eq!(bytes, b"\x1b[1;5A");
    }

    /// Even in application-cursor mode, Shift+Up falls back to CSI form.
    #[test]
    fn app_cursor_up_shift_falls_back_to_csi() {
        let bytes = key_to_pty_bytes(
            Key::Named(NamedKey::Up),
            Modifiers {
                shift: true,
                ..Default::default()
            },
            true,
        )
        .unwrap();
        assert_eq!(bytes, b"\x1b[1;2A");
    }

    /// Home with a modifier falls back to tilde-CSI even in app-cursor mode.
    #[test]
    fn app_cursor_home_shift_falls_back_to_csi() {
        let bytes = key_to_pty_bytes(
            Key::Named(NamedKey::Home),
            Modifiers {
                shift: true,
                ..Default::default()
            },
            true,
        )
        .unwrap();
        assert_eq!(bytes, b"\x1b[1;2~");
    }

    /// PageUp is never affected by DECCKM — always `ESC [ 5 ~`.
    #[test]
    fn app_cursor_page_up_unchanged() {
        let bytes =
            key_to_pty_bytes(Key::Named(NamedKey::PageUp), Modifiers::default(), true).unwrap();
        assert_eq!(bytes, b"\x1b[5~");
    }

    /// PageDown is never affected by DECCKM — always `ESC [ 6 ~`.
    #[test]
    fn app_cursor_page_down_unchanged() {
        let bytes =
            key_to_pty_bytes(Key::Named(NamedKey::PageDown), Modifiers::default(), true).unwrap();
        assert_eq!(bytes, b"\x1b[6~");
    }

    /// `encode_key`/`write_key` read `application_cursor_keys()` off the
    /// live session instead of requiring the caller to thread the flag
    /// through by hand — the whole point of moving this into the engine
    #[test]
    #[cfg(unix)]
    fn encode_key_reads_app_cursor_from_session() {
        let cwd = std::env::temp_dir();
        let sess =
            TerminalSession::spawn(80, 10, "/bin/sh", &cwd, 100).expect("failed to spawn /bin/sh");
        assert!(!sess.application_cursor_keys());
        let bytes = sess
            .encode_key(Key::Named(NamedKey::Up), Modifiers::default())
            .unwrap();
        // Not in application-cursor mode yet → plain CSI form.
        assert_eq!(bytes, b"\x1b[A");
    }

    // ── Mouse → PTY encoding (require a real PTY) ────────────────────────────

    /// With no mouse reporting and no alt-screen, the engine refuses to
    /// forward — `forward_mouse` returns `false` and `encode_mouse`
    /// returns `None`. Local handling (selection / scrollback) keeps
    /// working unchanged.
    #[test]
    #[cfg(unix)]
    fn no_forward_without_reporting_or_alt_screen() {
        let cwd = std::env::temp_dir();
        let mut sess =
            TerminalSession::spawn(80, 10, "/bin/sh", &cwd, 100).expect("failed to spawn /bin/sh");

        assert!(!sess.mouse_reporting_enabled());
        assert!(!sess.on_alt_screen());
        assert!(!sess.should_forward_wheel());

        // Wheel + click are both refused.
        assert!(sess
            .encode_mouse(
                TerminalMouseKind::WheelUp,
                MouseButton::Left,
                0,
                0,
                Modifiers::default()
            )
            .is_none());
        assert!(!sess.forward_mouse(
            TerminalMouseKind::Press,
            MouseButton::Left,
            0,
            0,
            Modifiers::default()
        ));

        sess.send_str("exit\n");
    }

    /// After the child enables xterm mouse reporting (`ESC[?1000h`), the
    /// engine starts forwarding mouse events to the PTY.
    #[test]
    #[cfg(unix)]
    fn forwards_after_mouse_reporting_enabled() {
        let cwd = std::env::temp_dir();
        let mut sess =
            TerminalSession::spawn(80, 10, "/bin/sh", &cwd, 100).expect("failed to spawn /bin/sh");

        // Child enables mouse reporting.
        sess.send_str("printf '\\033[?1000h'\n");
        assert!(
            poll_until(&mut sess, 5000, |s| s.mouse_reporting_enabled()),
            "mouse reporting did not turn on"
        );
        assert!(sess.should_forward_wheel());

        let bytes = sess.encode_mouse(
            TerminalMouseKind::WheelDown,
            MouseButton::Left,
            0,
            0,
            Modifiers::default(),
        );
        assert_eq!(bytes.as_deref(), Some(&b"\x1b[<65;1;1M"[..]));

        // Disable again — forwarding stops.
        sess.send_str("printf '\\033[?1000l'\n");
        assert!(
            poll_until(&mut sess, 5000, |s| !s.mouse_reporting_enabled()),
            "mouse reporting did not turn off"
        );
        assert!(!sess.should_forward_wheel());

        sess.send_str("exit\n");
    }

    /// Alt-screen entry alone (without explicit mouse reporting) makes the
    /// engine forward wheel events to the child — the routing rule that
    /// fixes embedded `claude` / `tmux` / `less`.
    #[test]
    #[cfg(unix)]
    fn wheel_forwards_on_alt_screen_even_without_mouse_reporting() {
        let cwd = std::env::temp_dir();
        let mut sess =
            TerminalSession::spawn(80, 10, "/bin/sh", &cwd, 100).expect("failed to spawn /bin/sh");

        sess.send_str("printf '\\033[?1049h'\n");
        assert!(
            poll_until(&mut sess, 5000, |s| s.on_alt_screen()),
            "did not enter alt-screen"
        );
        assert!(!sess.mouse_reporting_enabled()); // alt-screen alone
        assert!(sess.should_forward_wheel());

        // Press / Release / Move still gated on mouse reporting — alt-screen
        // alone is not enough for those (they only matter to apps that asked).
        assert!(sess
            .encode_mouse(
                TerminalMouseKind::Press,
                MouseButton::Left,
                0,
                0,
                Modifiers::default()
            )
            .is_none());

        // Wheel IS forwarded.
        assert!(sess
            .encode_mouse(
                TerminalMouseKind::WheelUp,
                MouseButton::Left,
                0,
                0,
                Modifiers::default()
            )
            .is_some());

        sess.send_str("printf '\\033[?1049l'\n");
        let _ = poll_until(&mut sess, 5000, |s| !s.on_alt_screen());
        sess.send_str("exit\n");
    }

    // ── `handle_wheel` — forward-vs-scrollback policy ────────────────────────

    /// With no mouse reporting and no alt-screen, `handle_wheel` falls back
    /// to local scrollback: returns `false`, and `scroll_offset` moves by
    /// exactly `step`.
    #[test]
    #[cfg(unix)]
    fn handle_wheel_scrolls_locally_without_forwarding() {
        let cwd = std::env::temp_dir();
        let mut sess =
            TerminalSession::spawn(80, 10, "/bin/sh", &cwd, 100).expect("failed to spawn /bin/sh");
        // Give it enough history to scroll into.
        for _ in 0..20 {
            sess.send_str("echo line\n");
        }
        let _ = poll_until(&mut sess, 2000, |s| s.history_len() >= 10);

        assert!(!sess.should_forward_wheel());

        // Distinct, nonzero col/row on each call to prove they're accepted
        // (and would be threaded through to the child) even though this
        // path falls back to local scrollback.
        let forwarded = sess.handle_wheel(true, 3, 12, 4);
        assert!(!forwarded);
        assert_eq!(sess.scroll_offset(), 3);

        let forwarded = sess.handle_wheel(false, 2, 7, 9);
        assert!(!forwarded);
        assert_eq!(sess.scroll_offset(), 1);

        sess.send_str("exit\n");
    }

    /// Once the child owns the wheel (mouse reporting on), `handle_wheel`
    /// forwards instead of touching local scrollback: returns `true`, and
    /// `scroll_offset` is untouched.
    #[test]
    #[cfg(unix)]
    fn handle_wheel_forwards_when_child_owns_it() {
        let cwd = std::env::temp_dir();
        let mut sess =
            TerminalSession::spawn(80, 10, "/bin/sh", &cwd, 100).expect("failed to spawn /bin/sh");

        sess.send_str("printf '\\033[?1000h'\n");
        assert!(
            poll_until(&mut sess, 5000, |s| s.mouse_reporting_enabled()),
            "mouse reporting did not turn on"
        );

        let before = sess.scroll_offset();
        let forwarded = sess.handle_wheel(true, 3, 12, 4);
        assert!(forwarded);
        assert_eq!(sess.scroll_offset(), before);

        sess.send_str("exit\n");
    }

    /// Scrollback must NOT grow while the child is on the alternate screen,
    #[test]
    #[cfg(unix)]
    fn scrollback_skipped_on_alt_screen_resumes_on_primary() {
        let cwd = std::env::temp_dir();
        // Small screen so each `echo` line scrolls quickly.
        let mut sess =
            TerminalSession::spawn(40, 5, "/bin/sh", &cwd, 1000).expect("failed to spawn /bin/sh");

        // Drain initial prompt.
        let _ = poll_until(&mut sess, 1000, |_| false);

        // Enter alt-screen.
        sess.send_str("printf '\\033[?1049h'\n");
        assert!(
            poll_until(&mut sess, 5000, |s| s.on_alt_screen()),
            "did not enter alt-screen"
        );

        // Record baseline AFTER we're on alt-screen (the `printf` command
        // line itself may have scrolled some rows on the primary screen).
        let baseline = sess.history_len();

        // Generate many lines of output. Each scrolls the alt-screen, but
        // alt-screen scrolls MUST NOT touch our history ring.
        for _ in 0..40 {
            sess.send_str("echo alt_content\n");
        }
        // Wait long enough for all the output to flush through the PTY.
        let _ = poll_until(&mut sess, 2000, |_| false);

        assert_eq!(
            sess.history_len(),
            baseline,
            "history grew while on alt-screen — alt-screen churn must not pollute shell scrollback"
        );

        // Exit alt-screen.
        sess.send_str("printf '\\033[?1049l'\n");
        assert!(
            poll_until(&mut sess, 5000, |s| !s.on_alt_screen()),
            "did not exit alt-screen"
        );

        // Generate more lines on the primary screen — history SHOULD grow now.
        for _ in 0..40 {
            sess.send_str("echo primary_content\n");
        }
        assert!(
            poll_until(&mut sess, 5000, |s| s.history_len() > baseline + 5),
            "history did not resume growing after returning to primary screen"
        );

        sess.send_str("exit\n");
    }

    /// `application_cursor_keys()` reflects the child's DECCKM state
    #[test]
    #[cfg(unix)]
    fn application_cursor_keys_tracks_decckm() {
        let cwd = std::env::temp_dir();
        let mut sess =
            TerminalSession::spawn(80, 24, "/bin/sh", &cwd, 1000).expect("failed to spawn /bin/sh");

        // Off by default.
        assert!(!sess.application_cursor_keys());

        // Emit ESC[?1h — the sequence programs like vim/claude use on entry.
        sess.send_str("printf '\\033[?1h'\n");
        assert!(
            poll_until(&mut sess, 5000, |s| s.application_cursor_keys()),
            "DECCKM should be enabled after ESC[?1h"
        );

        // Emit ESC[?1l — the exit/restore sequence.
        sess.send_str("printf '\\033[?1l'\n");
        assert!(
            poll_until(&mut sess, 5000, |s| !s.application_cursor_keys()),
            "DECCKM should be disabled after ESC[?1l"
        );

        sess.send_str("exit\n");
    }

    // ── DECSCUSR cursor shape / blink ───────────────────────────────────────

    /// [`decscusr_shape`] maps every one of the six standard `Ps` values,
    /// plus the `0` == `1` alias, to the right `(shape, blinking)` pair.
    /// Pure unit test — no parser or PTY involved.
    #[test]
    fn decscusr_shape_maps_all_standard_ps_values() {
        assert_eq!(
            decscusr_shape(0),
            Some((TerminalCursorShape::Block, true)),
            "Ps=0 (omitted) aliases Ps=1 per xterm"
        );
        assert_eq!(decscusr_shape(1), Some((TerminalCursorShape::Block, true)));
        assert_eq!(decscusr_shape(2), Some((TerminalCursorShape::Block, false)));
        assert_eq!(
            decscusr_shape(3),
            Some((TerminalCursorShape::Underline, true))
        );
        assert_eq!(
            decscusr_shape(4),
            Some((TerminalCursorShape::Underline, false))
        );
        assert_eq!(decscusr_shape(5), Some((TerminalCursorShape::Bar, true)));
        assert_eq!(decscusr_shape(6), Some((TerminalCursorShape::Bar, false)));
    }

    /// A `Ps` value outside the standard `0..=6` range is ignored (`None`),
    /// not mapped to a fallback shape — see the `unhandled_csi` call
    /// site's doc for why the caller keeps the last-known-good state
    /// instead of resetting it.
    #[test]
    fn decscusr_shape_ignores_out_of_range_ps() {
        assert_eq!(decscusr_shape(7), None);
        assert_eq!(decscusr_shape(999), None);
    }

    // ── terminal_query_replies (ConPTY handshake fix) ─────────────────────────

    #[test]
    fn terminal_query_replies_answers_cursor_position_query() {
        let reply = terminal_query_replies(b"\x1b[6n", (0, 0));
        assert_eq!(reply, b"\x1b[1;1R");
    }

    /// The reply reports the *current* cursor position, not always `1;1` —
    /// 0-based `cursor_position()` converted to the 1-based wire format.
    #[test]
    fn terminal_query_replies_cursor_position_uses_the_given_cursor() {
        let reply = terminal_query_replies(b"\x1b[6n", (4, 9));
        assert_eq!(reply, b"\x1b[5;10R");
    }

    #[test]
    fn terminal_query_replies_answers_primary_device_attributes_query() {
        assert_eq!(terminal_query_replies(b"\x1b[c", (0, 0)), b"\x1b[?1;0c");
        assert_eq!(terminal_query_replies(b"\x1b[0c", (0, 0)), b"\x1b[?1;0c");
    }

    /// An unrelated CSI sequence (here, "clear screen") must not be
    /// mistaken for a query — no reply at all.
    #[test]
    fn terminal_query_replies_ignores_unrelated_csi_sequences() {
        assert!(terminal_query_replies(b"\x1b[2J", (0, 0)).is_empty());
    }

    /// Secondary Device Attributes (`ESC[>c`) is a real, distinct query
    /// real terminals do answer, but this engine doesn't recognise it yet —
    /// pinned here so a future addition is a deliberate change, not a
    /// silent behaviour drift.
    #[test]
    fn terminal_query_replies_does_not_answer_secondary_device_attributes() {
        assert!(terminal_query_replies(b"\x1b[>c", (0, 0)).is_empty());
    }

    #[test]
    fn terminal_query_replies_ignores_plain_text_with_no_escape_sequences() {
        assert!(terminal_query_replies(b"hello, world\r\n", (0, 0)).is_empty());
    }

    /// A chunk can contain ordinary output *and* a query mixed together —
    /// the scan must find the query wherever it falls, not only at the
    /// start of the buffer, and answer only once.
    #[test]
    fn terminal_query_replies_finds_a_query_mixed_with_other_output() {
        let mut data = b"some prompt text ".to_vec();
        data.extend_from_slice(b"\x1b[6n");
        data.extend_from_slice(b" more text");
        assert_eq!(terminal_query_replies(&data, (0, 0)), b"\x1b[1;1R");
    }

    /// Two distinct queries in the same chunk both get answered, in order.
    #[test]
    fn terminal_query_replies_answers_multiple_queries_in_one_chunk() {
        let mut data = b"\x1b[6n".to_vec();
        data.extend_from_slice(b"\x1b[c");
        let mut expected = b"\x1b[1;1R".to_vec();
        expected.extend_from_slice(b"\x1b[?1;0c");
        assert_eq!(terminal_query_replies(&data, (0, 0)), expected);
    }

    /// A CSI sequence truncated mid-parameter (split across two PTY reads)
    /// must not panic or spin — it's simply left unanswered in this chunk.
    #[test]
    fn terminal_query_replies_handles_a_truncated_sequence_without_panicking() {
        assert!(terminal_query_replies(b"\x1b[6", (0, 0)).is_empty());
        assert!(terminal_query_replies(b"\x1b[", (0, 0)).is_empty());
        assert!(terminal_query_replies(b"\x1b", (0, 0)).is_empty());
    }

    /// A single-byte stream of unrelated bytes shorter than any CSI prefix
    /// must not panic on the `i + 1 >= data.len()` boundary check.
    #[test]
    fn terminal_query_replies_handles_a_lone_escape_byte_without_panicking() {
        assert!(terminal_query_replies(&[0x1b], (0, 0)).is_empty());
        assert!(terminal_query_replies(&[], (0, 0)).is_empty());
    }

    /// A `ESC[6n` sent with an unexpected private marker (e.g. the `?`
    /// form some terminals use for a different report) is not the plain
    /// `6` this engine answers — left unanswered rather than guessed at.
    #[test]
    fn terminal_query_replies_does_not_answer_a_6n_with_a_private_marker() {
        assert!(terminal_query_replies(b"\x1b[?6n", (0, 0)).is_empty());
    }

    /// A session that never receives any DECSCUSR sequence reports the
    /// documented defaults: `Block`, steady.
    #[test]
    #[cfg(unix)]
    fn cursor_shape_defaults_to_steady_block() {
        let cwd = std::env::temp_dir();
        let sess =
            TerminalSession::spawn(80, 24, "/bin/sh", &cwd, 1000).expect("failed to spawn /bin/sh");
        assert_eq!(sess.cursor_shape(), TerminalCursorShape::Block);
        assert!(!sess.cursor_blinking());
    }

    /// `cursor_shape()`/`cursor_blinking()` track a real child's DECSCUSR
    #[test]
    #[cfg(unix)]
    fn cursor_shape_tracks_decscusr() {
        let cwd = std::env::temp_dir();
        let mut sess =
            TerminalSession::spawn(80, 24, "/bin/sh", &cwd, 1000).expect("failed to spawn /bin/sh");

        // Ps=6: steady bar — the "entering insert mode" sequence.
        sess.send_str("printf '\\033[6 q'\n");
        assert!(
            poll_until(&mut sess, 5000, |s| s.cursor_shape()
                == TerminalCursorShape::Bar),
            "cursor shape should become Bar after ESC[6 q"
        );
        assert!(!sess.cursor_blinking(), "Ps=6 is the steady bar variant");

        // Ps=4: steady underline.
        sess.send_str("printf '\\033[4 q'\n");
        assert!(
            poll_until(&mut sess, 5000, |s| s.cursor_shape()
                == TerminalCursorShape::Underline),
            "cursor shape should become Underline after ESC[4 q"
        );

        // Ps=1: blinking block — the "back to normal mode" sequence.
        sess.send_str("printf '\\033[1 q'\n");
        assert!(
            poll_until(&mut sess, 5000, |s| s.cursor_shape()
                == TerminalCursorShape::Block
                && s.cursor_blinking()),
            "cursor shape should become blinking Block after ESC[1 q"
        );

        sess.send_str("exit\n");
    }

    /// `to_terminal()`'s cell grid stamps the session's DECSCUSR state
    /// onto the cursor cell — and *only* the cursor cell — matching the
    /// existing `is_cursor` contract. Pure unit test: injects
    /// `EngineCallbacks` state directly via `unhandled_csi` on a bare
    /// `vt100::Parser`, no PTY needed.
    #[test]
    #[cfg(unix)]
    fn build_rows_stamps_cursor_shape_only_on_the_cursor_cell() {
        let cwd = std::env::temp_dir();
        // A minimal session is still the easiest way to get a fully
        // initialised `TerminalSession` (real PTY, but no output waited
        // on) — mirrors the "Selection-in-scrollback" tests' rationale
        // above.
        let mut sess =
            TerminalSession::spawn(10, 3, "/bin/sh", &cwd, 100).expect("failed to spawn /bin/sh");
        // Poke the callback state directly rather than round-tripping
        // through a real PTY write — this test is about `build_rows`'
        // wiring, not DECSCUSR parsing itself (covered above).
        sess.parser.callbacks_mut().cursor_shape = TerminalCursorShape::Bar;
        sess.parser.callbacks_mut().cursor_blinking = true;

        let snapshot = sess.to_terminal(WidgetId::new("t"), None);
        let (cursor_row, cursor_col) = sess.parser.screen().cursor_position();
        for (r, row) in snapshot.cells.iter().enumerate() {
            for (c, cell) in row.iter().enumerate() {
                if cell.is_cursor {
                    assert_eq!(r as u16, cursor_row);
                    assert_eq!(c as u16, cursor_col);
                    assert_eq!(cell.cursor_shape, TerminalCursorShape::Bar);
                    assert!(cell.cursor_blinking);
                } else {
                    assert_eq!(cell.cursor_shape, TerminalCursorShape::Block);
                    assert!(!cell.cursor_blinking);
                }
            }
        }
    }

    /// Verify that `screen_text()` returns non-empty content after the shell
    /// produces output, and that it strips trailing blank rows.
    #[test]
    #[cfg(unix)]
    fn screen_text_strips_trailing_blanks() {
        let cwd = std::env::temp_dir();
        let mut sess =
            TerminalSession::spawn(80, 10, "/bin/sh", &cwd, 100).expect("failed to spawn /bin/sh");

        // Wait for the shell prompt (any output at all).
        let _ = poll_until(&mut sess, 3000, |s| !s.screen_text().is_empty());
        let text = sess.screen_text();
        // Must not end with a blank line.
        assert!(
            !text.ends_with('\n'),
            "screen_text() should not end with a newline; got: {text:?}"
        );
        sess.send_str("exit\n");
    }

    // ── Selection-in-scrollback tests (pure unit — no PTY output needed) ─────
    //
    // These tests inject history rows directly into `TerminalSession::history`
    // (accessible because `mod tests` is a child of the same module) and
    // exercise `selected_text` / `build_rows` without waiting for shell output.
    // A real PTY is still spawned so the struct is fully initialised, but no
    // `poll()` calls are made, so PTY output cannot race with the injected
    // history rows.

    /// Build a `Vec<HistCell>` row that fills `cols` columns with `ch` in the
    /// first `text_len` cells and spaces thereafter.
    #[cfg(unix)]
    fn make_hist_row_content(text: &str, cols: u16) -> Vec<HistCell> {
        let chars: Vec<char> = text.chars().collect();
        (0..cols as usize)
            .map(|i| HistCell {
                text: chars
                    .get(i)
                    .map_or_else(|| " ".to_string(), |c| c.to_string()),
                ..Default::default()
            })
            .collect()
    }

    /// `selected_text()` returns the correct history text when the view is
    /// fully scrolled into the scrollback buffer (all display rows are history
    /// rows, `scroll_offset == rows`).
    ///
    /// Before the fix this returned `None` regardless of the selection.
    #[test]
    #[cfg(unix)]
    fn selected_text_from_pure_history() {
        let cwd = std::env::temp_dir();
        // 10 cols × 4 rows — small enough that scrolling is easy to reason about.
        let mut sess = TerminalSession::spawn(10, 4, "/bin/sh", &cwd, 100).expect("spawn failed");

        // Inject three known history rows (no poll() — avoids races with PTY).
        sess.history
            .push_back(make_hist_row_content("AAAA", sess.cols));
        sess.history
            .push_back(make_hist_row_content("BBBB", sess.cols));
        sess.history
            .push_back(make_hist_row_content("CCCC", sess.cols));

        // Scroll so all 3 history rows are visible at the top; the 4th
        // display row would be a live row we don't care about.
        // scroll_offset = 3: display_r 0,1,2 → hist[0,1,2]; display_r 3 → live.
        sess.set_scroll_offset(3);

        // Select display row 1 (= history row "BBBB"), columns 0-3 inclusive.
        sess.selection = Some(TerminalSelection {
            start_row: 1,
            start_col: 0,
            end_row: 1,
            end_col: 3,
        });

        let text = sess
            .selected_text()
            .expect("selected_text() must be Some when scrolled");
        assert_eq!(
            text, "BBBB",
            "expected 'BBBB' from history row 1, got: {text:?}"
        );

        sess.send_str("exit\n");
    }

    /// `selected_text()` returns the correct text for a multi-row selection
    /// that spans multiple history rows.
    #[test]
    #[cfg(unix)]
    fn selected_text_multi_row_in_history() {
        let cwd = std::env::temp_dir();
        let mut sess = TerminalSession::spawn(10, 5, "/bin/sh", &cwd, 100).expect("spawn failed");

        sess.history
            .push_back(make_hist_row_content("LINE0", sess.cols));
        sess.history
            .push_back(make_hist_row_content("LINE1", sess.cols));
        sess.history
            .push_back(make_hist_row_content("LINE2", sess.cols));

        // Scroll_offset = 3: display rows 0,1,2 → history rows 0,1,2.
        sess.set_scroll_offset(3);

        // Select display rows 0–2, full width (cols 0 to 4 each).
        sess.selection = Some(TerminalSelection {
            start_row: 0,
            start_col: 0,
            end_row: 2,
            end_col: 4,
        });

        let text = sess.selected_text().expect("selected_text() must be Some");
        let lines: Vec<&str> = text.split('\n').collect();
        assert_eq!(lines.len(), 3, "expected 3 lines, got: {lines:?}");
        assert_eq!(lines[0], "LINE0", "row 0: got {:?}", lines[0]);
        assert_eq!(lines[1], "LINE1", "row 1: got {:?}", lines[1]);
        assert_eq!(lines[2], "LINE2", "row 2: got {:?}", lines[2]);

        sess.send_str("exit\n");
    }

    /// `build_rows()` marks cells `selected = true` for history rows when a
    /// selection covers them.
    ///
    /// Before the fix the `selected` flag was always `false` for history rows.
    #[test]
    #[cfg(unix)]
    fn build_rows_highlights_selection_in_history() {
        let cwd = std::env::temp_dir();
        let mut sess = TerminalSession::spawn(6, 4, "/bin/sh", &cwd, 100).expect("spawn failed");

        // One history row, 6 columns: ['H','I','S','T',' ',' '].
        sess.history
            .push_back(make_hist_row_content("HIST", sess.cols));
        // One more to ensure display_r=0 maps to the right row.
        sess.history
            .push_back(make_hist_row_content("XXXX", sess.cols));

        // scroll_offset = 2: display_r 0 → history[0]="HIST", display_r 1 → history[1]="XXXX"
        sess.set_scroll_offset(2);

        // Select display_r = 0, cols 1-3 → "IST"
        sess.selection = Some(TerminalSelection {
            start_row: 0,
            start_col: 1,
            end_row: 0,
            end_col: 3,
        });

        let rows = sess.build_rows(false);

        // display row 0: cols 1,2,3 must be selected; col 0 and 4+ must not.
        let row0 = &rows[0];
        assert!(!row0[0].selected, "col 0 should NOT be selected");
        assert!(row0[1].selected, "col 1 should be selected");
        assert!(row0[2].selected, "col 2 should be selected");
        assert!(row0[3].selected, "col 3 should be selected");
        assert!(!row0[4].selected, "col 4 should NOT be selected");

        // display row 1 (different history row) should have no selection.
        let row1 = &rows[1];
        assert!(
            row1.iter().all(|c| !c.selected),
            "row 1 should have no selection"
        );

        sess.send_str("exit\n");
    }

    // ── Grapheme cluster / wide-char cell content ──────────────────────

    /// `build_rows()`'s live-screen branch must carry a cell's *full*
    /// grapheme cluster — base character plus any combining marks — not
    /// just the first `char`. Feeds vt100 directly via `sess.parser`
    /// (same technique as `resize_preserves_wide_chars`) so the byte
    /// content is exact and doesn't depend on shell echo timing.
    #[test]
    #[cfg(unix)]
    fn build_rows_live_screen_preserves_combining_mark_grapheme() {
        let cwd = std::env::temp_dir();
        let mut sess = TerminalSession::spawn(10, 4, "/bin/sh", &cwd, 100).expect("spawn failed");

        // 'e' + U+0301 COMBINING ACUTE ACCENT — a two-codepoint grapheme
        // cluster vt100 stores in a single cell (`Cell::contents()`
        // returns both codepoints for one column).
        sess.parser.process("e\u{0301}".as_bytes());

        let rows = sess.build_rows(false);
        assert_eq!(
            rows[0][0].text, "e\u{0301}",
            "combining mark must survive into the cell's text, not just 'e'"
        );
        assert_eq!(
            rows[0][0].cell_width(),
            1,
            "base char + combining accent is still one column wide"
        );
        // The accent must not have consumed a second column — column 1
        // is still blank.
        assert_eq!(rows[0][1].text, " ");

        sess.send_str("exit\n");
    }

    /// `build_rows()`'s live-screen branch must reserve a two-column box
    /// for a wide (CJK) glyph and leave vt100's blank continuation
    /// column as-is, so column accounting downstream (TUI/GTK/macOS/win
    /// rasterisers) matches vt100's own layout exactly.
    #[test]
    #[cfg(unix)]
    fn build_rows_live_screen_wide_char_reserves_continuation_column() {
        let cwd = std::env::temp_dir();
        let mut sess = TerminalSession::spawn(10, 4, "/bin/sh", &cwd, 100).expect("spawn failed");

        // '日' is double-width; vt100 gives it column 0 and leaves
        // column 1 as an empty continuation cell.
        sess.parser.process("日B".as_bytes());

        let rows = sess.build_rows(false);
        assert_eq!(rows[0][0].text, "日");
        assert_eq!(rows[0][0].cell_width(), 2);
        assert_eq!(
            rows[0][1].text, " ",
            "wide glyph's continuation column must be blank, not a second copy"
        );
        // 'B' lands in column 2 — the continuation column at index 1
        // wasn't (incorrectly) treated as a second content column.
        assert_eq!(rows[0][2].text, "B");
        assert_eq!(rows[0][2].cell_width(), 1);

        sess.send_str("exit\n");
    }

    // SGR 2 faint/dim — vt100 ≥ 0.16 tracks this via `Cell::dim()`.

    /// `build_rows()`'s live-screen branch must carry vt100's SGR 2
    /// (faint) attribute into `TerminalCell::dim`. Feeds vt100 directly
    /// via `sess.parser` (same technique as
    /// `build_rows_live_screen_preserves_combining_mark_grapheme`) so the
    /// SGR sequence is exact and doesn't depend on shell echo timing.
    #[test]
    #[cfg(unix)]
    fn build_rows_live_screen_carries_dim_attribute() {
        let cwd = std::env::temp_dir();
        let mut sess = TerminalSession::spawn(10, 4, "/bin/sh", &cwd, 100).expect("spawn failed");

        // ESC[2m = SGR 2 (faint/dim) → 'D'. ESC[0m resets before 'N', a
        // normal-intensity glyph in the next column.
        sess.parser.process(b"\x1b[2mD\x1b[0mN");

        let rows = sess.build_rows(false);
        assert!(
            rows[0][0].dim,
            "cell painted under SGR 2 must carry dim = true"
        );
        assert!(
            !rows[0][1].dim,
            "cell painted after SGR 0 reset must not be dim"
        );

        sess.send_str("exit\n");
    }

    /// `build_rows()`'s history branch must also carry a captured cell's
    /// `dim` flag — mirrors `build_rows_highlights_selection_in_history`'s
    /// pure-unit technique (inject `HistCell`s directly, no PTY timing).
    #[test]
    #[cfg(unix)]
    fn build_rows_history_carries_dim_attribute() {
        let cwd = std::env::temp_dir();
        let mut sess = TerminalSession::spawn(6, 4, "/bin/sh", &cwd, 100).expect("spawn failed");

        let mut row = make_hist_row_content("DIM ", sess.cols);
        row[0].dim = true;
        sess.history.push_back(row);
        sess.set_scroll_offset(1);

        let rows = sess.build_rows(false);
        assert!(
            rows[0][0].dim,
            "history cell's dim flag must survive into build_rows output"
        );
        assert!(!rows[0][1].dim, "non-dim history cells must stay non-dim");

        sess.send_str("exit\n");
    }

    /// `capture_scrolled_rows()` must preserve a full grapheme cluster
    #[test]
    #[cfg(unix)]
    fn capture_scrolled_rows_preserves_combining_mark_grapheme() {
        let cwd = std::env::temp_dir();
        let mut sess = TerminalSession::spawn(10, 1, "/bin/sh", &cwd, 100).expect("spawn failed");

        sess.process_with_capture("e\u{0301}\n".as_bytes());

        assert_eq!(sess.history.len(), 1, "one row should have scrolled off");
        assert_eq!(
            sess.history[0][0].text, "e\u{0301}",
            "combining mark must survive scrollback capture, not just 'e'"
        );

        sess.send_str("exit\n");
    }

    /// `capture_scrolled_rows()` must also carry a captured cell's SGR 2
    /// (faint) attribute into `HistCell::dim` — same
    /// technique as the grapheme-cluster capture test above.
    #[test]
    #[cfg(unix)]
    fn capture_scrolled_rows_preserves_dim_attribute() {
        let cwd = std::env::temp_dir();
        let mut sess = TerminalSession::spawn(10, 1, "/bin/sh", &cwd, 100).expect("spawn failed");

        sess.process_with_capture(b"\x1b[2mD\x1b[0m\n");

        assert_eq!(sess.history.len(), 1, "one row should have scrolled off");
        assert!(
            sess.history[0][0].dim,
            "faint cell must survive scrollback capture as dim = true"
        );

        sess.send_str("exit\n");
    }

    /// `selected_text()` at `scroll_offset == 0` (live view) continues to
    /// work correctly — regression guard.
    #[test]
    #[cfg(unix)]
    fn selected_text_live_view_no_regression() {
        let cwd = std::env::temp_dir();
        let mut sess = TerminalSession::spawn(10, 4, "/bin/sh", &cwd, 100).expect("spawn failed");

        // At live view with no selection, must return None.
        assert!(sess.selection.is_none());
        assert!(sess.selected_text().is_none());

        // Set a selection and confirm we get Some (content is live-screen
        // dependent so we only check it's non-None and correctly typed).
        sess.selection = Some(TerminalSelection {
            start_row: 0,
            start_col: 0,
            end_row: 0,
            end_col: 4,
        });
        assert!(
            sess.selected_text().is_some(),
            "selected_text() must be Some when selection is set at live view"
        );

        sess.send_str("exit\n");
    }

    /// A selection spanning the history/live boundary: the history part is
    /// extracted from `self.history` and the live part from the vt100 screen.
    /// The result must be `Some(_)` and contain the history text on the first line.
    #[test]
    #[cfg(unix)]
    fn selected_text_spans_history_live_boundary() {
        let cwd = std::env::temp_dir();
        // 10 cols × 5 rows.
        let mut sess = TerminalSession::spawn(10, 5, "/bin/sh", &cwd, 100).expect("spawn failed");

        // Inject two history rows.
        sess.history
            .push_back(make_hist_row_content("HIST0", sess.cols));
        sess.history
            .push_back(make_hist_row_content("HIST1", sess.cols));

        // scroll_offset = 2: display_r 0 → HIST0, display_r 1 → HIST1,
        //                    display_r 2+ → live rows.
        sess.set_scroll_offset(2);

        // Selection: display row 1 (last history row) through display row 2
        // (first live row), columns 0-4.
        sess.selection = Some(TerminalSelection {
            start_row: 1,
            start_col: 0,
            end_row: 2,
            end_col: 4,
        });

        let text = sess
            .selected_text()
            .expect("selected_text() must be Some at boundary");
        let lines: Vec<&str> = text.split('\n').collect();
        assert_eq!(
            lines.len(),
            2,
            "expected 2 lines (history + live); got: {lines:?}"
        );
        assert_eq!(
            lines[0], "HIST1",
            "first line must come from history; got: {:?}",
            lines[0]
        );
        // lines[1] is from the live screen (shell prompt) — content is
        // non-deterministic, so we just verify it was included.

        sess.send_str("exit\n");
    }
}

/// Property tests for the vt100 parser this engine wraps.
/// Everything fed to [`vt100::Parser::process`] is untrusted, foreign
/// data by construction — it's whatever bytes the child shell/program
/// running inside the PTY chooses to write, including a hostile or
/// buggy program deliberately or accidentally emitting malformed escape
/// sequences — so "never panics" needs to hold over the arbitrary byte
/// space, not just hand-picked regression fixtures.
#[cfg(test)]
mod proptests {
    use super::{reflow_screen, MIN_VT100_COLS, MIN_VT100_ROWS};
    use proptest::prelude::*;

    proptest! {
        /// No byte sequence, however malformed (a truncated CSI, an
        /// out-of-range SGR parameter, a lone high continuation byte, a
        #[test]
        fn vt100_parser_never_panics(
            rows in MIN_VT100_ROWS..60,
            cols in MIN_VT100_COLS..200,
            bytes in prop::collection::vec(any::<u8>(), 0..2000),
        ) {
            let mut parser = vt100::Parser::new(rows, cols, 0);
            parser.process(&bytes);
        }

        /// Same, but the byte stream is valid UTF-8 text (still
        /// arbitrary — no attempt to keep it well-formed *terminal*
        /// output) — the shape a foreign program's plain-text output,
        /// as opposed to raw garbage, actually takes.
        #[test]
        fn vt100_parser_never_panics_on_arbitrary_utf8(
            rows in MIN_VT100_ROWS..60,
            cols in MIN_VT100_COLS..200,
            s in ".{0,2000}",
        ) {
            let mut parser = vt100::Parser::new(rows, cols, 0);
            parser.process(s.as_bytes());
        }

        /// A resize mid-stream followed by more arbitrary bytes must not
        /// panic either — this is the exact scenario [`reflow_screen`]'s
        /// doc comment calls out as the highest-risk path (wide-char cells
        #[test]
        fn vt100_parser_never_panics_across_a_resize(
            rows in MIN_VT100_ROWS..60,
            cols in MIN_VT100_COLS..200,
            new_rows in MIN_VT100_ROWS..60,
            new_cols in MIN_VT100_COLS..200,
            alternate in any::<bool>(),
            before in prop::collection::vec(any::<u8>(), 0..1000),
            after in prop::collection::vec(any::<u8>(), 0..1000),
        ) {
            let mut parser = vt100::Parser::new(rows, cols, 0);
            if alternate {
                parser.process(b"\x1b[?1049h");
            }
            parser.process(&before);
            reflow_screen(&mut parser, new_rows, new_cols);
            parser.process(&after);
        }

        /// The orphaned-wide-cell shrink narrowed to its
        /// essentials and re-randomised: a double-width glyph parked so
        /// that the shrink lands between its two halves, on every
        /// (old width, new width) pair that can straddle it.
        ///
        /// The generic property above finds this too, but only on a lucky
        /// seed — it was a ~5% hit rate there, which is why it reached CI
        /// green on Linux and red on Windows. This one hits it every run.
        #[test]
        fn reflow_survives_a_wide_glyph_split_by_the_new_width(
            rows in MIN_VT100_ROWS..8,
            new_cols in 4u16..40,
            extra in 0u16..12,
            alternate in any::<bool>(),
        ) {
            let cols = new_cols + 1 + extra;
            let mut parser = vt100::Parser::new(rows, cols, 0);
            if alternate {
                parser.process(b"\x1b[?1049h");
            }
            // Pad so the wide glyph's first half lands exactly on the
            // column that is about to become the last one, and its
            // continuation half on the first column to be truncated.
            let mut bytes = vec![b' '; usize::from(new_cols) - 1];
            bytes.extend_from_slice("\u{3000}".as_bytes());
            parser.process(&bytes);
            prop_assert!(
                parser.screen().cell(0, new_cols - 1).is_some_and(vt100::Cell::is_wide),
                "fixture must park a wide first half on the truncation boundary"
            );
            reflow_screen(&mut parser, rows, new_cols);
            // Writing over the (formerly) orphaned cell is what panicked.
            parser.process(b"\x1b[1;1H");
            parser.process(&vec![b'x'; usize::from(new_cols) * 2]);
        }
    }
}