termlens 0.11.0

Headless PTY test harness for CLI/TUI apps — spawn in a real PTY, assert on the rendered screen
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
//! A minimal escape-sequence progress tracker.
//!
//! This is deliberately NOT a VT parser — the emulator interprets the
//! stream. It answers two questions:
//!
//! 1. For `wait_idle`: *did the byte stream end in the middle of
//!    something?* — an escape/CSI/OSC/DCS sequence or a partial UTF-8
//!    character. Declaring a terminal "idle" between the two halves of a
//!    split `ESC [ 3 1 m` would hand tests a torn frame.
//! 2. For `wait_frame`: *where do synchronized updates begin and end?*
//!    DEC private mode 2026 (`CSI ? 2026 h` / `CSI ? 2026 l`) brackets a
//!    repaint; the byte that ends one marks a complete frame. Parameters
//!    are parsed incrementally in O(1) space, and `?2026` is recognized
//!    anywhere in a multi-mode list such as `CSI ? 2026 ; 25 h`.
//!
//! It also tracks screen state the vt100 backend does not expose: the
//! **window title** (`OSC 0`/`OSC 2`), kept whole in its own buffer — the
//! diagnostic capture below truncates at 24 bytes, real titles don't fit —
//! focus reporting (mode 1004), the cursor shape (`DECSCUSR`), and the
//! **set of mouse tracking modes** the application asked for, which vt100
//! collapses into the one protocol it would report in.
//!
//! And it holds the **character-set state** vt100 ignores: which glyph set
//! `ESC ( ) * + Ps` designated into G0–G3, which of G0/G1 `SI`/`SO` has
//! lock-shifted, and whether `ESC N` (SS2) / `ESC O` (SS3) has invoked G2/G3
//! for the next character only. That is what lets the emulator hand the grid
//! the glyph a byte *draws* — `ESC ( 0 l q q q k` is `┌───┐`, not five
//! letters — which is how ncurses draws every border (`smacs`/`rmacs` on an
//! xterm terminfo are exactly `ESC ( 0` / `ESC ( B`). A mixed line of text
//! and box-drawing uses the single shift instead, so `ESC * 0 ESC N l` is
//! `┌` and the character after it is back to the locked set. Two sets are
//! translated: DEC Special Graphics, and the UK set (`ESC ( A`), whose one
//! difference from ASCII is `£` at `#`; every other designation — the
//! alternate ROMs, the other national sets — is acknowledged and reads as
//! ASCII. `DECSC`/`DECRC` save and restore this state alongside the cursor,
//! and `RIS` and `DECSTR` return it to power-on. Locking shifts remain G0/G1
//! (`SO`/`SI`); `LS2`/`LS3` are not modelled. The tracker decides, the
//! emulator rewrites: the bytes the
//! parsers see are then a translated stream rather than a sub-slice of the
//! read, which `emu/vt100.rs` stages.
//!
//! The same split holds the **tab stops** (see [`TabStops`]). vt100 has a
//! hardcoded eight and no way to be told otherwise, so `HTS`, `TBC`, `CHT`
//! and `CBT` reached its dispatch table and vanished — and an application
//! that lays a table out by setting its own stops, which is what the
//! capabilities are for, drew every column in the wrong place. The set
//! lives here; the *cursor column* every one of those operations needs
//! lives in the grid, so the tracker emits a [`TabOp`] and the emulator
//! resolves it against the position it holds, rewriting a motion as `CHA`
//! (`CSI n G`) — a sequence the backend does dispatch, the same way DEC
//! Special Graphics became a glyph substitution. Plain `HT` is rewritten
//! too, or vt100's fixed eight and these stops would disagree the moment an
//! application set one.

use std::sync::Arc;

use crate::graphics::{GraphicsBuilder, GraphicsCounts, GraphicsPayload};
use crate::screen::{Clipboard, Link, MouseModes};

/// OSC strings are captured whole (titles must not truncate), but bounded:
/// a buggy or hostile stream must not grow memory without limit. No real
/// title comes anywhere near this.
const OSC_CAPTURE_MAX: usize = 64 * 1024;

/// How many `OSC 8` spans to keep, oldest evicted.
///
/// Bounded rather than unbounded because a TUI redraws: an application that
/// links five things every frame would otherwise grow this forever. Sixty-four
/// holds many screens' worth of links, so the current frame's are always
/// present, which is what a test asserts on.
const LINK_HISTORY: usize = 64;

/// How many label bytes one span may accumulate.
///
/// This is the bound that stops an *unterminated* link from bleeding into the
/// rest of the stream: without it, one missing `OSC 8 ; ; ST` makes every
/// byte the application writes afterwards part of one label. Past it the
/// label is reported as unknown rather than as a prefix — a prefix of the
/// wrong length is still a wrong answer.
const LINK_LABEL_MAX: usize = 4 * 1024;

/// Decode standard base64 (`OSC 52` payloads). `None` for anything that is
/// not valid: an out-of-alphabet byte, a bad length, or padding in the
/// wrong place. Returning `None` rather than a best effort is the point —
/// a partially decoded clipboard would be indistinguishable from a
/// correct one, and a test asserting on it would pass while proving
/// nothing.
pub(crate) fn decode_base64(input: &[u8]) -> Option<Vec<u8>> {
    fn value(b: u8) -> Option<u32> {
        match b {
            b'A'..=b'Z' => Some(u32::from(b - b'A')),
            b'a'..=b'z' => Some(u32::from(b - b'a') + 26),
            b'0'..=b'9' => Some(u32::from(b - b'0') + 52),
            b'+' => Some(62),
            b'/' => Some(63),
            _ => None,
        }
    }

    // Padding is optional in the wild but must be trailing and must not
    // exceed two bytes; what remains has to be a whole number of quanta.
    let body = input.strip_suffix(b"==").map_or_else(
        || input.strip_suffix(b"=").unwrap_or(input),
        |stripped| stripped,
    );
    let pad = input.len() - body.len();
    if pad > 0 && input.len() % 4 != 0 {
        return None;
    }
    if body.len() % 4 == 1 {
        return None; // one leftover character encodes nothing
    }

    let mut out = Vec::with_capacity(body.len() / 4 * 3 + 2);
    for quantum in body.chunks(4) {
        let mut bits = 0u32;
        for &b in quantum {
            bits = (bits << 6) | value(b)?;
        }
        // A short final quantum carries 1 or 2 bytes; shift it up to a
        // full 24-bit group and keep only the bytes it actually encodes.
        let carried = match quantum.len() {
            4 => 3,
            3 => 2,
            _ => 1,
        };
        bits <<= 6 * (4 - quantum.len());
        for i in 0..carried {
            #[allow(clippy::cast_possible_truncation)]
            out.push((bits >> (16 - 8 * i)) as u8);
        }
    }
    Some(out)
}

/// Columns between the tab stops a terminal powers on with. Eight is the
/// value every terminfo, every shell and vt100's own hardcoded `col_tab` is
/// written against.
const TAB_INTERVAL: u16 = 8;

/// Whether the power-on layout has a stop at `col`.
///
/// Column 0 is one of them, as it is in xterm's `TabReset` and alacritty's
/// `TabStops::new`. Forward motion scans strictly right of the cursor and so
/// can never land there; it matters only to `CBT`, which would clamp to 0
/// anyway. Keeping it makes the set the plain "every eighth column" the
/// resize rule extends, with no column that has to be special-cased.
fn default_stop(col: u16) -> bool {
    col % TAB_INTERVAL == 0
}

/// Where the tab stops are: one flag per column, `cols` wide.
///
/// The whole set lives in the tracker because vt100 holds no tab state at
/// all — its `HT` is a fixed eight — so there is nothing here to keep in
/// step with the backend, only a column to hand back to it.
#[derive(Debug)]
struct TabStops {
    stops: Vec<bool>,
}

impl TabStops {
    fn new(cols: u16) -> Self {
        Self {
            stops: (0..cols).map(default_stop).collect(),
        }
    }

    /// The rightmost column, which every motion clamps to.
    ///
    /// Zero for an empty set, which makes both motions no-ops rather than
    /// panics; the builder floors a terminal at two columns, so an empty set
    /// only ever arises in a unit test.
    fn last_column(&self) -> u16 {
        u16::try_from(self.stops.len())
            .unwrap_or(u16::MAX)
            .saturating_sub(1)
    }

    /// Grow or shrink to `cols`.
    ///
    /// **Decision:** columns the grid did not have before get the power-on
    /// every-eighth pattern, and stops inside the old width are left exactly
    /// as they were. A resize is not a reset — an application that set its
    /// own stops and then had its window widened would otherwise find them
    /// gone — and there is no better answer for territory that never
    /// existed than the layout the terminal would have powered on with.
    /// Narrowing drops the columns that no longer exist; widening again does
    /// not bring their stops back, since the set no longer holds them. This
    /// is what alacritty does, and it is the simple end of the trade.
    fn set_cols(&mut self, cols: u16) {
        let old = u16::try_from(self.stops.len()).unwrap_or(u16::MAX);
        self.stops.resize(usize::from(cols), false);
        for col in old..cols {
            self.stops[usize::from(col)] = default_stop(col);
        }
    }

    /// Back to the power-on layout, for `RIS` and `DECSTR`.
    fn reset(&mut self) {
        let cols = u16::try_from(self.stops.len()).unwrap_or(u16::MAX);
        for col in 0..cols {
            self.stops[usize::from(col)] = default_stop(col);
        }
    }

    /// `HTS`: a stop at `col`. Out-of-range columns are dropped rather than
    /// clamped — clamping would set a stop the application did not ask for.
    fn set(&mut self, col: u16) {
        if let Some(stop) = self.stops.get_mut(usize::from(col)) {
            *stop = true;
        }
    }

    /// `TBC 0`: clear the stop at `col`.
    fn clear(&mut self, col: u16) {
        if let Some(stop) = self.stops.get_mut(usize::from(col)) {
            *stop = false;
        }
    }

    /// `TBC 3`: clear every stop. Forward motion then runs to the last
    /// column and back-tab to column 0, which is what a terminal with no
    /// stops does.
    fn clear_all(&mut self) {
        self.stops.fill(false);
    }

    /// The most steps a motion can usefully take: one per column.
    fn steps_bound(&self) -> u16 {
        u16::try_from(self.stops.len()).unwrap_or(u16::MAX)
    }

    /// The column `count` stops right of `col`, or the last column if the
    /// stops run out first.
    fn forward(&self, col: u16, count: u16) -> u16 {
        let last = self.last_column();
        // vt100 reports a column past the end while a wrap is pending, and
        // clamps it in `col_tab`; clamping here keeps the rewrite agreeing
        // with the move it replaces.
        let mut at = col.min(last);
        // Every step moves at least one column, so more steps than there are
        // columns cannot move further — and `CSI 65535 I` is a parameter an
        // application is free to send.
        for _ in 0..count.min(self.steps_bound()) {
            match ((at.saturating_add(1))..=last).find(|&c| self.stops[usize::from(c)]) {
                Some(next) => at = next,
                None => return last,
            }
        }
        at
    }

    /// The column `count` stops left of `col`, or column 0 if the stops run
    /// out first.
    ///
    /// Each step goes to the nearest stop *strictly* left of where it
    /// started, which is what xterm and alacritty both do: a cursor sitting
    /// one past a stop it just tabbed to and then wrote over moves to that
    /// stop, not to the one before it.
    fn back(&self, col: u16, count: u16) -> u16 {
        let mut at = col.min(self.last_column());
        for _ in 0..count.min(self.steps_bound()) {
            match (0..at).rev().find(|&c| self.stops[usize::from(c)]) {
                Some(prev) => at = prev,
                None => return 0,
            }
        }
        at
    }
}

/// A tab-stop operation the tracker recognized but cannot carry out alone:
/// every one of them is relative to the cursor column, which lives in the
/// grid. The emulator resolves it against the position it holds.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum TabOp {
    /// `HTS` (`ESC H`): set a stop at the cursor column.
    Set,
    /// `TBC` / `TBC 0` (`CSI g`): clear the stop at the cursor column.
    ClearAtCursor,
    /// `TBC 3` (`CSI 3 g`): clear every stop.
    ClearAll,
    /// `HT` (`\t`) or `CHT` (`CSI n I`): forward `n` stops.
    Forward(u16),
    /// `CBT` (`CSI n Z`): back `n` stops. Also what an application echoing
    /// `Shift-Tab` emits on its output side.
    Back(u16),
}

/// Which glyph set a G0–G3 designation currently names.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Charset {
    /// ASCII — and every designation this crate has no table for: the
    /// alternate ROMs and the national replacement sets other than the UK
    /// one, which differ from it in a handful of positions.
    Ascii,
    /// The DEC United Kingdom set (`ESC ( A`): ASCII with `£` at `#`.
    Uk,
    /// DEC Special Graphics (`ESC ( 0`): the line-drawing set.
    DecSpecialGraphics,
}

/// What `DECSC` saves of the character-set state — see
/// [`SeqTracker::saved_charsets`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct SavedCharsets {
    g0: Charset,
    g1: Charset,
    g2: Charset,
    g3: Charset,
    shifted_out: bool,
}

/// The glyph a byte draws in DEC Special Graphics, where it differs from
/// ASCII: the 32 bytes `0x5f..=0x7e`. Everything below `_` draws as itself.
/// The mapping is xterm's, which is also what every terminfo `acsc` string
/// is written against.
fn dec_special_graphics(b: u8) -> Option<&'static str> {
    Some(match b {
        b'_' => " ",        // blank
        b'`' => "\u{25c6}", // ◆ diamond
        b'a' => "\u{2592}", // ▒ checkerboard
        b'b' => "\u{2409}", // ␉ HT
        b'c' => "\u{240c}", // ␌ FF
        b'd' => "\u{240d}", // ␍ CR
        b'e' => "\u{240a}", // ␊ LF
        b'f' => "\u{b0}",   // ° degree
        b'g' => "\u{b1}",   // ± plus-minus
        b'h' => "\u{2424}", // ␤ NL
        b'i' => "\u{240b}", // ␋ VT
        b'j' => "\u{2518}", //        b'k' => "\u{2510}", //        b'l' => "\u{250c}", //        b'm' => "\u{2514}", //        b'n' => "\u{253c}", //        b'o' => "\u{23ba}", // ⎺ scan line 1
        b'p' => "\u{23bb}", // ⎻ scan line 3
        b'q' => "\u{2500}", // ─ scan line 5
        b'r' => "\u{23bc}", // ⎼ scan line 7
        b's' => "\u{23bd}", // ⎽ scan line 9
        b't' => "\u{251c}", //        b'u' => "\u{2524}", //        b'v' => "\u{2534}", //        b'w' => "\u{252c}", //        b'x' => "\u{2502}", //        b'y' => "\u{2264}", //        b'z' => "\u{2265}", //        b'{' => "\u{3c0}",  // π
        b'|' => "\u{2260}", //        b'}' => "\u{a3}",   // £
        b'~' => "\u{b7}",   // · bullet
        _ => return None,
    })
}

/// SS2/SS3 invoke G2/G3 for exactly one character, then the locking
/// shift resumes. Stored as which *slot* to read, not a copy of the set:
/// a designation between the shift and the character still applies.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SingleShift {
    G2,
    G3,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum State {
    /// Plain text.
    Ground,
    /// Got ESC, awaiting the introducer or final byte.
    Esc,
    /// Inside `ESC <intermediate 0x20-0x2F>…`, awaiting a final byte.
    EscIntermediate,
    /// Inside a CSI sequence (`ESC [ …`), awaiting a final byte 0x40–0x7E.
    Csi,
    /// Inside an OSC string (`ESC ] …`), terminated by BEL or ST.
    Osc,
    /// Inside a DCS/SOS/PM/APC string, terminated by ST only.
    Dcs,
    /// Inside an OSC string and just saw ESC (potential `ESC \` = ST).
    OscEsc,
    /// Inside a DCS-class string and just saw ESC (potential ST).
    DcsEsc,
}

/// What one byte completed, if anything.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum SeqEvent {
    /// Nothing actionable.
    None,
    /// A `CSI ? 2026 … h` completed: a synchronized update began.
    SyncBegin,
    /// A `CSI ? 2026 … l` completed: a frame is now complete.
    SyncEnd,
    /// `DECSTR` (`CSI ! p`) completed: the tracker has already returned
    /// its own state to the defaults; the emulator must do the same for
    /// the modes it holds.
    SoftReset,
    /// The application asked the terminal a question.
    Query(Query),
    /// An inline graphics payload completed. Carried out of the tracker
    /// rather than stored in it because the placement — where the cursor
    /// stood — is a fact about the grid, which only the emulator holds.
    Graphics(Box<GraphicsPayload>),
    /// A tab-stop operation completed, and needs the cursor column to
    /// finish — carried out for the same reason a graphics placement is.
    Tabs(TabOp),
}

/// A terminal query the application issued. The tracker classifies;
/// policy (answer vs record) lives with the caller.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Query {
    /// DSR cursor position: `CSI 6 n` (or the DEC `CSI ? 6 n` form).
    CursorPosition {
        /// True for the `?`-prefixed DECXCPR form.
        private: bool,
    },
    /// DSR operating status: `CSI 5 n`.
    OperatingStatus,
    /// Primary device attributes: `CSI c` / `CSI 0 c`.
    PrimaryDa,
    /// Secondary device attributes: `CSI > c` / `CSI > 0 c`.
    SecondaryDa,
    /// Text-area size in characters: `CSI 18 t`.
    TextAreaSize,
    /// OSC color query (`OSC 10;?` foreground / `OSC 11;?` background).
    OscColor {
        /// 10 = foreground, 11 = background.
        code: u8,
        /// True when the query used ST; the reply must mirror it.
        st_terminated: bool,
    },
    /// DECRQM: "is private mode `n` set?" — `CSI ? n $ p`. Answering
    /// this truthfully lets an application that *probes* before using a
    /// mode (synchronized output above all) turn it on against termlens.
    RequestMode(u32),
    /// Window size in pixels: `CSI 14 t`.
    WindowSizePixels,
    /// Character cell size in pixels: `CSI 16 t`.
    CellSizePixels,
    /// The kitty graphics capability probe (`APC _G … a=q … ST`), carrying
    /// the image id it named so a reply can echo it back.
    ///
    /// Classified rather than refused outright: whether it is answerable
    /// depends on what the test declared the terminal supports, and that is
    /// policy, which lives with the caller.
    KittyGraphics {
        /// The `i=` value, if the probe gave one.
        id: Option<u32>,
        /// Printable rendering, for the timeout note when unanswered.
        shape: String,
    },
    /// XTGETTCAP: "what is capability `name`?" — `DCS + q <hex names> ST`,
    /// carrying the hex-encoded names exactly as asked, since the reply must
    /// echo each one back.
    RequestTermcap {
        /// Hex-encoded names, `;`-separated, as the application wrote them.
        names: String,
        /// Printable rendering, for the timeout note when unanswered.
        shape: String,
    },
    /// Recognized as a question, but one termlens has no answer for
    /// (XTGETTCAP, kitty `CSI ? u`, DECRQSS, `OSC 4`/`OSC 52`, other
    /// DSR/DA/XTWINOPS reports, …). Carries a printable rendering for
    /// diagnostics.
    Unanswerable(String),
}

/// The numeric value of `key` in a kitty control block (`i=3,a=q`), if it
/// carries one. Keys are comma-separated `name=value` pairs.
fn kitty_key(control: &[u8], key: &[u8]) -> Option<u32> {
    control
        .split(|&b| b == b',')
        .find_map(|pair| pair.strip_prefix(key))
        .and_then(|digits| std::str::from_utf8(digits).ok())
        .and_then(|digits| digits.parse().ok())
}

/// Whether a kitty control block sets `key` to exactly `value`.
fn key_is(control: &[u8], key: &[u8], value: &[u8]) -> bool {
    control.split(|&b| b == b',').any(|pair| {
        pair.strip_prefix(key)
            .and_then(|rest| rest.strip_prefix(b"="))
            == Some(value)
    })
}

/// Render a captured escape sequence printably (`ESC` becomes `^[`).
fn printable(bytes: &[u8]) -> String {
    let mut out = String::new();
    for &b in bytes {
        match b {
            0x1b => out.push_str("^["),
            0x07 => out.push_str("^G"),
            0x20..=0x7e => out.push(b as char),
            _ => out.push_str(&format!("\\x{b:02x}")),
        }
    }
    out
}

/// The bit a DEC private mode number occupies in the tracked set of mouse
/// tracking modes, matching [`MouseModes`]'s layout; zero for any other
/// parameter, so accumulating over a whole list is one `|=` per value.
fn mouse_bit(mode: u32) -> u8 {
    match mode {
        9 => 1,
        1000 => 2,
        1002 => 4,
        1003 => 8,
        _ => 0,
    }
}

#[derive(Debug)]
pub(crate) struct SeqTracker {
    state: State,
    /// Continuation bytes still expected for the current UTF-8 character.
    utf8_remaining: u8,
    /// True between a 2026 `h` and the matching `l`.
    sync_update: bool,
    // Incremental CSI scanner: enough to recognize mode 2026 and the
    // handful of query shapes, in O(1) space.
    csi_prefix: u8,
    /// Intermediate byte seen in the current CSI (only `$` matters).
    csi_intermediate: u8,
    csi_invalid: bool,
    csi_first: bool,
    csi_param: u32,
    csi_has_digits: bool,
    csi_first_param: u32,
    csi_param_count: u8,
    csi_saw_2026: bool,
    /// Set when the current CSI's parameter list contains 1004 (focus
    /// reporting), the same trick `csi_saw_2026` uses — a mode can arrive
    /// anywhere in a multi-mode list, so scanning for it beats assuming it
    /// is the only parameter.
    csi_saw_1004: bool,
    /// Whether a completed parameter of the current CSI was `4`: insert
    /// mode, when the final byte turns out to be a plain `h` or `l`.
    csi_saw_irm: bool,
    /// The mouse tracking modes (`9`, `1000`, `1002`, `1003`) named in the
    /// current CSI's parameter list, as [`mouse_bit`]s — the same scan as
    /// `csi_saw_1004`, for a group rather than one mode.
    csi_saw_mouse: u8,
    /// Raw capture of the current sequence (from ESC), for diagnostics
    /// and DCS query recognition. Bounded; long sequences truncate.
    seq_buf: [u8; 24],
    seq_len: u8,
    /// Content bytes of the current OSC string (no `ESC ]`, no
    /// terminator), kept whole so titles never truncate.
    osc_buf: Vec<u8>,
    /// Set when the current OSC string hit [`OSC_CAPTURE_MAX`]. What was
    /// captured is then a prefix, and a prefix of base64 can still decode —
    /// to the wrong thing. Reporting the truncation is the only honest
    /// option, so it is tracked rather than inferred.
    osc_truncated: bool,
    /// The window title as most recently set via `OSC 0`/`OSC 2`; empty
    /// until the application sets one. Shared so snapshots clone for free.
    title: Arc<str>,
    /// The most recent `OSC 52` clipboard write, decoded.
    clipboard: Option<Arc<Clipboard>>,
    /// `OSC 8` spans seen, oldest first. A span is pushed when it *opens* —
    /// the URI is known then, and a test waiting for a link should not have
    /// to wait for the application to close it — and completed in place when
    /// it closes.
    links: Arc<Vec<Link>>,
    /// Label bytes of the span currently open. Held outside `links` so the
    /// shared vector is touched twice per span (open, close) rather than
    /// once per character written.
    link_label: Vec<u8>,
    /// True while a span is open, so printable bytes know where to go.
    link_open: bool,
    /// Set when the open span's label passed [`LINK_LABEL_MAX`].
    link_label_truncated: bool,
    /// Bells rung in ground state. A `BEL` closing an OSC string is a
    /// terminator and one inside a DCS-class string is payload; neither is
    /// a bell, and both are handled by the state machine rather than here.
    bells: u64,
    /// Inline graphics transmitted, counted as images rather than as
    /// escapes: [`GraphicsBuilder`] joins a chunked kitty transmission
    /// before either is incremented.
    counts: GraphicsCounts,
    /// The payload being assembled, if a kitty transmission is mid-chunk.
    building: GraphicsBuilder,
    /// How many payload bytes may be kept for inspection. Counting is
    /// unaffected by it; only the data is dropped.
    capture: usize,
    /// Printable characters written since the current frame began. Reset by
    /// the Begin, read by the End — so it measures what one repaint drew,
    /// which is the other half of "did this repaint get more expensive?".
    frame_printable: u32,
    /// True while the application has focus reporting (mode 1004) enabled.
    /// Tracked here because vt100 does not model 1004 at all — the same
    /// reason the window title is tracked here.
    focus_events: bool,
    /// The mouse tracking modes the application has enabled and not yet
    /// disabled, as [`mouse_bit`]s. vt100 collapses the four into the one
    /// protocol it would report in — correct for the input path, since a
    /// terminal reports in one protocol — which cannot say which members
    /// of the group were asked for; crossterm asks for three at once. The
    /// set is kept here so `DECRQM` can answer each mode on its own
    /// evidence and a snapshot can report what was requested (#151).
    mouse_tracking: u8,
    /// The raw `DECSCUSR` parameter the application last asked for, or
    /// `None` while it has never asked. Kept as the parameter rather than
    /// as a decoded shape so the one place that knows what `5` means is
    /// the accessor on `Screen`, and "never asked" stays distinguishable
    /// from every value it could have asked for.
    cursor_style: Option<u8>,
    /// The intermediate byte of the current `ESC <intermediate> <final>`
    /// sequence — `(` `)` `*` `+` for a G0–G3 designation — so the final
    /// byte knows which set it designates. Zero once a second intermediate
    /// makes it something else.
    esc_intermediate: u8,
    /// What `ESC ( ) * + Ps` last designated into G0–G3.
    g0: Charset,
    g1: Charset,
    g2: Charset,
    g3: Charset,
    /// True after `SO` (`0x0e`) invoked G1; `SI` (`0x0f`) returns to G0.
    /// Single shifts override this for one character without changing it.
    shifted_out: bool,
    /// Pending SS2/SS3, if any. Cleared by the next character, or by RIS;
    /// an intervening control or designation must not consume it, or a
    /// mixed line that shifts then redraws would lose the graphic.
    single_shift: Option<SingleShift>,
    /// The charset half of the state `DECSC` (`ESC 7`) saves: G0–G3 and
    /// which of G0/G1 is locked in. `DECRC` (`ESC 8`) restores it; with
    /// nothing saved it restores the power-on defaults, as xterm does. vt100
    /// saves and restores the cursor and attributes itself, so only the
    /// half it does not know about lives here. `None` after RIS, or a
    /// restore after a reset would resurrect a designation from before it.
    saved_charsets: Option<SavedCharsets>,
    /// Which introducer opened the current DCS-class string: `P` (DCS),
    /// `X` (SOS), `^` (PM) or `_` (APC). Sixel and kitty graphics differ
    /// only by this, so consuming all four alike — which is all the tracker
    /// needed before — cannot tell them apart.
    dcs_introducer: u8,
    /// Final byte of the current DCS header, 0 until seen. Sixel's is `q`
    /// with no intermediate; XTGETTCAP and DECRQSS reach `q` through `+`
    /// and `$`, which is what keeps them from being counted as pictures.
    dcs_final: u8,
    /// Intermediate byte in the current DCS header (`+` or `$` in practice).
    dcs_intermediate: u8,
    /// Payload bytes after the header, so a payload's size is reportable
    /// without keeping the payload.
    dcs_data_len: u64,
    /// The opening bytes of a DCS-class payload: enough for a kitty control
    /// block (`G` plus `key=value` pairs up to the first `;`) and for an
    /// XTGETTCAP name list, whose hex names run about six bytes each. A
    /// longer list truncates, and the names that survive are still answered
    /// — a partial answer beats none, and the ones we drop get no reply,
    /// which is what an application already has to handle.
    dcs_head: [u8; 128],
    dcs_head_len: u8,
    /// Every byte of the current DCS-class string, up to the capture bound —
    /// the image data itself, which the 128-byte head deliberately is not.
    /// Kept only while the bound allows; `dcs_body_full` says whether it is
    /// the whole payload or the start of one.
    dcs_body: Vec<u8>,
    dcs_body_full: bool,
    /// Where the tab stops are. Sized to the grid, so `set_cols` follows
    /// every resize.
    tabs: TabStops,
    /// `IRM` (`CSI 4 h`) is set — see [`insert_mode`](Self::insert_mode).
    insert_mode: bool,
}

impl SeqTracker {
    /// `cols` sizes the tab-stop set; everything else here is width-agnostic.
    pub(crate) fn new(capture: usize, cols: u16) -> Self {
        Self {
            state: State::Ground,
            utf8_remaining: 0,
            sync_update: false,
            csi_prefix: 0,
            csi_intermediate: 0,
            csi_invalid: false,
            csi_first: true,
            csi_param: 0,
            csi_has_digits: false,
            csi_first_param: 0,
            csi_param_count: 0,
            csi_saw_2026: false,
            csi_saw_1004: false,
            csi_saw_irm: false,
            csi_saw_mouse: 0,
            seq_buf: [0; 24],
            seq_len: 0,
            osc_buf: Vec::new(),
            osc_truncated: false,
            title: Arc::from(""),
            clipboard: None,
            links: Arc::new(Vec::new()),
            link_label: Vec::new(),
            link_open: false,
            link_label_truncated: false,
            bells: 0,
            counts: GraphicsCounts::default(),
            building: GraphicsBuilder::default(),
            capture,
            frame_printable: 0,
            focus_events: false,
            mouse_tracking: 0,
            cursor_style: None,
            esc_intermediate: 0,
            g0: Charset::Ascii,
            g1: Charset::Ascii,
            g2: Charset::Ascii,
            g3: Charset::Ascii,
            shifted_out: false,
            single_shift: None,
            saved_charsets: None,
            dcs_introducer: 0,
            dcs_final: 0,
            dcs_intermediate: 0,
            dcs_data_len: 0,
            dcs_head: [0; 128],
            dcs_head_len: 0,
            dcs_body: Vec::new(),
            dcs_body_full: true,
            tabs: TabStops::new(cols),
            insert_mode: false,
        }
    }

    /// Resize the tab-stop set with the grid. See [`TabStops::set_cols`] for
    /// what happens to the columns on either side of the change.
    pub(crate) fn set_cols(&mut self, cols: u16) {
        self.tabs.set_cols(cols);
    }

    /// Carry out a [`TabOp`] at cursor column `col`, returning the column the
    /// cursor must move to when the operation is a motion and `None` when it
    /// only edits the set.
    pub(crate) fn tab_op(&mut self, op: TabOp, col: u16) -> Option<u16> {
        match op {
            TabOp::Set => {
                self.tabs.set(col);
                None
            }
            TabOp::ClearAtCursor => {
                self.tabs.clear(col);
                None
            }
            TabOp::ClearAll => {
                self.tabs.clear_all();
                None
            }
            TabOp::Forward(count) => Some(self.tabs.forward(col, count)),
            TabOp::Back(count) => Some(self.tabs.back(col, count)),
        }
    }

    #[cfg(test)]
    pub(crate) fn feed(&mut self, bytes: &[u8]) {
        for &b in bytes {
            self.step(b);
        }
    }

    pub(crate) fn mid_sequence(&self) -> bool {
        self.state != State::Ground || self.utf8_remaining > 0
    }

    /// True while the stream is inside a DEC 2026 synchronized update.
    pub(crate) fn in_sync_update(&self) -> bool {
        self.sync_update
    }

    /// The most recent `OSC 52` clipboard write, or `None` if the
    /// application has not copied anything.
    pub(crate) fn clipboard(&self) -> Option<Arc<Clipboard>> {
        self.clipboard.clone()
    }

    /// The window title as most recently set via `OSC 0`/`OSC 2` (empty
    /// until the application sets one).
    pub(crate) fn title(&self) -> Arc<str> {
        Arc::clone(&self.title)
    }

    /// Bells rung in ground state so far.
    pub(crate) fn bells(&self) -> u64 {
        self.bells
    }

    /// The `OSC 8` hyperlinks seen so far, oldest first.
    pub(crate) fn links(&self) -> Arc<Vec<Link>> {
        Arc::clone(&self.links)
    }

    /// Begin an `OSC 8` span. Any span still open is closed first: a new
    /// URI supersedes the current one in a real terminal, so treating it as
    /// nested would attribute the new label to the old target.
    fn open_link(&mut self, params: &[u8], uri: &[u8]) {
        self.close_link();
        // `id=` is the one standard parameter; the list is `:`-separated.
        let id = params
            .split(|&b| b == b':')
            .find_map(|pair| pair.strip_prefix(b"id="))
            .map(String::from_utf8_lossy);
        // Borrowed where the bytes are valid UTF-8, which is the normal case:
        // `Link::open` copies into an `Arc<str>` either way, so owning here
        // first would allocate twice for one span.
        let uri = String::from_utf8_lossy(uri);
        let links = Arc::make_mut(&mut self.links);
        links.push(Link::open(&uri, id.as_deref()));
        while links.len() > LINK_HISTORY {
            links.remove(0);
        }
        self.link_open = true;
        self.link_label.clear();
        self.link_label_truncated = false;
    }

    /// Close the open `OSC 8` span, if any, recording the text it wrapped.
    fn close_link(&mut self) {
        if !self.link_open {
            return;
        }
        self.link_open = false;
        let raw = std::mem::take(&mut self.link_label);
        let label = if self.link_label_truncated {
            None
        } else {
            // Invalid UTF-8 is refused rather than replaced: a label with
            // U+FFFD in it is not the text the user sees.
            String::from_utf8(raw).ok()
        };
        self.link_label_truncated = false;
        // The open span is the newest, and eviction only ever drops the
        // oldest, so the one to complete is the last.
        if let Some(link) = Arc::make_mut(&mut self.links).last_mut() {
            link.close(label);
        }
    }

    /// Inline graphics counted so far.
    pub(crate) fn graphics(&self) -> GraphicsCounts {
        self.counts
    }

    /// True while the application has focus reporting (mode 1004) enabled.
    pub(crate) fn focus_events(&self) -> bool {
        self.focus_events
    }

    /// The mouse tracking modes the application has enabled and not yet
    /// disabled — the requested set, not the one protocol vt100 reports in.
    pub(crate) fn mouse_tracking(&self) -> MouseModes {
        MouseModes::from_bits(self.mouse_tracking)
    }

    /// The raw `DECSCUSR` parameter last requested, `None` if never.
    pub(crate) fn cursor_style(&self) -> Option<u8> {
        self.cursor_style
    }

    /// Printable characters written since the current frame began, cleared
    /// for the next one.
    pub(crate) fn take_frame_printable(&mut self) -> u32 {
        std::mem::replace(&mut self.frame_printable, 0)
    }

    /// The glyph `b` draws in the invoked character set, when that set
    /// redefines `b` — the 32 bytes DEC Special Graphics redraws, or `#` in
    /// the UK set — or `None` when the byte draws as itself, or is not a
    /// character at all.
    ///
    /// Consulted **before** the byte is stepped: whether a byte is a
    /// character depends on the state the tracker is in before it, and the
    /// designation's own final byte must not be translated. A pending
    /// single shift is read here and consumed in `transition` when the
    /// character is processed, so a second look (the open-link label) still
    /// sees the same set.
    pub(crate) fn charset_glyph(&self, b: u8) -> Option<&'static str> {
        if self.state != State::Ground {
            return None;
        }
        match self.invoked_charset() {
            Charset::Ascii => None,
            Charset::Uk => (b == b'#').then_some("\u{a3}"),
            Charset::DecSpecialGraphics => dec_special_graphics(b),
        }
    }

    fn invoked_charset(&self) -> Charset {
        match self.single_shift {
            Some(SingleShift::G2) => self.g2,
            Some(SingleShift::G3) => self.g3,
            None => {
                if self.shifted_out {
                    self.g1
                } else {
                    self.g0
                }
            }
        }
    }

    /// Every set back to ASCII with G0 invoked and no single shift pending:
    /// the power-on charset state, which RIS returns to and which `DECRC`
    /// with nothing saved restores.
    fn reset_charsets(&mut self) {
        self.g0 = Charset::Ascii;
        self.g1 = Charset::Ascii;
        self.g2 = Charset::Ascii;
        self.g3 = Charset::Ascii;
        self.shifted_out = false;
        self.single_shift = None;
    }

    /// The tracker's half of `DECSTR`: the character sets and the `DECSC`
    /// slot back to power-on, the cursor shape back to the terminal's
    /// default, focus reporting off. The window title, the clipboard, the
    /// bell count and the link log stay, for the same reason they survive
    /// `RIS`: they are records of what the application emitted, not modes
    /// the terminal holds. An open link span stays open too — a soft reset
    /// clears no screen, so the text after it is still the span's text.
    fn soft_reset(&mut self) {
        self.reset_charsets();
        self.saved_charsets = None;
        self.cursor_style = None;
        self.focus_events = false;
        self.mouse_tracking = 0;
        self.insert_mode = false;
        self.tabs.reset();
    }

    /// Whether `IRM` (`CSI 4 h`) is set: a printable byte pushes the rest
    /// of the row right instead of overwriting the cell under the cursor.
    /// vt100 does not model the mode, so the emulator reserves the room
    /// with an `ICH` it does dispatch (#261).
    pub(crate) fn insert_mode(&self) -> bool {
        self.insert_mode
    }

    /// Apply the final byte of an `ESC ( ) * + Ps` designation.
    ///
    /// `0` is DEC Special Graphics and `A` the United Kingdom set, whose one
    /// difference from ASCII is `£` at `#`. Everything else — `B` (ASCII),
    /// the alternate-ROM sets `1` and `2`, the other national sets — reads
    /// as ASCII: a designation acknowledged and left untranslated, which is
    /// close enough for every one of them that guessing at the odd position
    /// would be a worse answer than the plain one.
    fn designate(&mut self, final_byte: u8) {
        let set = match final_byte {
            b'0' => Charset::DecSpecialGraphics,
            b'A' => Charset::Uk,
            _ => Charset::Ascii,
        };
        match self.esc_intermediate {
            b'(' => self.g0 = set,
            b')' => self.g1 = set,
            b'*' => self.g2 = set,
            b'+' => self.g3 = set,
            _ => {}
        }
    }

    fn reset_dcs_scanner(&mut self, introducer: u8) {
        self.dcs_introducer = introducer;
        self.dcs_final = 0;
        self.dcs_intermediate = 0;
        self.dcs_data_len = 0;
        self.dcs_head_len = 0;
        self.dcs_body.clear();
        self.dcs_body_full = true;
    }

    fn reset_csi_scanner(&mut self) {
        self.csi_prefix = 0;
        self.csi_intermediate = 0;
        self.csi_invalid = false;
        self.csi_first = true;
        self.csi_param = 0;
        self.csi_has_digits = false;
        self.csi_first_param = 0;
        self.csi_param_count = 0;
        self.csi_saw_2026 = false;
        self.csi_saw_1004 = false;
        self.csi_saw_irm = false;
        self.csi_saw_mouse = 0;
    }

    fn push_seq(&mut self, b: u8) {
        if usize::from(self.seq_len) < self.seq_buf.len() {
            self.seq_buf[usize::from(self.seq_len)] = b;
            self.seq_len += 1;
        }
    }

    fn push_osc(&mut self, b: u8) {
        if self.osc_buf.len() < OSC_CAPTURE_MAX {
            self.osc_buf.push(b);
        } else {
            self.osc_truncated = true;
        }
    }

    fn seq_printable(&self) -> String {
        printable(&self.seq_buf[..usize::from(self.seq_len)])
    }

    /// Close the parameter currently being accumulated.
    fn end_csi_param(&mut self) {
        if self.csi_param == 2026 {
            self.csi_saw_2026 = true;
        }
        if self.csi_param == 1004 {
            self.csi_saw_1004 = true;
        }
        if self.csi_param == 4 {
            self.csi_saw_irm = true;
        }
        self.csi_saw_mouse |= mouse_bit(self.csi_param);
        if self.csi_param_count == 0 {
            self.csi_first_param = self.csi_param;
        }
        self.csi_param_count = self.csi_param_count.saturating_add(1);
        self.csi_param = 0;
        self.csi_has_digits = false;
    }

    /// Track one CSI parameter/intermediate byte.
    fn scan_csi_byte(&mut self, b: u8) {
        match b {
            b'?' | b'>' | b'=' if self.csi_first => self.csi_prefix = b,
            b'0'..=b'9' => {
                self.csi_param = self
                    .csi_param
                    .saturating_mul(10)
                    .saturating_add(u32::from(b - b'0'));
                self.csi_has_digits = true;
            }
            b';' => self.end_csi_param(),
            // `$` is the intermediate of the DECRQM request (`CSI ? n $ p`),
            // `SP` of DECSCUSR (`CSI Ps SP q`) and `!` of DECSTR
            // (`CSI ! p`); recording them keeps those sequences
            // classifiable instead of discarding them as unrecognized.
            b'$' | b' ' | b'!' => self.csi_intermediate = b,
            // Sub-parameters or other intermediates: none of the sequences
            // we recognize use them.
            _ => self.csi_invalid = true,
        }
        self.csi_first = false;
    }

    /// The event (if any) implied by a CSI final byte.
    fn csi_final(&mut self, b: u8) -> SeqEvent {
        if self.csi_invalid {
            return SeqEvent::None;
        }
        if self.csi_has_digits {
            self.end_csi_param();
        }
        let params_empty = self.csi_param_count == 0;
        let single = |v: u32| self.csi_param_count == 1 && self.csi_first_param == v;

        // DECRQM (`CSI ? n $ p`) and DECRQSS-adjacent `$`-intermediate
        // requests. Handled before the plain-CSI table below, which
        // assumes no intermediate.
        if self.csi_intermediate == b'$' {
            return match (self.csi_prefix, b) {
                (b'?', b'p') if self.csi_param_count == 1 => {
                    SeqEvent::Query(Query::RequestMode(self.csi_first_param))
                }
                // ANSI-mode DECRQM and mode *reports* we cannot answer.
                (_, b'p' | b'y') => SeqEvent::Query(Query::Unanswerable(self.seq_printable())),
                _ => SeqEvent::None,
            };
        }

        // DECSTR (`CSI ! p`), the soft reset: what a well-behaved TUI sends
        // on startup and teardown for a known-good terminal without the
        // screen clear RIS brings. The spec's list is long; the modes this
        // crate holds are returned to their defaults here, and the emulator
        // is told to do the same for the ones it holds (#233).
        if self.csi_intermediate == b'!' {
            if b == b'p' && self.csi_prefix == 0 && params_empty {
                self.soft_reset();
                return SeqEvent::SoftReset;
            }
            return SeqEvent::None;
        }

        // DECSCUSR (`CSI Ps SP q`): the shape of the cursor, and whether it
        // blinks. vt100 models neither, so a modal editor switching to a bar
        // for insert mode is invisible without this — as is the program that
        // switches and never switches back, which leaves the user's terminal
        // wrong after exit.
        //
        // Also reached by the other `SP`-intermediate sequences (SL, SR).
        // They are not ours to act on, and returning here keeps them out of
        // the plain-CSI table below, which assumes no intermediate — exactly
        // as they were kept out by `csi_invalid` before `SP` was accepted.
        if self.csi_intermediate == b' ' {
            if b == b'q' && self.csi_prefix == 0 && self.csi_param_count <= 1 {
                // An omitted parameter means 0. Values above 6 are undefined
                // and xterm ignores them; so do we, leaving the last style
                // the application actually asked for rather than inventing
                // one it did not.
                let ps = if self.csi_param_count == 0 {
                    0
                } else {
                    self.csi_first_param
                };
                if let Ok(style @ 0..=6) = u8::try_from(ps) {
                    self.cursor_style = Some(style);
                }
            }
            return SeqEvent::None;
        }

        // DEC private mode 1004 (focus reporting). vt100 does not model it,
        // so an application that enables it is invisible without this — and
        // `focus_in`/`focus_out` refuse to send events the application never
        // asked for, exactly as `click` refuses without mouse tracking.
        if self.csi_prefix == b'?' && self.csi_saw_1004 {
            match b {
                b'h' => self.focus_events = true,
                b'l' => self.focus_events = false,
                _ => {}
            }
        }

        // The mouse tracking modes, kept as the set the application asked
        // for — see `mouse_tracking`. Every mode named in one list is set
        // or cleared together, which is how they arrive.
        if self.csi_prefix == b'?' && self.csi_saw_mouse != 0 {
            match b {
                b'h' => self.mouse_tracking |= self.csi_saw_mouse,
                b'l' => self.mouse_tracking &= !self.csi_saw_mouse,
                _ => {}
            }
        }

        // DEC private mode 2026 (synchronized output).
        if self.csi_prefix == b'?' && self.csi_saw_2026 {
            match b {
                b'h' => {
                    self.sync_update = true;
                    self.frame_printable = 0;
                    return SeqEvent::SyncBegin;
                }
                // Only an End that closes a Begin we saw ends a frame.
                // An unmatched End is ordinary application behaviour, not a
                // malformed stream: programs defensively reset terminal
                // modes at startup and on crash, and such a reset string
                // naturally contains `?2026l`. Treating it as a frame would
                // manufacture one out of whatever happened to be on the
                // grid — and, worse, push `frames_seen` off zero, which is
                // what gates the "never emitted a synchronized update"
                // diagnosis. Silently not ending a frame is the whole
                // correct response.
                b'l' if self.sync_update => {
                    self.sync_update = false;
                    return SeqEvent::SyncEnd;
                }
                _ => {}
            }
        }

        // Insert mode (`IRM`, ANSI mode 4): `smir`/`rmir` in the terminfo
        // entry every child is handed, and the mode ncurses uses for
        // `insch`. vt100 dispatches no ANSI mode at all, so the flag lives
        // here and the emulator acts on it (#261). Any mode list naming 4
        // counts, as it does for the private modes above.
        if self.csi_prefix == 0 && self.csi_saw_irm {
            match b {
                b'h' => self.insert_mode = true,
                b'l' => self.insert_mode = false,
                _ => {}
            }
        }

        // Tab stops: `TBC` (`CSI g`), `CHT` (`CSI n I`) and `CBT`
        // (`CSI n Z`). All three are relative to the cursor column, so they
        // leave as requests rather than as changes.
        if self.csi_prefix == 0 {
            // An omitted parameter is 0, and a 0 count means 1 — vt100's own
            // `canonicalize_params_1`, so a rewritten move and the move it
            // replaces read their parameter the same way.
            let ps = if params_empty {
                0
            } else {
                self.csi_first_param
            };
            let count = u16::try_from(ps).unwrap_or(u16::MAX).max(1);
            match b {
                // Only `0` (this column) and `3` (all) are modelled. The
                // rest of the family clears *line* tab stops, which this
                // crate has no notion of; ignoring them beats inventing one.
                b'g' if self.csi_param_count <= 1 => {
                    return match ps {
                        0 => SeqEvent::Tabs(TabOp::ClearAtCursor),
                        3 => SeqEvent::Tabs(TabOp::ClearAll),
                        _ => SeqEvent::None,
                    };
                }
                b'I' if self.csi_param_count <= 1 => {
                    return SeqEvent::Tabs(TabOp::Forward(count));
                }
                b'Z' if self.csi_param_count <= 1 => {
                    return SeqEvent::Tabs(TabOp::Back(count));
                }
                _ => {}
            }
        }

        // Queries. Classification only — answering policy lives upstream.
        let query = match (self.csi_prefix, b) {
            (0, b'n') if single(6) => Some(Query::CursorPosition { private: false }),
            (b'?', b'n') if single(6) => Some(Query::CursorPosition { private: true }),
            (0, b'n') if single(5) => Some(Query::OperatingStatus),
            (0, b'c') if params_empty || single(0) => Some(Query::PrimaryDa),
            (b'>', b'c') if params_empty || single(0) => Some(Query::SecondaryDa),
            (0, b't') if single(18) => Some(Query::TextAreaSize),
            // Pixel geometry. Arithmetic, not rendering: answering claims
            // nothing the emulator cannot do, and DA1 goes on declining
            // graphics either way.
            (0, b't') if single(14) => Some(Query::WindowSizePixels),
            (0, b't') if single(16) => Some(Query::CellSizePixels),
            // Questions we can recognize but not answer.
            (_, b'n') | (b'=', b'c') => Some(Query::Unanswerable(self.seq_printable())),
            (b'?', b'u') if params_empty => {
                // kitty keyboard probe. Its protocol pairs this with DA1;
                // our DA1 answer unblocks the probe like any non-kitty
                // terminal, but the probe itself is still unanswered.
                Some(Query::Unanswerable(self.seq_printable()))
            }
            (0, b't')
                if matches!(self.csi_first_param, 11 | 13 | 19 | 20 | 21)
                    && self.csi_param_count == 1 =>
            {
                Some(Query::Unanswerable(self.seq_printable()))
            }
            _ => None,
        };
        query.map_or(SeqEvent::None, SeqEvent::Query)
    }

    /// The event (if any) implied by a completed OSC or DCS string.
    fn string_final(&mut self, was_osc: bool, st_terminated: bool) -> SeqEvent {
        if was_osc {
            // `osc_buf` holds exactly the content (`ESC ]` and terminator
            // stripped). A color query is exactly `10;?` or `11;?`
            // (12 = cursor color: unanswerable).
            match self.osc_buf.as_slice() {
                b"10;?" => {
                    return SeqEvent::Query(Query::OscColor {
                        code: 10,
                        st_terminated,
                    })
                }
                b"11;?" => {
                    return SeqEvent::Query(Query::OscColor {
                        code: 11,
                        st_terminated,
                    })
                }
                b"12;?" => return SeqEvent::Query(Query::Unanswerable(self.seq_printable())),
                content
                    if content.ends_with(b"?")
                        && (content.starts_with(b"4;") || content.starts_with(b"52;")) =>
                {
                    // Palette queries (`OSC 4;n;?`) and clipboard reads
                    // (`OSC 52;…;?`), recognized so a blocked application
                    // is diagnosed rather than left silently hanging. The
                    // `?` matters: both codes also *set* — a palette
                    // colour, or the clipboard from base64 — and a set is
                    // not a question.
                    return SeqEvent::Query(Query::Unanswerable(self.seq_printable()));
                }
                content => {
                    // OSC 0 (icon + title) / OSC 2 (title) set the window
                    // title — state the vt100 backend does not track.
                    // OSC 1 (icon only) is deliberately ignored.
                    if let Some(title) = content
                        .strip_prefix(b"0;")
                        .or_else(|| content.strip_prefix(b"2;"))
                    {
                        self.title = Arc::from(String::from_utf8_lossy(title));
                    } else if let Some(rest) = content.strip_prefix(b"8;") {
                        // `OSC 8 ; params ; URI` opens a hyperlink span and
                        // `OSC 8 ; ; ` closes it. Captured rather than
                        // answered, exactly as OSC 52 is below: the label
                        // renders as ordinary text, so the URL exists
                        // nowhere else and "did it link the right place?"
                        // is otherwise unanswerable.
                        //
                        // Parameters cannot contain `;`, so the first one
                        // ends them and everything after is the URI —
                        // which may itself contain `;` in a query string.
                        // No separator at all is malformed, and a malformed
                        // sequence is not a close: silently ending the span
                        // would attribute the text after it to nothing.
                        if let Some(sep) = rest.iter().position(|&b| b == b';') {
                            // A truncated OSC cannot be acted on in either
                            // direction: the URI we hold is a prefix, and
                            // opening a span on it would record a link the
                            // application never emitted.
                            if !self.osc_truncated {
                                // Owned before the call: both helpers take
                                // `&mut self`, and these slices point into
                                // `osc_buf`, which is part of it.
                                let params = rest[..sep].to_vec();
                                let uri = rest[sep + 1..].to_vec();
                                if uri.is_empty() {
                                    self.close_link();
                                } else {
                                    self.open_link(&params, &uri);
                                }
                            }
                        }
                    } else if let Some(rest) = content.strip_prefix(b"52;") {
                        // OSC 52 write: `targets ; base64`. The reads were
                        // classified above, so anything here is a write.
                        // Captured rather than answered — "did it copy the
                        // right thing?" is otherwise unanswerable, since the
                        // only evidence a test can see is the app's own
                        // toast, which proves the code path ran and nothing
                        // about the payload.
                        //
                        // Base64 has no `;`, so the first one is the
                        // separator. No separator at all is not a write.
                        if let Some(sep) = rest.iter().position(|&b| b == b';') {
                            let targets = String::from_utf8_lossy(&rest[..sep]).into_owned();
                            let payload = &rest[sep + 1..];
                            let text = if self.osc_truncated {
                                None
                            } else {
                                decode_base64(payload)
                                    .and_then(|bytes| String::from_utf8(bytes).ok())
                            };
                            self.clipboard = Some(Arc::new(Clipboard::new(&targets, text)));
                        }
                    }
                    return SeqEvent::None;
                }
            }
        }
        // An APC opening with `G` is the kitty graphics protocol — or a
        // continuation of one, which carries `m=` and nothing else.
        if self.dcs_introducer == b'_'
            && (self.dcs_head.first() == Some(&b'G') || self.building.in_progress())
        {
            let control = self.dcs_control_block().to_vec();
            // The control block is `G` followed by the comma-separated keys.
            let keys = control.strip_prefix(b"G").unwrap_or(&control);
            let is_query = keys.split(|&b| b == b',').any(|pair| pair == b"a=q");
            if !is_query {
                // One image, however many escapes it took. `m=1` says
                // another follows; the transmission is not an image until
                // one arrives without it, and counting each escape instead
                // reported a 4.9 KB chart as two pictures.
                self.building.kitty(keys);
                let at = self.dcs_payload_start();
                self.building.chunk(
                    self.dcs_data_len,
                    &self.dcs_body[at..],
                    self.dcs_body_full,
                    self.capture,
                );
                if key_is(keys, b"m", b"1") {
                    return SeqEvent::None;
                }
                return match self.building.finish() {
                    Some(payload) => {
                        self.counts.record(&payload);
                        SeqEvent::Graphics(Box::new(payload))
                    }
                    None => SeqEvent::None,
                };
            }
            // Only an explicit `a=q` is a question. A transmission is an
            // instruction, and classifying one as a query would put "the
            // application queried the terminal" into the next timeout of
            // every application that draws — a false diagnosis, and a loud
            // one.
            let id = kitty_key(keys, b"i=");
            return SeqEvent::Query(Query::KittyGraphics {
                id,
                shape: self.seq_printable(),
            });
        }
        // Sixel: `DCS <params> q <data> ST`, with no intermediate byte. The
        // intermediate is the whole distinction from the two DCS questions
        // below, which reach the same `q` final through `+` and `$`.
        if self.dcs_introducer == b'P' && self.dcs_final == b'q' && self.dcs_intermediate == 0 {
            self.building.sixel();
            let at = self.dcs_payload_start();
            self.building.chunk(
                self.dcs_data_len,
                &self.dcs_body[at..],
                self.dcs_body_full,
                self.capture,
            );
            return match self.building.finish() {
                Some(payload) => {
                    self.counts.record(&payload);
                    SeqEvent::Graphics(Box::new(payload))
                }
                None => SeqEvent::None,
            };
        }
        // XTGETTCAP (`ESC P + q <hex names> ST`). The names are needed to
        // answer, so they come out of the header capture rather than the
        // 24-byte diagnostic buffer.
        if self.dcs_introducer == b'P' && self.dcs_intermediate == b'+' && self.dcs_final == b'q' {
            let head = &self.dcs_head[..usize::from(self.dcs_head_len)];
            // `head` starts at `+`; the names follow the `q`.
            let names = head
                .iter()
                .position(|&b| b == b'q')
                .map(|at| String::from_utf8_lossy(&head[at + 1..]).into_owned())
                .unwrap_or_default();
            return SeqEvent::Query(Query::RequestTermcap {
                names,
                shape: self.seq_printable(),
            });
        }
        // DECRQSS (`ESC P $ q … ST`, "what is the current setting of …?").
        let body = &self.seq_buf[..usize::from(self.seq_len)];
        if matches!(body.get(2..4), Some(b"+q" | b"$q")) {
            return SeqEvent::Query(Query::Unanswerable(self.seq_printable()));
        }
        SeqEvent::None
    }

    /// The image data inside the captured body: for kitty everything after
    /// the `;` that closes the control block, and for sixel everything after
    /// the final byte that closes the DCS header. The protocol's own framing
    /// is metadata, already parsed; what is left is what a decoder wants.
    fn dcs_payload_start(&self) -> usize {
        let separator = if self.dcs_introducer == b'_' {
            b';'
        } else {
            self.dcs_final
        };
        self.dcs_body.iter().position(|&b| b == separator).map_or(
            // No separator: a control-only escape — a delete, or a
            // placement of something transmitted earlier — with no data.
            self.dcs_body.len(),
            |at| at + 1,
        )
    }

    /// The captured head of a DCS-class payload, cut at the first `;`.
    ///
    /// A kitty payload is `G <key=value>,… ; <base64>`; only the control
    /// block before the `;` is worth reading, and stopping there keeps a
    /// base64 blob from being scanned for keys it cannot contain.
    fn dcs_control_block(&self) -> &[u8] {
        let head = &self.dcs_head[..usize::from(self.dcs_head_len)];
        match head.iter().position(|&b| b == b';') {
            Some(sep) => &head[..sep],
            None => head,
        }
    }

    /// Consume one byte of a DCS-class string: header first, then payload.
    fn push_dcs(&mut self, b: u8) {
        // Every byte between the introducer and the terminator, for both
        // protocols alike — a sixel's parameters and a kitty control block
        // are a handful of bytes against an image's thousands, and counting
        // them uniformly is easier to reason about than two rules.
        self.dcs_data_len += 1;
        if self.dcs_introducer != b'_' && self.dcs_final == 0 {
            match b {
                // Parameter and private bytes stay in the header.
                0x30..=0x3f => {}
                // Intermediates: `+` (XTGETTCAP) and `$` (DECRQSS).
                0x20..=0x2f => self.dcs_intermediate = b,
                // Final byte closes the header; the rest is payload.
                0x40..=0x7e => self.dcs_final = b,
                _ => {}
            }
        }
        if usize::from(self.dcs_head_len) < self.dcs_head.len() {
            self.dcs_head[usize::from(self.dcs_head_len)] = b;
            self.dcs_head_len += 1;
        }
        // The body is what a decoder needs and the head is not: 128 bytes
        // holds a control block, never an image. Bounded, and the flag says
        // which of the two this is, so a truncated payload is reported as
        // uncaptured rather than decoded into a plausible wrong picture.
        if self.dcs_body.len() < self.capture {
            self.dcs_body.push(b);
        } else {
            self.dcs_body_full = false;
        }
    }

    /// Feed one byte: capture it if it belongs to a sequence, then run
    /// the state machine.
    pub(crate) fn step(&mut self, b: u8) -> SeqEvent {
        if self.state == State::Ground {
            if b == 0x1b {
                self.seq_len = 0;
                self.push_seq(b);
            }
        } else {
            self.push_seq(b);
        }
        self.transition(b)
    }

    fn transition(&mut self, b: u8) -> SeqEvent {
        const ESC: u8 = 0x1b;
        const CAN: u8 = 0x18;
        const SUB: u8 = 0x1a;
        const BEL: u8 = 0x07;
        const HT: u8 = 0x09;
        const SO: u8 = 0x0e;
        const SI: u8 = 0x0f;

        let mut event = SeqEvent::None;
        self.state = match self.state {
            State::Ground => {
                if b == ESC {
                    self.utf8_remaining = 0;
                    State::Esc
                } else {
                    // Only here is a BEL a bell. Inside OSC it terminates
                    // the string and inside a DCS-class string it is data,
                    // and both of those are other states.
                    if b == BEL && self.utf8_remaining == 0 {
                        self.bells = self.bells.saturating_add(1);
                    }
                    // Locking shifts: SO invokes G1, SI returns to G0. vt100
                    // sees both bytes too and ignores them, so nothing else
                    // has to be told. A pending single shift overrides
                    // whichever is locked, for one character, and is not
                    // consumed here — SI/SO are C0, not GL.
                    match b {
                        SO => self.shifted_out = true,
                        SI => self.shifted_out = false,
                        // Plain `HT` has to come through here as well as
                        // `CHT`, or vt100's fixed eight would keep answering
                        // it and the two would disagree the moment an
                        // application set a stop of its own — a table drawn
                        // half from each.
                        HT => event = SeqEvent::Tabs(TabOp::Forward(1)),
                        _ => {}
                    }
                    // Anything that is not a C0 control or DEL. Named once
                    // because the two readers below want the same test for
                    // different reasons, and they must not drift apart: a
                    // byte that counts as drawn is a byte a link wraps.
                    let printable = b >= 0x20 && b != 0x7f;
                    // One per *character*: continuation bytes arrive while
                    // `utf8_remaining` is non-zero, so nothing is counted
                    // twice. Controls, the BEL just handled included, are not
                    // printable.
                    if printable && self.utf8_remaining == 0 {
                        self.frame_printable = self.frame_printable.saturating_add(1);
                    }
                    // Text written inside an `OSC 8` span is that link's
                    // label. Bytes rather than characters here, so a
                    // multi-byte grapheme survives the split — its
                    // continuation bytes are all >= 0x80 and printable too.
                    // A byte the invoked character set redefines is recorded
                    // as the glyph it draws: the label is what a reader sees
                    // and clicks, and a reader sees `─`, not `q`.
                    if printable && self.link_open {
                        let drawn: &[u8] = match self.charset_glyph(b) {
                            Some(glyph) => glyph.as_bytes(),
                            None => std::slice::from_ref(&b),
                        };
                        for &drawn in drawn {
                            if self.link_label.len() < LINK_LABEL_MAX {
                                self.link_label.push(drawn);
                            } else {
                                self.link_label_truncated = true;
                            }
                        }
                    }
                    // A single shift lasts for one *character*, not one byte:
                    // a multi-byte UTF-8 character consumes it too, so a
                    // continuation byte must not, or the shift survives `汉`
                    // and translates the byte after it. C0, DEL and newline
                    // still do not consume it: SS2 then SI then `l` draws
                    // from G2, which is the mixed-line case this exists for.
                    // RIS clears it separately.
                    let utf8_continuation = (0x80..=0xbf).contains(&b);
                    if b >= 0x20 && b != 0x7f && !utf8_continuation {
                        self.single_shift = None;
                    }
                    self.track_utf8(b);
                    State::Ground
                }
            }
            State::Esc => match b {
                b'[' => {
                    self.reset_csi_scanner();
                    State::Csi
                }
                b']' => {
                    self.osc_buf.clear();
                    self.osc_truncated = false;
                    State::Osc
                }
                // DCS, SOS, PM, APC — string sequences terminated by ST.
                b'P' | b'X' | b'^' | b'_' => {
                    self.reset_dcs_scanner(b);
                    State::Dcs
                }
                0x20..=0x2f => {
                    self.esc_intermediate = b;
                    State::EscIntermediate
                }
                ESC => State::Esc,
                CAN | SUB => State::Ground,
                // RIS (`ESC c`), the hard reset: the terminal returns to its
                // power-on state, so the cursor is the terminal's default
                // again, all four character sets are ASCII with G0 invoked,
                // no single shift is pending, and any open hyperlink span
                // cannot survive.
                //
                // Reporting the last `DECSCUSR` after a reset would claim a
                // fact the terminal does not hold — and it would do it in the
                // one place that matters, since `printf '\033c'` is a way a
                // program restores the cursor on exit, which is exactly what
                // `cursor_shape` exists to let a test check.
                //
                // The window title is deliberately *not* cleared here. In
                // xterm it is a window property rather than terminal state
                // and RIS does not restore it; guessing either way would be
                // the same error in the other direction. Same for the
                // clipboard, the bell count and the link *log*, which are
                // records of what the application emitted rather than state
                // the terminal still holds.
                b'c' => {
                    self.cursor_style = None;
                    self.reset_charsets();
                    self.saved_charsets = None;
                    self.mouse_tracking = 0;
                    self.insert_mode = false;
                    self.tabs.reset();
                    self.close_link();
                    State::Ground
                }
                // DECSC / DECRC: the charset half of save-cursor and
                // restore-cursor. The idiom is save, jump, draw a border,
                // restore — and a restore that forgot the designation
                // rendered the border after it as `lqk`. vt100 does the
                // cursor and attributes; the sets are ours (#232).
                b'7' => {
                    self.saved_charsets = Some(SavedCharsets {
                        g0: self.g0,
                        g1: self.g1,
                        g2: self.g2,
                        g3: self.g3,
                        shifted_out: self.shifted_out,
                    });
                    State::Ground
                }
                b'8' => {
                    match self.saved_charsets {
                        Some(saved) => {
                            self.g0 = saved.g0;
                            self.g1 = saved.g1;
                            self.g2 = saved.g2;
                            self.g3 = saved.g3;
                            self.shifted_out = saved.shifted_out;
                        }
                        // Nothing saved: xterm restores the defaults rather
                        // than leaving the current designation, and so do
                        // we — the least surprising answer, and no new state.
                        None => self.reset_charsets(),
                    }
                    State::Ground
                }
                // HTS (`ESC H`): a tab stop at the cursor column, which the
                // emulator supplies. `hts` is in the terminfo entry every
                // child is handed, so an application laying out a table is
                // entitled to expect it.
                b'H' => {
                    event = SeqEvent::Tabs(TabOp::Set);
                    State::Ground
                }
                // SS2 / SS3: invoke G2 / G3 for the next character only.
                // These are two-character escapes in the *output* stream;
                // `ESC O A` as a DECCKM cursor key is what we *send*, a
                // different direction, and is not parsed here.
                b'N' => {
                    self.single_shift = Some(SingleShift::G2);
                    State::Ground
                }
                b'O' => {
                    self.single_shift = Some(SingleShift::G3);
                    State::Ground
                }
                // Final byte of a two-character sequence (ESC 7, ESC =, …).
                _ => State::Ground,
            },
            State::EscIntermediate => match b {
                // A second intermediate makes this something other than a
                // G0–G3 designation (`ESC % G` selects UTF-8, for one).
                0x20..=0x2f => {
                    self.esc_intermediate = 0;
                    State::EscIntermediate
                }
                ESC => State::Esc,
                CAN | SUB => State::Ground,
                // The final byte: a designation, if the intermediate was a
                // G-set introducer, and the end of the sequence either way.
                0x30..=0x7e => {
                    self.designate(b);
                    State::Ground
                }
                _ => State::Ground,
            },
            State::Csi => match b {
                0x40..=0x7e => {
                    event = self.csi_final(b);
                    State::Ground
                }
                ESC => State::Esc,
                CAN | SUB => State::Ground,
                // Parameter/intermediate bytes (and embedded C0 controls).
                _ => {
                    self.scan_csi_byte(b);
                    State::Csi
                }
            },
            State::Osc => match b {
                BEL => {
                    event = self.string_final(true, false);
                    State::Ground
                }
                ESC => State::OscEsc,
                CAN | SUB => State::Ground,
                _ => {
                    self.push_osc(b);
                    State::Osc
                }
            },
            State::Dcs => match b {
                ESC => State::DcsEsc,
                CAN | SUB => State::Ground,
                _ => {
                    self.push_dcs(b);
                    State::Dcs // BEL is data inside DCS-class strings
                }
            },
            State::OscEsc => match b {
                b'\\' => {
                    event = self.string_final(true, true); // ESC \ = ST
                    State::Ground
                }
                ESC => State::OscEsc,
                // The ESC aborted the string and starts a new sequence;
                // reprocess this byte in Esc state (capture already done).
                _ => {
                    self.state = State::Esc;
                    return self.transition(b);
                }
            },
            State::DcsEsc => match b {
                b'\\' => {
                    event = self.string_final(false, true);
                    State::Ground
                }
                ESC => State::DcsEsc,
                _ => {
                    self.state = State::Esc;
                    return self.transition(b);
                }
            },
        };
        event
    }

    fn track_utf8(&mut self, b: u8) {
        if self.utf8_remaining > 0 && (0x80..=0xbf).contains(&b) {
            self.utf8_remaining -= 1;
            return;
        }
        self.utf8_remaining = match b {
            0xc2..=0xdf => 1,
            0xe0..=0xef => 2,
            0xf0..=0xf4 => 3,
            // ASCII, stray continuation, or invalid lead: not mid-character.
            _ => 0,
        };
    }
}

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

    /// The width these tests construct a tracker at. Only the tab-stop set
    /// is sized, and only the tab tests care what the size is; the rest is
    /// width-agnostic and takes the default terminal's 80.
    const TEST_COLS: u16 = 80;

    fn fed(bytes: &[u8]) -> SeqTracker {
        let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, TEST_COLS);
        t.feed(bytes);
        t
    }

    /// Every event a `BEL` byte can be, and only one of them is a bell.
    #[test]
    fn only_a_bel_in_ground_state_is_a_bell() {
        assert_eq!(fed(b"a\x07b").bells(), 1);
        assert_eq!(fed(b"\x07\x07\x07").bells(), 3, "a count, not a flag");
        assert_eq!(fed(b"plain").bells(), 0);

        // Terminating an OSC string: punctuation, not a bell. And the title
        // must still arrive, which is the thing that would break if the BEL
        // were intercepted before the state machine saw it.
        let t = fed(b"\x1b]0;my app\x07");
        assert_eq!(t.bells(), 0);
        assert_eq!(&*t.title(), "my app");

        // Payload inside a DCS-class string.
        assert_eq!(fed(b"\x1bPq\x07\x07\x1b\\").bells(), 0);
        // A bell after a sequence closes still counts.
        assert_eq!(fed(b"\x1b]0;t\x07\x07").bells(), 1);
    }

    /// The capture bound is a bound on the *payload*, not on each escape.
    ///
    /// kitty sends one escape per 4096 bytes, so a bound applied per escape
    /// would let a thousand-chunk image retain a thousand times the budget —
    /// which is the whole of what the knob is for.
    #[test]
    fn the_capture_bound_holds_across_a_chunked_transmission() {
        let mut tracker = SeqTracker::new(40, TEST_COLS);
        // Ten chunks of eight data bytes: every escape fits the bound
        // comfortably, and the ten together do not.
        let mut wire: Vec<u8> = b"\x1b_Ga=T,f=32,s=4,v=4,m=1;AAAAAAAA\x1b\\".to_vec();
        for _ in 0..8 {
            wire.extend_from_slice(b"\x1b_Gm=1;BBBBBBBB\x1b\\");
        }
        wire.extend_from_slice(b"\x1b_Gm=0;CCCCCCCC\x1b\\");

        let mut seen = None;
        for &byte in &wire {
            if let SeqEvent::Graphics(payload) = tracker.step(byte) {
                seen = Some(*payload);
            }
        }
        let payload = seen.expect("a payload");
        assert_eq!(payload.chunks(), 10);
        assert_eq!(
            payload.data(),
            None,
            "80 bytes must not be kept under a 40-byte bound"
        );
        assert_eq!(tracker.graphics().kitty, 1, "and it is still one image");
    }

    /// Every payload a feed produced, in order.
    fn payloads(bytes: &[u8]) -> Vec<GraphicsPayload> {
        let mut tracker = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, TEST_COLS);
        let mut out = Vec::new();
        for &byte in bytes {
            if let SeqEvent::Graphics(payload) = tracker.step(byte) {
                out.push(*payload);
            }
        }
        out
    }

    /// Kitty and sixel payloads, and the two DCS *questions* that share
    /// sixel's `q` final byte and must not be counted as pictures.
    #[test]
    fn graphics_payloads_are_counted_by_protocol() {
        let kitty = fed(b"\x1b_Gf=24,s=1,v=1,a=T;AAAABBBB\x1b\\");
        assert_eq!(kitty.graphics().kitty, 1);
        assert_eq!(kitty.graphics().sixel, 0);
        // Everything between the introducer and the terminator.
        assert_eq!(kitty.graphics().bytes, 26);
        assert_eq!(fed(b"\x1bPq~~\x1b\\").graphics().bytes, 3, "q~~");

        let sixel = fed(b"\x1bPq#0;2;0;0;0#0~~-~~\x1b\\");
        assert_eq!(sixel.graphics().sixel, 1);
        assert_eq!(sixel.graphics().kitty, 0);

        // Sixel with parameters before the `q`.
        assert_eq!(fed(b"\x1bP0;1;0q~~\x1b\\").graphics().sixel, 1);

        // Neither of these is a picture: both reach `q` through an
        // intermediate byte, which is the whole distinction.
        let termcap = fed(b"\x1bP+q544e\x1b\\").graphics();
        assert_eq!((termcap.kitty, termcap.sixel), (0, 0), "XTGETTCAP");
        let decrqss = fed(b"\x1bP$qm\x1b\\").graphics();
        assert_eq!((decrqss.kitty, decrqss.sixel), (0, 0), "DECRQSS");

        // Two of each accumulate.
        let both = fed(b"\x1b_Ga=T;AA\x1b\\\x1bPq~\x1b\\\x1b_Ga=T;BB\x1b\\");
        assert_eq!((both.graphics().kitty, both.graphics().sixel), (2, 1));
    }

    /// The protocol caps a payload at 4096 bytes and continues with `m=1`,
    /// so every image of consequence arrives in several escapes. Counting
    /// each of them reported one 4.9 KB chart as two pictures — and the
    /// second "picture" had no control block, so nothing could be said
    /// about it either.
    #[test]
    fn a_chunked_kitty_transmission_is_one_image() {
        let wire = b"\x1b_Ga=T,f=32,s=2,v=2,i=1,m=1;AAAA\x1b\\                     \x1b_Gm=1;BBBB\x1b\\\x1b_Gm=0;CCCC\x1b\\";
        let counts = fed(wire).graphics();
        assert_eq!(counts.kitty, 1, "one image, three escapes");

        let payloads = payloads(wire);
        assert_eq!(payloads.len(), 1);
        assert_eq!(payloads[0].chunks(), 3);
        assert_eq!(payloads[0].data(), Some(&b"AAAABBBBCCCC"[..]));
        // The facts come off the first escape; the continuations carry none.
        assert_eq!(payloads[0].size(), Some((2, 2)));
        assert_eq!(payloads[0].id(), Some(1));
        // And the cost is the whole transmission, not the last escape.
        assert_eq!(counts.bytes, payloads[0].bytes());
    }

    /// A delete takes an image *off* the screen. Counting it as one
    /// transmitted made an application that tears down what it drew
    /// indistinguishable from one that drew twice as much.
    #[test]
    fn a_delete_is_counted_apart_from_the_images() {
        let counts = fed(b"\x1b_Ga=T,f=32,s=1,v=1;AA\x1b\\\x1b_Ga=d,d=I,i=1,q=2\x1b\\").graphics();
        assert_eq!(counts.kitty, 1, "one image");
        assert_eq!(counts.deletes, 1, "and one teardown");
        // The wire cost of both is still counted: a delete is traffic.
        assert!(counts.bytes > 22);
    }

    /// A payload past the capture bound keeps every count and drops the
    /// data, rather than handing back a prefix that would decode into a
    /// plausible-looking wrong picture.
    #[test]
    fn a_payload_past_the_capture_bound_is_counted_and_not_kept() {
        let mut tracker = SeqTracker::new(8, TEST_COLS);
        let mut seen = None;
        for &byte in b"\x1b_Ga=T,f=32,s=4,v=4;AAAABBBBCCCCDDDD\x1b\\" {
            if let SeqEvent::Graphics(payload) = tracker.step(byte) {
                seen = Some(*payload);
            }
        }
        let payload = seen.expect("a payload");
        assert_eq!(payload.data(), None, "not kept");
        assert_eq!(payload.size(), Some((4, 4)), "but still described");
        assert_eq!(tracker.graphics().kitty, 1, "and still counted");
    }

    /// The control block is metadata; the data is what a decoder wants.
    #[test]
    fn a_payload_carries_the_data_and_not_the_framing() {
        let kitty = payloads(b"\x1b_Ga=T,f=24,s=1,v=1;QUJD\x1b\\");
        assert_eq!(kitty[0].data(), Some(&b"QUJD"[..]));
        assert_eq!(kitty[0].format(), GraphicsFormat::Rgb);

        // Sixel's header ends at the `q`; everything after it is the image.
        let sixel = payloads(b"\x1bP0;1;0q\"1;1;2;6#0;2;100;0;0~~\x1b\\");
        assert_eq!(sixel[0].data(), Some(&b"\"1;1;2;6#0;2;100;0;0~~"[..]));
        assert_eq!(sixel[0].size(), Some((2, 6)));
    }

    /// The kitty graphics *query* was the one probe of the startup set that
    /// got neither an answer nor a diagnosis: `string_final` looked only at
    /// `+q`/`$q`, which an APC never matches, so `note_unanswered` never saw
    /// it and the timeout said nothing.
    #[test]
    fn the_kitty_graphics_query_is_classified() {
        let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, TEST_COLS);
        let mut events = Vec::new();
        for &b in b"\x1b_Gi=1,a=q;\x1b\\" {
            events.push(t.step(b));
        }
        assert!(
            events.iter().any(|e| matches!(
                e,
                SeqEvent::Query(Query::KittyGraphics { id: Some(1), shape })
                    if shape.contains("_G")
            )),
            "the query must be classified, with its id, for a reply or a \
             timeout note: {events:?}"
        );
        // A query carries no picture, so it is not counted as one.
        assert_eq!(t.graphics().kitty, 0);
    }

    /// A transmission is an instruction, not a question. Classifying one as
    /// a query would put "the application queried the terminal" into the
    /// next timeout of every application that draws.
    #[test]
    fn a_kitty_transmission_is_not_treated_as_a_query() {
        let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, TEST_COLS);
        let mut events = Vec::new();
        for &b in b"\x1b_Gf=24,a=T;QUJD\x1b\\" {
            events.push(t.step(b));
        }
        assert!(
            !events.iter().any(|e| matches!(e, SeqEvent::Query(_))),
            "a transmit is not a question: {events:?}"
        );
        assert_eq!(t.graphics().kitty, 1);
    }

    /// The links a fed tracker holds, as `(uri, id, label, closed)`.
    fn links(bytes: &[u8]) -> Vec<(String, Option<String>, Option<String>, bool)> {
        fed(bytes)
            .links()
            .iter()
            .map(|l| {
                (
                    l.uri().to_string(),
                    l.id().map(str::to_string),
                    l.label().map(str::to_string),
                    l.closed(),
                )
            })
            .collect()
    }

    /// The reproduction from the issue: the label renders as ordinary text
    /// and the URL has to be somewhere a test can reach.
    #[test]
    fn an_osc8_span_records_its_uri_and_the_text_it_wrapped() {
        let seen = links(b"see \x1b]8;;https://example.invalid/a\x1b\\docs\x1b]8;;\x1b\\ here");
        assert_eq!(
            seen,
            vec![(
                "https://example.invalid/a".to_string(),
                None,
                Some("docs".to_string()),
                true
            )]
        );
    }

    #[test]
    fn a_bel_terminated_span_and_a_multibyte_label_both_survive() {
        // BEL is the other legal OSC terminator, and the one `printf` in a
        // shell reaches for.
        let seen = links("\x1b]8;;http://x/\x07café\x1b]8;;\x07".as_bytes());
        assert_eq!(seen[0].2, Some("café".to_string()));
        assert!(seen[0].3);
    }

    #[test]
    fn the_id_parameter_is_kept_so_multi_span_links_can_be_grouped() {
        let seen = links(
            b"\x1b]8;id=42:x=y;http://x/\x1b\\one\x1b]8;;\x1b\\               \x1b]8;id=42;http://x/\x1b\\two\x1b]8;;\x1b\\",
        );
        assert_eq!(seen.len(), 2);
        assert_eq!(seen[0].1.as_deref(), Some("42"));
        assert_eq!(seen[1].1.as_deref(), Some("42"));
        assert_eq!(seen[0].2.as_deref(), Some("one"));
        assert_eq!(seen[1].2.as_deref(), Some("two"));
    }

    /// A URI with a query string contains `;` of its own. Splitting on the
    /// last separator, or on all of them, truncates the target silently —
    /// which is precisely the wrong-URL failure this feature exists to catch.
    #[test]
    fn only_the_first_separator_ends_the_parameters() {
        let seen = links(b"\x1b]8;;http://x/?a=1;b=2\x1b\\t\x1b]8;;\x1b\\");
        assert_eq!(seen[0].0, "http://x/?a=1;b=2");
    }

    /// An unterminated span is a real defect — in a real terminal every
    /// character after it joins the link — so it is reported rather than
    /// dropped, and its label is bounded rather than allowed to swallow the
    /// stream.
    #[test]
    fn an_unterminated_span_is_reported_open_and_cannot_bleed() {
        let mut bytes = b"\x1b]8;;http://x/\x1b\\".to_vec();
        bytes.extend(std::iter::repeat_n(b'z', LINK_LABEL_MAX + 100));
        let seen = links(&bytes);
        assert_eq!(seen.len(), 1);
        assert_eq!(seen[0].0, "http://x/");
        assert!(!seen[0].3, "the application never closed it");
        // Still open, so there is no final label — and the bound means the
        // captured bytes are a prefix, which is not an answer either.
        assert_eq!(seen[0].2, None);
    }

    #[test]
    fn a_label_past_the_bound_is_unknown_rather_than_a_prefix() {
        let mut bytes = b"\x1b]8;;http://x/\x1b\\".to_vec();
        bytes.extend(std::iter::repeat_n(b'z', LINK_LABEL_MAX + 1));
        bytes.extend_from_slice(b"\x1b]8;;\x1b\\");
        let seen = links(&bytes);
        assert!(seen[0].3, "closed");
        assert_eq!(
            seen[0].2, None,
            "a prefix of the wrong length is a wrong answer"
        );
    }

    /// A real terminal replaces the current target rather than nesting, so a
    /// second open closes the first — otherwise the second label would be
    /// attributed to the first URI.
    #[test]
    fn a_new_span_supersedes_one_left_open() {
        let seen = links(b"\x1b]8;;http://a/\x1b\\one\x1b]8;;http://b/\x1b\\two\x1b]8;;\x1b\\");
        assert_eq!(seen.len(), 2);
        assert_eq!(
            (seen[0].0.as_str(), seen[0].2.as_deref()),
            ("http://a/", Some("one"))
        );
        assert_eq!(
            (seen[1].0.as_str(), seen[1].2.as_deref()),
            ("http://b/", Some("two"))
        );
    }

    /// A URI past the OSC capture bound is a *prefix*, and opening a span on
    /// a prefix records a link pointing somewhere the application never
    /// named — the wrong-URL failure this feature exists to catch, only
    /// manufactured by termlens rather than by the program under test.
    /// Refused outright, exactly as a truncated `OSC 52` payload is.
    #[test]
    fn an_osc8_past_the_capture_bound_is_refused_rather_than_truncated() {
        let mut bytes = b"\x1b]8;;http://x/".to_vec();
        bytes.extend(std::iter::repeat_n(b'a', OSC_CAPTURE_MAX));
        bytes.extend_from_slice(b"\x1b\\label\x1b]8;;\x1b\\");
        assert!(
            links(&bytes).is_empty(),
            "a truncated URI must not become a link"
        );
    }

    #[test]
    fn a_malformed_osc8_neither_opens_nor_closes() {
        // No second `;` at all: not a link, and not a close either —
        // silently closing would attribute what follows to nothing.
        let seen = links(b"\x1b]8;http://x/\x1b\\t");
        assert!(seen.is_empty());
        // An open, then a malformed one, then text: the text still belongs
        // to the span that is actually open.
        let seen = links(b"\x1b]8;;http://x/\x1b\\a\x1b]8;junk\x1b\\b\x1b]8;;\x1b\\");
        assert_eq!(seen.len(), 1);
        assert_eq!(seen[0].2.as_deref(), Some("ab"));
    }

    /// The label is what a reader sees: a link wrapped around line drawing
    /// records the glyphs, not the bytes that stood for them.
    #[test]
    fn a_label_drawn_in_the_graphics_set_records_the_glyphs() {
        let seen = links(b"\x1b(0\x1b]8;;http://x/\x1b\\lqk\x1b]8;;\x1b\\\x1b(B");
        assert_eq!(seen[0].2.as_deref(), Some("\u{250c}\u{2500}\u{2510}"));
        // SS2 is looked up twice (the rewriter, then the open span) and
        // consumed once: a shift that stuck would keep translating.
        let seen = links(b"\x1b*0\x1b]8;;http://x/\x1b\\\x1bNl|\x1b]8;;\x1b\\");
        assert_eq!(seen[0].2.as_deref(), Some("\u{250c}|"));
    }

    #[test]
    fn control_characters_are_not_part_of_a_label() {
        // A newline moves the cursor; it does not spell anything.
        let seen = links(b"\x1b]8;;http://x/\x1b\\a\r\nb\x1b]8;;\x1b\\");
        assert_eq!(seen[0].2.as_deref(), Some("ab"));
    }

    #[test]
    fn the_link_log_is_bounded_and_evicts_the_oldest() {
        let mut bytes = Vec::new();
        for n in 0..LINK_HISTORY + 10 {
            bytes
                .extend_from_slice(format!("\x1b]8;;http://x/{n}\x1b\\l\x1b]8;;\x1b\\").as_bytes());
        }
        let seen = links(&bytes);
        assert_eq!(seen.len(), LINK_HISTORY);
        // Oldest evicted, newest kept.
        assert_eq!(seen[0].0, "http://x/10");
        assert_eq!(
            seen[LINK_HISTORY - 1].0,
            format!("http://x/{}", LINK_HISTORY + 9)
        );
    }

    #[test]
    fn an_application_that_emits_no_links_reports_none() {
        assert!(links(b"plain text\x1b]0;title\x07").is_empty());
    }

    #[test]
    fn decscusr_records_the_parameter_the_application_asked_for() {
        // Never asked is its own state, and not the same as any value.
        assert_eq!(fed(b"hello").cursor_style(), None);
        for ps in 0u8..=6 {
            let bytes = format!("\x1b[{ps} q");
            assert_eq!(
                fed(bytes.as_bytes()).cursor_style(),
                Some(ps),
                "DECSCUSR {ps} was not recorded"
            );
        }
        // An omitted parameter is 0 (a blinking block), per xterm.
        assert_eq!(fed(b"\x1b[ q").cursor_style(), Some(0));
        // The last one wins, which is what makes a restore assertable.
        assert_eq!(fed(b"\x1b[5 q\x1b[2 q").cursor_style(), Some(2));
    }

    /// RIS is a way a program restores the cursor on exit, so a stale
    /// `DECSCUSR` after one would fail the very assertion `cursor_shape`
    /// exists to support — and claim a shape the terminal no longer holds.
    #[test]
    fn a_hard_reset_returns_the_cursor_to_the_terminals_default() {
        assert_eq!(fed(b"\x1b[5 q").cursor_style(), Some(5));
        assert_eq!(fed(b"\x1b[5 q\x1bc").cursor_style(), None);
        // …and a style set *after* the reset is still recorded.
        assert_eq!(fed(b"\x1b[5 q\x1bc\x1b[2 q").cursor_style(), Some(2));
    }

    /// An open span cannot survive a hard reset, so it is closed with what
    /// it had. The *log* is a record of what the application emitted and is
    /// deliberately kept, like the bell count and the clipboard.
    #[test]
    fn a_hard_reset_closes_an_open_span_and_keeps_the_log() {
        let seen = links(b"\x1b]8;;http://x/\x1b\\lab\x1bcafter");
        assert_eq!(seen.len(), 1);
        assert_eq!(seen[0].0, "http://x/");
        assert_eq!(
            seen[0].2.as_deref(),
            Some("lab"),
            "the text before the reset"
        );
        assert!(seen[0].3, "closed by the reset");
        // Text after the reset belongs to no span.
        let seen = links(b"\x1b]8;;http://x/\x1b\\a\x1bcbbb");
        assert_eq!(seen[0].2.as_deref(), Some("a"));
    }

    /// The two-character escapes that are *not* RIS must keep passing
    /// through untouched — `ESC 7` (save cursor) is next to it in the table.
    #[test]
    fn other_two_character_escapes_do_not_reset_anything() {
        for seq in [
            &b"\x1b[5 q\x1b7"[..],
            b"\x1b[5 q\x1b8",
            b"\x1b[5 q\x1bD",
            b"\x1b[5 q\x1bM",
        ] {
            assert_eq!(
                fed(seq).cursor_style(),
                Some(5),
                "{seq:?} reset the cursor style"
            );
        }
    }

    #[test]
    fn an_undefined_or_misshapen_decscusr_leaves_the_last_known_style() {
        // 7+ is undefined; xterm ignores it, and inventing a shape here
        // would report one the application never asked for.
        assert_eq!(fed(b"\x1b[5 q\x1b[7 q").cursor_style(), Some(5));
        assert_eq!(fed(b"\x1b[7 q").cursor_style(), None);
        // A private prefix or a second parameter makes it a different
        // sequence, not a DECSCUSR with extra decoration.
        assert_eq!(fed(b"\x1b[?5 q").cursor_style(), None);
        assert_eq!(fed(b"\x1b[5;2 q").cursor_style(), None);
    }

    /// `SP` is the intermediate of DECSCUSR *and* of SL/SR (`CSI Ps SP @`
    /// / `A`), which scroll the screen sideways. Accepting the intermediate
    /// must not turn those into a cursor style, nor let them fall through
    /// into the query table below, which assumes no intermediate.
    #[test]
    fn the_other_space_intermediate_sequences_are_not_cursor_styles() {
        for seq in [&b"\x1b[2 @"[..], b"\x1b[2 A", b"\x1b[1 t"] {
            let mut t = fed(seq);
            assert_eq!(t.cursor_style(), None, "{seq:?} set a cursor style");
            assert_eq!(t.step(b'x'), SeqEvent::None);
        }
    }

    /// The tracker parses bytes a *child process* chooses, so every buffer
    /// in it is a place a hostile or merely broken program could push on.
    /// Each one is bounded in code; this is the test that says so out loud.
    ///
    /// Two phases, because they catch different things. Random bytes explore
    /// the state machine and are the net for a panic — an index, a slice, an
    /// arithmetic overflow — on input nobody thought about. They do *not*
    /// reach any bound: a bound needs thousands of bytes pushed the same way
    /// on purpose, which random bytes essentially never do. So the second
    /// phase writes the shapes a hostile child would actually use.
    ///
    /// The peak assertions at the end are the point. Without them this test
    /// would go on passing if the corpus stopped stressing the buffers, and
    /// its bound checks would be decoration — which is what they were when
    /// first written here, and what the mutation pass caught.
    ///
    /// Deterministic: the seed is the whole corpus, so a failure reproduces.
    #[test]
    fn hostile_input_cannot_panic_or_grow_a_buffer_past_its_bound() {
        let capture = crate::graphics::DEFAULT_CAPTURE;
        let mut tracker = SeqTracker::new(capture, TEST_COLS);
        // (links, label, osc, dcs_body) high-water marks.
        let mut peak = (0usize, 0usize, 0usize, 0usize);

        fn observe(t: &SeqTracker, capture: usize, peak: &mut (usize, usize, usize, usize)) {
            assert!(t.links.len() <= LINK_HISTORY, "link log overran");
            assert!(t.link_label.len() <= LINK_LABEL_MAX, "label overran");
            assert!(t.osc_buf.len() <= OSC_CAPTURE_MAX, "osc buffer overran");
            assert!(t.dcs_body.len() <= capture, "dcs body overran");
            assert!(usize::from(t.seq_len) <= t.seq_buf.len());
            assert!(usize::from(t.dcs_head_len) <= t.dcs_head.len());
            peak.0 = peak.0.max(t.links.len());
            peak.1 = peak.1.max(t.link_label.len());
            peak.2 = peak.2.max(t.osc_buf.len());
            peak.3 = peak.3.max(t.dcs_body.len());
        }

        // Phase 1 — the panic net. xorshift64: a few lines, no dependency,
        // reproducible. Weighted toward the introducers that actually drive
        // the state machine; uniform noise would sit in Ground almost always.
        let mut state: u64 = 0x2545_F491_4F6C_DD1D;
        let mut rand = move || {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            state
        };
        const PALETTE: &[u8] =
            b"\x1b[]P_^X;:0123456789 qhlmc\\\x07\x18\x1a~?$8abzId=\xff\x80\xc3\n\r\t";
        for _ in 0..400_000 {
            tracker.step(PALETTE[(rand() as usize) % PALETTE.len()]);
            observe(&tracker, capture, &mut peak);
        }

        // Phase 2 — the shapes a hostile child would use, each aimed at one
        // buffer and overrunning it by a clear margin.
        let feed = |bytes: &[u8], t: &mut SeqTracker, peak: &mut _| {
            for &b in bytes {
                t.step(b);
                observe(t, capture, peak);
            }
        };
        // (a) far more spans than the log holds.
        for n in 0..LINK_HISTORY * 3 {
            feed(
                format!("\x1b]8;;http://x/{n}\x1b\\L\x1b]8;;\x1b\\").as_bytes(),
                &mut tracker,
                &mut peak,
            );
        }
        // (b) one span whose label runs well past the bound.
        feed(b"\x1b]8;;http://x/\x1b\\", &mut tracker, &mut peak);
        feed(&vec![b'L'; LINK_LABEL_MAX * 2], &mut tracker, &mut peak);
        feed(b"\x1b]8;;\x1b\\", &mut tracker, &mut peak);
        // (c) one OSC longer than the capture bound.
        feed(b"\x1b]0;", &mut tracker, &mut peak);
        feed(&vec![b'T'; OSC_CAPTURE_MAX * 2], &mut tracker, &mut peak);
        feed(b"\x07", &mut tracker, &mut peak);

        // The corpus must actually have reached each bound, or every check
        // above was inert.
        assert_eq!(peak.0, LINK_HISTORY, "the link log was never filled");
        assert_eq!(peak.1, LINK_LABEL_MAX, "the label bound was never reached");
        assert_eq!(peak.2, OSC_CAPTURE_MAX, "the osc bound was never reached");

        // And the accessors stay total on whatever state that left behind.
        let _ = tracker.title();
        let _ = tracker.clipboard();
        let _ = tracker.links();
        let _ = tracker.cursor_style();
        let _ = tracker.graphics();
    }

    /// The same, on the grammar rather than the alphabet: well-formed
    /// `OSC 8` spans interleaved with the sequences most likely to collide
    /// with them, driven long enough to exercise eviction many times over.
    #[test]
    fn a_long_well_formed_stream_stays_bounded_and_consistent() {
        let mut tracker = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, TEST_COLS);
        for n in 0..5_000u32 {
            let chunk = format!(
                "\x1b]8;id={n};http://example.invalid/{n}\x1b\\label{n}\x1b]8;;\x1b\\\
                 \x1b]0;title{n}\x07\x1b[{} q text\r\n",
                n % 7
            );
            tracker.feed(chunk.as_bytes());
            assert!(tracker.links.len() <= LINK_HISTORY);
        }
        let links = tracker.links();
        assert_eq!(links.len(), LINK_HISTORY, "the log fills and then holds");
        // Oldest evicted, newest kept, every retained span complete.
        assert!(links.iter().all(|l| l.closed() && l.label().is_some()));
        assert_eq!(links[LINK_HISTORY - 1].uri(), "http://example.invalid/4999");
        assert_eq!(links[LINK_HISTORY - 1].label(), Some("label4999"));
    }

    /// The glyphs a fed tracker would hand the grid for `text`, byte by
    /// byte: the translation where one applies, the byte itself otherwise.
    fn drawn(bytes: &[u8]) -> String {
        let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, TEST_COLS);
        let mut out = String::new();
        for &b in bytes {
            match t.charset_glyph(b) {
                Some(glyph) => out.push_str(glyph),
                None if t.state == State::Ground && (0x20..0x7f).contains(&b) => {
                    out.push(b as char);
                }
                None => {}
            }
            t.step(b);
        }
        out
    }

    /// The reproduction from the issue, and the shape ncurses emits on an
    /// xterm terminfo: designate into G0, draw, designate ASCII back.
    #[test]
    fn dec_special_graphics_in_g0_translates_the_bytes_it_redefines() {
        assert_eq!(drawn(b"lqqqk"), "lqqqk", "ASCII until designated");
        assert_eq!(
            drawn(b"\x1b(0lqqqk\x1b(B"),
            "\u{250c}\u{2500}\u{2500}\u{2500}\u{2510}"
        );
        // Back to ASCII after the redesignation, and the letters are letters.
        assert_eq!(drawn(b"\x1b(0lq\x1b(Blq"), "\u{250c}\u{2500}lq");
        // Bytes below `_` are the same in both sets.
        assert_eq!(drawn(b"\x1b(0A1 +\x1b(B"), "A1 +");
        // The designation's own final byte is never a glyph.
        assert_eq!(drawn(b"\x1b(0\x1b(0"), "");
    }

    /// The vt100-terminfo shape: designate into G1 once, then SO/SI.
    #[test]
    fn shift_out_invokes_g1_and_shift_in_returns_to_g0() {
        assert_eq!(drawn(b"\x1b)0lqk"), "lqk", "G1 designated but not invoked");
        assert_eq!(
            drawn(b"\x1b)0\x0elqk\x0flqk"),
            "\u{250c}\u{2500}\u{2510}lqk"
        );
        // SO with an ASCII G1 changes nothing.
        assert_eq!(drawn(b"\x0elqk"), "lqk");
        // And G0 can be the graphics set while G1 is ASCII: SO turns it off.
        assert_eq!(drawn(b"\x1b(0q\x0eq\x0fq"), "\u{2500}q\u{2500}");
    }

    /// The issue's reproduction: designate G2/G3, single-shift one graphic,
    /// then the locked set resumes. `|` is itself a Special Graphics byte
    /// (`≠`), so a shift that stuck would translate it too.
    #[test]
    fn ss2_invokes_g2_for_one_character() {
        assert_eq!(drawn(b"\x1b*0\x1bNl\x1b(B|"), "\u{250c}|");
        assert_eq!(
            drawn(b"\x1b*0\x1bNll"),
            "\u{250c}l",
            "the character after the shift is the locked set again"
        );
        // Designated but not invoked: G2 does not replace the locking shift.
        assert_eq!(drawn(b"\x1b*0l"), "l");
        // SS2 with G2 still ASCII changes nothing, and does not stick.
        assert_eq!(drawn(b"\x1bNlq"), "lq");
    }

    #[test]
    fn ss3_invokes_g3_for_one_character() {
        assert_eq!(drawn(b"\x1b+0\x1bOl\x1b(B|"), "\u{250c}|");
        assert_eq!(drawn(b"\x1b+0\x1bOll"), "\u{250c}l");
        assert_eq!(drawn(b"\x1b+0l"), "l");
    }

    /// A single shift overrides the locked set without disturbing it: SO
    /// stays in G1 around the one G2 character.
    #[test]
    fn a_single_shift_overrides_the_locking_shift_for_one_character() {
        // G1 graphics, G2 ASCII: SO then SS2 then `lqk` is `l` then `─┐`.
        assert_eq!(drawn(b"\x1b)0\x1b*B\x0e\x1bNlqk"), "l\u{2500}\u{2510}");
        // And the other way: G0 graphics, SS2 from ASCII G2 turns one
        // byte back into a letter without leaving the graphics set.
        assert_eq!(drawn(b"\x1b(0\x1b*B\x1bNlq"), "l\u{2500}");
    }

    /// SS2/SS3 apply to the next *character*, not the next byte. An
    /// intervening SI or a G0 redesignation must not eat the shift.
    #[test]
    fn a_single_shift_survives_intervening_controls_and_designations() {
        assert_eq!(drawn(b"\x1b*0\x1bN\x0fl"), "\u{250c}");
        assert_eq!(drawn(b"\x1b*0\x1bN\x7fl"), "\u{250c}");
        assert_eq!(drawn(b"\x1b*0\x1bN\x1b(Bl"), "\u{250c}");
        // A designation into G2 between the shift and the character still
        // applies: the slot is read when the character is drawn.
        assert_eq!(drawn(b"\x1b*0\x1bN\x1b*Bl"), "l");
        assert_eq!(drawn(b"\x1bN\x1b*0l"), "\u{250c}");
    }

    /// A single shift is one *character*: CJK, emoji and `é` consume it,
    /// so the graphics byte after them is a letter. `drawn` skips UTF-8,
    /// so this asks the tracker after the character rather than concatenating.
    #[test]
    fn a_multibyte_character_consumes_a_single_shift() {
        for ch in ["", "🦀", "é"] {
            let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, TEST_COLS);
            t.feed(b"\x1b*0\x1bN");
            assert_eq!(
                t.charset_glyph(b'l'),
                Some("\u{250c}"),
                "shift pending before {ch}"
            );
            t.feed(ch.as_bytes());
            assert_eq!(
                t.charset_glyph(b'l'),
                None,
                "shift must not survive {ch} and translate the next l"
            );
        }
    }

    #[test]
    fn a_hard_reset_returns_all_four_sets_to_ascii() {
        assert_eq!(drawn(b"\x1b(0\x1b)0\x0eq\x1bcq\x0fq"), "\u{2500}qq");
        // Pending SS2 does not survive RIS. Redesignating G2 afterwards
        // without a new shift would still translate `l` if the shift stuck,
        // which is worse than never shifting: the rest of the line goes.
        assert_eq!(drawn(b"\x1b*0\x1bN\x1bc\x1b*0l"), "l");
        // G2 itself is ASCII again, so a new SS2 without redesignating is
        // a letter too.
        assert_eq!(drawn(b"\x1b*0\x1bc\x1bNl"), "l");
        assert_eq!(drawn(b"\x1b+0\x1bO\x1bc\x1b+0l"), "l");
    }

    /// Only a byte in ground state is a character: the same bytes inside an
    /// OSC title, a CSI parameter or a DCS payload must pass untouched.
    #[test]
    fn bytes_inside_sequences_are_never_translated() {
        let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, TEST_COLS);
        for &b in b"\x1b(0" {
            t.step(b);
        }
        assert_eq!(t.charset_glyph(b'q'), Some("\u{2500}"));
        for &b in b"\x1b]0;lqqk" {
            assert_eq!(t.charset_glyph(b), None, "inside an OSC: {b:?}");
            t.step(b);
        }
        t.step(0x07);
        assert_eq!(&*t.title(), "lqqk", "the title keeps its letters");
        for &b in b"\x1b[3" {
            assert_eq!(t.charset_glyph(b), None, "inside a CSI: {b:?}");
            t.step(b);
        }
        t.step(b'm');
        assert_eq!(t.charset_glyph(b'x'), Some("\u{2502}"), "and ground again");
    }

    /// Other national sets and the alternate ROMs read as ASCII, and a second
    /// intermediate is not a designation at all.
    #[test]
    fn other_designations_read_as_ascii() {
        for seq in [
            &b"\x1b(A"[..],
            b"\x1b(B",
            b"\x1b(1",
            b"\x1b*A",
            b"\x1b+B",
            b"\x1b(2",
            b"\x1b(<",
        ] {
            let mut bytes = seq.to_vec();
            bytes.push(b'q');
            assert_eq!(drawn(&bytes), "q", "{seq:?}");
        }
        // `ESC ( 0` then `ESC % G` (select UTF-8): the second sequence has
        // two intermediates and designates nothing, so G0 stays graphics.
        assert_eq!(drawn(b"\x1b(0\x1b%Gq"), "\u{2500}");
        // Same for a national set in G2/G3, invoked by the single shift.
        assert_eq!(drawn(b"\x1b*A\x1bNq"), "q");
        assert_eq!(drawn(b"\x1b+A\x1bOq"), "q");
    }

    #[test]
    fn a_designation_split_across_feeds_still_applies() {
        let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, TEST_COLS);
        t.feed(b"\x1b(");
        assert!(t.mid_sequence());
        t.feed(b"0");
        assert_eq!(t.charset_glyph(b'l'), Some("\u{250c}"));

        let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, TEST_COLS);
        t.feed(b"\x1b*");
        assert!(t.mid_sequence());
        t.feed(b"0\x1bN");
        assert!(!t.mid_sequence());
        assert_eq!(t.charset_glyph(b'l'), Some("\u{250c}"));
    }

    #[test]
    fn plain_text_is_ground() {
        assert!(!fed(b"hello world\r\n").mid_sequence());
    }

    #[test]
    fn split_csi_is_mid_sequence_until_final_byte() {
        let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, TEST_COLS);
        t.feed(b"\x1b[3");
        assert!(t.mid_sequence());
        t.feed(b"1");
        assert!(t.mid_sequence());
        t.feed(b"m");
        assert!(!t.mid_sequence());
    }

    #[test]
    fn two_char_escape_completes() {
        assert!(!fed(b"\x1b7").mid_sequence()); // DECSC
        assert!(fed(b"\x1b").mid_sequence());
    }

    #[test]
    fn esc_intermediate_completes_on_final() {
        assert!(fed(b"\x1b(").mid_sequence()); // charset designation, unfinished
        assert!(!fed(b"\x1b(B").mid_sequence());
        assert!(fed(b"\x1b*").mid_sequence());
        assert!(!fed(b"\x1b*0").mid_sequence());
        // SS2/SS3 are two-character escapes; they must not stay mid-sequence
        // or wait_idle would hang after a lone graphic shift.
        assert!(!fed(b"\x1bN").mid_sequence());
        assert!(!fed(b"\x1bO").mid_sequence());
    }

    #[test]
    fn osc_terminated_by_bel_or_st() {
        assert!(fed(b"\x1b]0;title").mid_sequence());
        assert!(!fed(b"\x1b]0;title\x07").mid_sequence());
        assert!(!fed(b"\x1b]0;title\x1b\\").mid_sequence());
    }

    #[test]
    fn dcs_terminated_by_st_only() {
        assert!(fed(b"\x1bPdata").mid_sequence());
        assert!(fed(b"\x1bPdata\x07").mid_sequence()); // BEL is DCS payload
        assert!(!fed(b"\x1bPdata\x1b\\").mid_sequence());
    }

    #[test]
    fn esc_inside_string_starts_new_sequence() {
        // ESC c aborts the OSC and completes as its own two-char escape.
        assert!(!fed(b"\x1b]0;title\x1bc").mid_sequence());
        // ESC [ aborts the OSC and leaves us inside a CSI.
        assert!(fed(b"\x1b]0;title\x1b[3").mid_sequence());
    }

    #[test]
    fn can_aborts_sequences() {
        assert!(!fed(b"\x1b[31\x18").mid_sequence());
    }

    #[test]
    fn sync_update_events_fire_on_2026_set_and_reset() {
        let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, TEST_COLS);
        let events: Vec<SeqEvent> = b"\x1b[?2026h".iter().map(|&b| t.step(b)).collect();
        assert_eq!(*events.last().unwrap(), SeqEvent::SyncBegin);
        assert!(t.in_sync_update());
        let events: Vec<SeqEvent> = b"\x1b[?2026l".iter().map(|&b| t.step(b)).collect();
        assert_eq!(*events.last().unwrap(), SeqEvent::SyncEnd);
        assert!(!t.in_sync_update());
    }

    #[test]
    fn sync_2026_is_recognized_anywhere_in_a_multi_mode_list() {
        let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, TEST_COLS);
        t.feed(b"\x1b[?2026;25h");
        assert!(t.in_sync_update());
        let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, TEST_COLS);
        t.feed(b"\x1b[?25;2026h");
        assert!(t.in_sync_update());
    }

    #[test]
    fn lookalike_sequences_do_not_toggle_sync() {
        let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, TEST_COLS);
        t.feed(b"\x1b[2026h"); // not private (no '?')
        assert!(!t.in_sync_update());
        t.feed(b"\x1b[?2026m"); // wrong final byte
        assert!(!t.in_sync_update());
        t.feed(b"\x1b[?2026:1h"); // sub-parameter form: not a plain mode set
        assert!(!t.in_sync_update());
        t.feed(b"\x1b[?20260h"); // different mode number
        assert!(!t.in_sync_update());
    }

    #[test]
    fn base64_decodes_or_refuses() {
        assert_eq!(
            decode_base64(b"dGhlIHRpdGxl").as_deref(),
            Some(&b"the title"[..])
        );
        // Every padding shape.
        assert_eq!(decode_base64(b"YQ==").as_deref(), Some(&b"a"[..]));
        assert_eq!(decode_base64(b"YWI=").as_deref(), Some(&b"ab"[..]));
        assert_eq!(decode_base64(b"YWJj").as_deref(), Some(&b"abc"[..]));
        // Unpadded is common in the wild and unambiguous.
        assert_eq!(decode_base64(b"YQ").as_deref(), Some(&b"a"[..]));
        assert_eq!(decode_base64(b"YWI").as_deref(), Some(&b"ab"[..]));
        // A real write of nothing.
        assert_eq!(decode_base64(b"").as_deref(), Some(&b""[..]));

        // Refusals: out of alphabet, impossible length, misplaced padding.
        assert_eq!(decode_base64(b"not base64!"), None);
        assert_eq!(decode_base64(b"YWJjZ"), None);
        assert_eq!(decode_base64(b"Y===="), None);
        // One leftover character encodes nothing.
        assert_eq!(decode_base64(b"Y"), None);
    }

    #[test]
    fn osc52_writes_are_captured_with_their_target() {
        let t = fed(b"\x1b]52;c;V2lyZSB1cCB0aGUgUFRZIHJlYWRlcg==\x07");
        let clip = t.clipboard().expect("a write was observed");
        assert_eq!(clip.targets(), "c");
        assert_eq!(clip.text(), Some("Wire up the PTY reader"));

        // Primary selection, ST-terminated instead of BEL.
        let t = fed(b"\x1b]52;p;c2VsZWN0ZWQgd29yZHM=\x1b\\");
        let clip = t.clipboard().expect("a write was observed");
        assert_eq!(clip.targets(), "p");
        assert_eq!(clip.text(), Some("selected words"));

        // No target named: the terminal would pick its default, and we
        // report what the application actually sent rather than guessing.
        let t = fed(b"\x1b]52;;Y29waWVk\x07");
        assert_eq!(t.clipboard().expect("write").targets(), "");

        // The most recent write wins.
        let t = fed(b"\x1b]52;c;YQ==\x07\x1b]52;c;YWI=\x07");
        assert_eq!(t.clipboard().expect("write").text(), Some("ab"));
    }

    #[test]
    fn an_undecodable_payload_is_not_an_empty_clipboard() {
        // The distinction the whole feature rests on: a test asserting
        // `text() == Some("")` must not pass on a payload we could not read.
        let empty = fed(b"\x1b]52;c;\x07");
        assert_eq!(empty.clipboard().expect("write").text(), Some(""));

        let broken = fed(b"\x1b]52;c;!!!not base64!!!\x07");
        assert_eq!(broken.clipboard().expect("write").text(), None);
        assert_eq!(broken.clipboard().expect("write").targets(), "c");

        // Valid base64 that is not text.
        let not_utf8 = fed(b"\x1b]52;c;//8=\x07");
        assert_eq!(not_utf8.clipboard().expect("write").text(), None);
    }

    #[test]
    fn a_payload_past_the_capture_bound_is_reported_as_unreadable() {
        // A prefix of base64 can still decode — to the wrong thing. Any
        // truncation must therefore read as "could not decode".
        let mut stream = b"\x1b]52;c;".to_vec();
        stream.extend(std::iter::repeat_n(b'A', OSC_CAPTURE_MAX + 64));
        stream.push(0x07);
        let t = fed(&stream);
        assert_eq!(t.clipboard().expect("write").text(), None);
    }

    #[test]
    fn a_clipboard_read_is_a_query_not_a_write() {
        let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, TEST_COLS);
        let events: Vec<SeqEvent> = b"\x1b]52;c;?\x07".iter().map(|&b| t.step(b)).collect();
        assert!(matches!(
            events.last(),
            Some(SeqEvent::Query(Query::Unanswerable(_)))
        ));
        assert!(t.clipboard().is_none(), "a read must not invent a write");
    }

    #[test]
    fn an_end_that_closes_no_begin_is_not_a_frame() {
        // Applications reset terminal modes defensively at startup and on
        // crash, and such a reset string contains `?2026l`. It must not end
        // a frame that never began.
        let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, TEST_COLS);
        let events: Vec<SeqEvent> = b"\x1b[?2026l".iter().map(|&b| t.step(b)).collect();
        assert!(!events.contains(&SeqEvent::SyncEnd));
        assert!(!t.in_sync_update());

        // Taken verbatim from a real crash handler.
        let reset = b"\x1b[?2026l\x1b[?25h\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?2004l\x1b[?1049l";
        let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, TEST_COLS);
        let events: Vec<SeqEvent> = reset.iter().map(|&b| t.step(b)).collect();
        assert!(!events.contains(&SeqEvent::SyncEnd));

        // And the End of a real frame still ends it, once only.
        let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, TEST_COLS);
        let events: Vec<SeqEvent> = b"\x1b[?2026h\x1b[?2026l\x1b[?2026l"
            .iter()
            .map(|&b| t.step(b))
            .collect();
        assert_eq!(
            events.iter().filter(|e| **e == SeqEvent::SyncEnd).count(),
            1
        );
    }

    #[test]
    fn sync_survives_an_aborted_csi_inside_the_update() {
        let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, TEST_COLS);
        t.feed(b"\x1b[?2026h\x1b[31\x18"); // CAN aborts the SGR, not the frame
        assert!(t.in_sync_update());
        t.feed(b"\x1b[?2026l");
        assert!(!t.in_sync_update());
    }

    fn queries_of(bytes: &[u8]) -> Vec<Query> {
        let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, TEST_COLS);
        bytes
            .iter()
            .filter_map(|&b| match t.step(b) {
                SeqEvent::Query(q) => Some(q),
                _ => None,
            })
            .collect()
    }

    #[test]
    fn recognizes_the_answerable_queries() {
        assert_eq!(
            queries_of(b"\x1b[6n"),
            vec![Query::CursorPosition { private: false }]
        );
        assert_eq!(
            queries_of(b"\x1b[?6n"),
            vec![Query::CursorPosition { private: true }]
        );
        assert_eq!(queries_of(b"\x1b[5n"), vec![Query::OperatingStatus]);
        assert_eq!(queries_of(b"\x1b[c"), vec![Query::PrimaryDa]);
        assert_eq!(queries_of(b"\x1b[0c"), vec![Query::PrimaryDa]);
        assert_eq!(queries_of(b"\x1b[>c"), vec![Query::SecondaryDa]);
        assert_eq!(queries_of(b"\x1b[18t"), vec![Query::TextAreaSize]);
        assert_eq!(
            queries_of(b"\x1b]11;?\x07"),
            vec![Query::OscColor {
                code: 11,
                st_terminated: false
            }]
        );
        assert_eq!(
            queries_of(b"\x1b]10;?\x1b\\"),
            vec![Query::OscColor {
                code: 10,
                st_terminated: true
            }]
        );
    }

    /// The pixel reports used to be lumped in with the whole `CSI t` family
    /// as unanswerable. They are arithmetic, so they are now their own
    /// questions — while the rest of the family stays declined.
    #[test]
    fn pixel_geometry_queries_are_classified_apart_from_the_rest() {
        assert_eq!(queries_of(b"\x1b[14t"), vec![Query::WindowSizePixels]);
        assert_eq!(queries_of(b"\x1b[16t"), vec![Query::CellSizePixels]);
        assert_eq!(queries_of(b"\x1b[18t"), vec![Query::TextAreaSize]);
        for shape in [&b"\x1b[11t"[..], b"\x1b[13t", b"\x1b[19t", b"\x1b[20t"] {
            assert!(
                matches!(queries_of(shape).as_slice(), [Query::Unanswerable(_)]),
                "still declined: {shape:?}"
            );
        }
    }

    /// The names must come out intact, since the reply has to echo each one
    /// back — and they are longer than the 24-byte diagnostic buffer can
    /// hold, which is why they come from the header capture instead.
    #[test]
    fn xtgettcap_carries_the_names_it_was_asked_for() {
        // "TN" and "colors", hex-encoded, as xterm-style clients send them.
        let q = queries_of(b"\x1bP+q544e;636f6c6f7273\x1b\\");
        assert_eq!(
            q,
            vec![Query::RequestTermcap {
                names: "544e;636f6c6f7273".into(),
                shape: "^[P+q544e;636f6c6f7273^[\\".into(),
            }]
        );
    }

    #[test]
    fn a_kitty_probe_without_an_id_still_classifies() {
        assert_eq!(
            queries_of(b"\x1b_Ga=q;\x1b\\"),
            vec![Query::KittyGraphics {
                id: None,
                shape: "^[_Ga=q;^[\\".into()
            }]
        );
    }

    #[test]
    fn recognizes_unanswerable_questions_with_their_shape() {
        let q = queries_of(b"\x1b[?u");
        assert_eq!(q, vec![Query::Unanswerable("^[[?u".into())]);
        // 14t and 16t are classified in their own right now; 13t is not.
        let q = queries_of(b"\x1b[13t");
        assert_eq!(q, vec![Query::Unanswerable("^[[13t".into())]);
        // XTGETTCAP is answerable now; DECRQSS still is not.
        let q = queries_of(b"\x1bP$qm\x1b\\"); // DECRQSS
        assert_eq!(q, vec![Query::Unanswerable("^[P$qm^[\\".into())]);
        let q = queries_of(b"\x1b[=c"); // DA3
        assert_eq!(q, vec![Query::Unanswerable("^[[=c".into())]);
        let q = queries_of(b"\x1b]12;?\x07"); // cursor color
        assert_eq!(q, vec![Query::Unanswerable("^[]12;?^G".into())]);
        // Any CSI …n is a DSR-family status request by definition.
        let q = queries_of(b"\x1b[6;1n");
        assert_eq!(q, vec![Query::Unanswerable("^[[6;1n".into())]);
    }

    #[test]
    fn recognizes_decrqm_mode_requests() {
        assert_eq!(queries_of(b"\x1b[?2026$p"), vec![Query::RequestMode(2026)]);
        assert_eq!(queries_of(b"\x1b[?2004$p"), vec![Query::RequestMode(2004)]);
        assert_eq!(queries_of(b"\x1b[?1$p"), vec![Query::RequestMode(1)]);
        // ANSI-mode DECRQM (no `?`) is recognized but not answerable.
        assert_eq!(
            queries_of(b"\x1b[4$p"),
            vec![Query::Unanswerable("^[[4$p".into())]
        );
    }

    #[test]
    fn recognizes_the_remaining_unanswerable_families() {
        // DECRQSS: "what is the current setting of ...?"
        assert_eq!(
            queries_of(b"\x1bP$qm\x1b\\"),
            vec![Query::Unanswerable("^[P$qm^[\\".into())]
        );
        // Palette query and clipboard read.
        assert_eq!(
            queries_of(b"\x1b]4;1;?\x07"),
            vec![Query::Unanswerable("^[]4;1;?^G".into())]
        );
        assert_eq!(
            queries_of(b"\x1b]52;c;?\x07"),
            vec![Query::Unanswerable("^[]52;c;?^G".into())]
        );
    }

    #[test]
    fn setting_a_palette_colour_is_not_a_query() {
        // `OSC 4;1;rgb:...` sets rather than asks — only the `?` form is
        // a question.
        assert!(queries_of(b"\x1b]4;1;rgb:ff/00/00\x07").is_empty());
        assert!(queries_of(b"\x1b]52;c;aGVsbG8=\x07").is_empty());
    }

    #[test]
    fn ordinary_output_is_not_a_query() {
        assert!(queries_of(b"\x1b[31m").is_empty()); // SGR
        assert!(queries_of(b"\x1b[2J\x1b[H").is_empty()); // clear+home
        assert!(queries_of(b"\x1b[8;30;100t").is_empty()); // resize command
        assert!(queries_of(b"\x1b]0;title\x07").is_empty()); // set title
        assert!(queries_of(b"\x1b[1;6H").is_empty()); // cursor move
        assert!(queries_of(b"plain text").is_empty());
    }

    #[test]
    fn osc_0_and_2_set_the_title_via_bel_or_st() {
        let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, TEST_COLS);
        assert_eq!(&*t.title(), "");
        t.feed(b"\x1b]2;hello world\x07");
        assert_eq!(&*t.title(), "hello world");
        t.feed("\x1b]0;second ✓\x1b\\".as_bytes());
        assert_eq!(&*t.title(), "second ✓");
    }

    #[test]
    fn titles_longer_than_the_diagnostic_capture_are_kept_whole() {
        let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, TEST_COLS);
        let title = "t".repeat(80); // seq_buf truncates at 24; titles must not
        t.feed(format!("\x1b]2;{title}\x07").as_bytes());
        assert_eq!(&*t.title(), title.as_str());
    }

    #[test]
    fn title_survives_chunked_delivery() {
        let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, TEST_COLS);
        t.feed(b"\x1b]2;split");
        t.feed(b" title\x07");
        assert_eq!(&*t.title(), "split title");
    }

    #[test]
    fn title_keeps_embedded_semicolons() {
        let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, TEST_COLS);
        t.feed(b"\x1b]0;a;b;c\x07");
        assert_eq!(&*t.title(), "a;b;c");
    }

    #[test]
    fn icon_only_and_aborted_titles_do_not_change_the_title() {
        let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, TEST_COLS);
        t.feed(b"\x1b]2;kept\x07");
        t.feed(b"\x1b]1;icon only\x07"); // OSC 1: icon name, not the title
        assert_eq!(&*t.title(), "kept");
        t.feed(b"\x1b]2;aborted\x18"); // CAN aborts the string
        assert_eq!(&*t.title(), "kept");
        t.feed(b"\x1b]2;also aborted\x1b[31m"); // ESC starts a new sequence
        assert_eq!(&*t.title(), "kept");
        t.feed(b"\x1b]2;\x07"); // explicitly set empty: cleared
        assert_eq!(&*t.title(), "");
    }

    #[test]
    fn split_utf8_is_mid_sequence() {
        let bytes = "".as_bytes(); // 3 bytes
        let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, TEST_COLS);
        t.feed(&bytes[..1]);
        assert!(t.mid_sequence());
        t.feed(&bytes[1..2]);
        assert!(t.mid_sequence());
        t.feed(&bytes[2..]);
        assert!(!t.mid_sequence());
    }

    /// Every [`TabOp`] a stream can produce, so the recognition is pinned
    /// apart from the rewrite that acts on it.
    fn tab_ops(bytes: &[u8]) -> Vec<TabOp> {
        let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, TEST_COLS);
        let mut out = Vec::new();
        for &byte in bytes {
            if let SeqEvent::Tabs(op) = t.step(byte) {
                out.push(op);
            }
        }
        out
    }

    #[test]
    fn the_five_tab_sequences_are_recognized() {
        assert_eq!(tab_ops(b"\x1bH"), vec![TabOp::Set]);
        assert_eq!(tab_ops(b"\x1b[g"), vec![TabOp::ClearAtCursor]);
        assert_eq!(tab_ops(b"\x1b[0g"), vec![TabOp::ClearAtCursor]);
        assert_eq!(tab_ops(b"\x1b[3g"), vec![TabOp::ClearAll]);
        assert_eq!(tab_ops(b"\t"), vec![TabOp::Forward(1)]);
        // An omitted or zero count is one, as it is for every other CSI
        // motion; anything else is taken as written.
        assert_eq!(tab_ops(b"\x1b[I"), vec![TabOp::Forward(1)]);
        assert_eq!(tab_ops(b"\x1b[0I"), vec![TabOp::Forward(1)]);
        assert_eq!(tab_ops(b"\x1b[3I"), vec![TabOp::Forward(3)]);
        assert_eq!(tab_ops(b"\x1b[Z"), vec![TabOp::Back(1)]);
        assert_eq!(tab_ops(b"\x1b[2Z"), vec![TabOp::Back(2)]);
    }

    #[test]
    fn sequences_that_only_look_like_tab_operations_are_left_alone() {
        // `TBC 1`, `2`, `4` and `5` clear *line* tab stops, which this crate
        // has no notion of. Recognized as not ours rather than guessed at.
        assert!(tab_ops(b"\x1b[1g").is_empty());
        assert!(tab_ops(b"\x1b[2g").is_empty());
        // A private prefix is a different sequence entirely.
        assert!(tab_ops(b"\x1b[?3g").is_empty());
        assert!(tab_ops(b"\x1b[?1I").is_empty());
        // `CSI H` is CUP, and only the bare `ESC H` is HTS.
        assert!(tab_ops(b"\x1b[H").is_empty());
        assert!(tab_ops(b"\x1b[1;1H").is_empty());
        // A tab inside a string sequence is payload, not a motion — the
        // same rule that keeps a BEL there from being a bell.
        assert!(tab_ops(b"\x1b]0;a\tb\x07").is_empty());
        assert!(tab_ops(b"\x1bPq\t\x1b\\").is_empty());
    }

    #[test]
    fn a_stop_set_at_the_cursor_is_where_the_next_tab_lands() {
        let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, 24);
        // The default eight, until the application says otherwise.
        assert_eq!(t.tab_op(TabOp::Forward(1), 1), Some(8));
        assert_eq!(t.tab_op(TabOp::Set, 3), None);
        assert_eq!(t.tab_op(TabOp::Forward(1), 1), Some(3));
        // Setting one adds to the set rather than replacing it.
        assert_eq!(t.tab_op(TabOp::Forward(1), 3), Some(8));
        // And clearing it takes only that one away.
        assert_eq!(t.tab_op(TabOp::ClearAtCursor, 3), None);
        assert_eq!(t.tab_op(TabOp::Forward(1), 1), Some(8));
    }

    #[test]
    fn motions_move_by_whole_stops_and_saturate_at_the_edges() {
        let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, 24);
        assert_eq!(t.tab_op(TabOp::Forward(2), 0), Some(16));
        // Past the last stop there is nowhere left to go but the last
        // column, and asking for more stops than exist does not overshoot.
        assert_eq!(t.tab_op(TabOp::Forward(9), 0), Some(23));
        assert_eq!(t.tab_op(TabOp::Forward(u16::MAX), 0), Some(23));
        // Back-tab goes to the nearest stop strictly left of the cursor —
        // so a cursor one past the stop it just wrote over returns to it.
        assert_eq!(t.tab_op(TabOp::Back(1), 17), Some(16));
        assert_eq!(t.tab_op(TabOp::Back(1), 16), Some(8));
        assert_eq!(t.tab_op(TabOp::Back(2), 17), Some(8));
        assert_eq!(t.tab_op(TabOp::Back(u16::MAX), 17), Some(0));
    }

    #[test]
    fn clearing_every_stop_leaves_the_two_edges() {
        let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, 24);
        assert_eq!(t.tab_op(TabOp::ClearAll, 0), None);
        assert_eq!(t.tab_op(TabOp::Forward(1), 0), Some(23));
        assert_eq!(t.tab_op(TabOp::Back(1), 20), Some(0));
        // A stop set afterwards is the only one there is.
        assert_eq!(t.tab_op(TabOp::Set, 5), None);
        assert_eq!(t.tab_op(TabOp::Forward(1), 0), Some(5));
    }

    #[test]
    fn a_reset_restores_the_default_every_eighth_set() {
        for reset in [&b"\x1bc"[..], b"\x1b[!p"] {
            let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, 24);
            assert_eq!(t.tab_op(TabOp::ClearAll, 0), None);
            assert_eq!(t.tab_op(TabOp::Set, 3), None);
            assert_eq!(t.tab_op(TabOp::Forward(1), 0), Some(3));
            t.feed(reset);
            assert_eq!(
                t.tab_op(TabOp::Forward(1), 0),
                Some(8),
                "the custom stop must not survive {}",
                printable(reset)
            );
            assert_eq!(t.tab_op(TabOp::Forward(1), 8), Some(16));
        }
    }

    #[test]
    fn a_resize_extends_the_set_without_disturbing_the_stops_it_had() {
        let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, 24);
        assert_eq!(t.tab_op(TabOp::Set, 3), None);
        assert_eq!(t.tab_op(TabOp::ClearAtCursor, 16), None);
        t.set_cols(40);
        // The documented rule: new columns get the every-eighth pattern,
        // and both edits inside the old width survive.
        assert_eq!(t.tab_op(TabOp::Forward(1), 0), Some(3));
        assert_eq!(t.tab_op(TabOp::Forward(1), 8), Some(24), "16 stays cleared");
        assert_eq!(t.tab_op(TabOp::Forward(1), 24), Some(32), "new territory");
        // Narrowing drops the columns that no longer exist, and motion
        // clamps to the width that does.
        t.set_cols(10);
        assert_eq!(t.tab_op(TabOp::Forward(1), 8), Some(9));
    }
}