summaryrefslogtreecommitdiff
path: root/vendor/libghostty-vt/src/terminal/snapshot/screen.zig
blob: d4ef16f731f12aea8d920c7c70d0df612d4a9c77 (plain)
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
//! SCREEN record payload encoding.
//!
//! One SCREEN record represents the live state for one terminal screen. The
//! record is followed immediately by the number of complete PAGE records
//! declared by `page_count`. They are the minimal suffix of native pages needed
//! to cover the active area and are ordered from oldest to newest. A decoder
//! uses the declared count, rather than another record tag, to find the end of
//! the screen's page sequence.
//!
//! The final screen-height rows are the active area. When its boundary falls
//! inside the first encoded page, that page also contains an incidental history
//! prefix. `history_rows` declares the complete logical history extent so a
//! client can size its scrollbar at READY without waiting for HISTORY. A client
//! may expose or ignore the resident overlap carried by SCREEN. The extent is
//! advisory; native row totals remain derived from decoded PAGE records.
//!
//! Screen dimensions are terminal-wide state and are not repeated here. Page
//! capacities, native page IDs and pointers, history availability, selection,
//! viewport, dirty state, and derived semantic-prompt state are also omitted.
//!
//! All integers are unsigned and little-endian.
//!
//! ## Binary Format
//!
//! A SCREEN record is followed immediately by its declared PAGE records:
//!
//! ```text
//!  +----------------------+
//!  | SCREEN record        |
//!  +----------------------+
//!  | PAGE record 0        |
//!  +----------------------+
//!  | ...                  |
//!  +----------------------+
//!  | PAGE record (n - 1)  |
//!  +----------------------+
//!
//!  n = page_count
//! ```
//!
//! The HISTORY record for this screen declares and sends the older complete
//! pages after the terminal becomes ready. The incidental prefix is already
//! present in SCREEN and is not sent again.
//!
//! The SCREEN payload begins with a fixed header. When the header says there is
//! no saved cursor, the payload is:
//!
//! ```text
//!   0 +----------------------+
//!     | Header               |
//!  53 +----------------------+
//!     | Cursor hyperlink     |
//!     | variable             |
//! end +----------------------+
//! ```
//!
//! When a saved cursor is present, it is inserted before the cursor hyperlink:
//!
//! ```text
//!   0 +----------------------+
//!     | Header               |
//!  53 +----------------------+
//!     | Saved cursor         |
//!  76 +----------------------+
//!     | Cursor hyperlink     |
//!     | variable             |
//! end +----------------------+
//! ```
//!
//! The cursor hyperlink begins with a one-byte kind. Zero means no hyperlink
//! and has no following bytes. Kinds one and two use the implicit and explicit
//! hyperlink encodings documented in `hyperlink.zig`.
//!
//! ### Header
//!
//! ```text
//!   0 +----------------------------------+
//!     | Screen key (u16)                 |
//!   2 +----------------------------------+
//!     | Page count (u16)                 |
//!   4 +----------------------------------+
//!     | Logical history rows (u64)       |
//!  12 +----------------------------------+
//!     | Cursor x (u16)                   |
//!  14 +----------------------------------+
//!     | Cursor y (u16)                   |
//!  16 +----------------------------------+
//!     | Cursor visual style (u8)         |
//!  17 +----------------------------------+
//!     | Cursor flags (u8)                |
//!  18 +----------------------------------+
//!     | Concrete cursor pen (Style)      |
//!  34 +----------------------------------+
//!     | Hyperlink implicit counter (u32) |
//!  38 +----------------------------------+
//!     | Current charset (CharsetState)   |
//!  40 +----------------------------------+
//!     | Protected mode (u8)              |
//!  41 +----------------------------------+
//!     | Kitty keyboard stack index (u8)  |
//!  42 +----------------------------------+
//!     | Kitty keyboard stack flags       |
//!     | 8 * u8                           |
//!  50 +----------------------------------+
//!     | Semantic-click kind (u8)         |
//!  51 +----------------------------------+
//!     | Semantic-click value (u8)        |
//!  52 +----------------------------------+
//!     | Saved-cursor-present (u8)        |
//!  53 +----------------------------------+
//! ```
//!
//! The concrete cursor pen uses the fixed style encoding from `style.zig`.
//!
//! ### Cursor flags
//!
//! ```text
//! bit 0 +--------------------------------+
//!       | Pending wrap                   |
//! bit 1 +--------------------------------+
//!       | Protected                      |
//! bit 2 +--------------------------------+
//!       | Semantic content               |
//!       | 2 bits                         |
//! bit 4 +--------------------------------+
//!       | Semantic-content-clear-EOL     |
//! bit 5 +--------------------------------+
//!       | Reserved, zero                 |
//!       | 3 bits                         |
//! bit 8 +--------------------------------+
//! ```
//!
//! ### Charset state
//!
//! The current and saved cursor charset states share this packed layout:
//!
//! ```text
//!  bit 0 +-------------------------------+
//!        | G0 charset                    |
//!        | 2 bits                        |
//!  bit 2 +-------------------------------+
//!        | G1 charset                    |
//!        | 2 bits                        |
//!  bit 4 +-------------------------------+
//!        | G2 charset                    |
//!        | 2 bits                        |
//!  bit 6 +-------------------------------+
//!        | G3 charset                    |
//!        | 2 bits                        |
//!  bit 8 +-------------------------------+
//!        | GL slot                       |
//!        | 2 bits                        |
//! bit 10 +-------------------------------+
//!        | GR slot                       |
//!        | 2 bits                        |
//! bit 12 +-------------------------------+
//!        | Single shift                  |
//!        | 3 bits                        |
//! bit 15 +-------------------------------+
//!        | Reserved, zero                |
//! bit 16 +-------------------------------+
//! ```
//!
//! The Kitty keyboard stack contains its current index followed by all eight
//! flag entries, including disabled entries.
//!
//! ### Saved cursor
//!
//! ```text
//!   0 +-----------------------------+
//!     | Saved cursor x (u16)        |
//!   2 +-----------------------------+
//!     | Saved cursor y (u16)        |
//!   4 +-----------------------------+
//!     | Saved cursor pen (Style)    |
//!  20 +-----------------------------+
//!     | Saved cursor flags (u8)     |
//!  21 +-----------------------------+
//!     | Saved charset state         |
//!  23 +-----------------------------+
//! ```
//!
//! ### Saved cursor flags
//!
//! ```text
//! bit 0 +---------------------------+
//!       | Protected                 |
//! bit 1 +---------------------------+
//!       | Pending wrap              |
//! bit 2 +---------------------------+
//!       | Origin                    |
//! bit 3 +---------------------------+
//!       | Reserved, zero            |
//!       | 5 bits                    |
//! bit 8 +---------------------------+
//! ```
//!
//! Native enum values used below are stable terminal registries. Their wire
//! widths are fixed independently by this payload. Changing those values or
//! any packed bit assignment requires a snapshot version bump.

const std = @import("std");
const build_options = @import("terminal_options");
const Allocator = std.mem.Allocator;
const hyperlink = @import("hyperlink.zig");
const test_fixture = @import("fixture.zig");
const io = @import("io.zig");
const grid = @import("grid.zig");
const page = @import("page.zig");
const record = @import("record.zig");
const style = @import("style.zig");
const terminal_ansi = @import("../ansi.zig");
const terminal_charsets = @import("../charsets.zig");
const terminal_hyperlink = @import("../hyperlink.zig");
const terminal_kitty = @import("../kitty.zig");
const terminal_osc = @import("../osc.zig");
const terminal_page = @import("../page.zig");
const TerminalPageList = @import("../PageList.zig");
const TerminalScreen = @import("../Screen.zig");
const TerminalScreenKey = @import("../ScreenSet.zig").Key;
const terminal_style = @import("../style.zig");

const TerminalHyperlink = terminal_hyperlink.Hyperlink;
const TerminalStyle = terminal_style.Style;

/// Errors possible while encoding fixed SCREEN payload fields.
const PayloadEncodeError = hyperlink.EncodeError || error{
    InvalidCursorFlags,
    InvalidCharsetState,
    InvalidKittyKeyboardIndex,
    InvalidKittyKeyboardFlags,
    InvalidSavedCursorFlags,
};

/// Errors possible while encoding a SCREEN and its complete PAGE sequence.
pub const EncodeError = Allocator.Error || PayloadEncodeError || page.EncodeError || error{
    /// The active area spans more pages than the SCREEN header can declare.
    PageCountOverflow,
};

/// Encode one SCREEN and its minimal suffix of complete native pages.
///
/// The suffix begins with the page containing the active area's first row and
/// ends with the newest page. Completed records may already be emitted if a
/// later record fails; the missing READY marker makes that prefix invalid.
pub fn encode(
    screen: *const TerminalScreen,
    key: TerminalScreenKey,
    destination: *record.Writer,
) EncodeError!void {
    // The active top may fall inside this page, leaving an incidental history
    // prefix. Every earlier complete page is history and is omitted.
    const first = screen.pages.getTopLeft(.active).node;
    var page_count: usize = 0;
    var node: ?@TypeOf(first) = first;
    while (node) |current| : (node = current.next) page_count += 1;
    const encoded_page_count = std.math.cast(
        u16,
        page_count,
    ) orelse return error.PageCountOverflow;

    // SCREEN declares exactly how many immediately following PAGE records
    // belong to it.
    {
        const payload = destination.begin(.screen);
        errdefer destination.cancel();
        try encodePayload(
            screen,
            key,
            encoded_page_count,
            payload,
        );
        try destination.finish();
    }

    // Active pages are resident today, but use the representation-safe access
    // path so a future PageList compression-policy change cannot turn this
    // wire encoder's optimization invariant into undefined behavior.
    node = first;
    while (node) |current| : (node = current.next) {
        var preserved = try current.pagePreservingState(screen.alloc);
        defer preserved.deinit();
        try page.encode(preserved.page(), destination);
    }
}

/// Errors possible while restoring a SCREEN and its declared PAGE sequence.
pub const DecodeError = PayloadDecodeError ||
    page.DecodeError ||
    record.Reader.InitError ||
    record.Reader.FinishError ||
    TerminalPageList.Builder.FinishError ||
    TerminalPageList.IncreaseCapacityError ||
    error{
        /// The next record is valid but is not a SCREEN.
        UnexpectedRecordTag,

        /// A SCREEN must declare at least one PAGE.
        InvalidPageCount,
    };

/// One decoded SCREEN sequence and the native screen identified by its header.
pub const Decoded = struct {
    key: TerminalScreenKey,
    /// Expected history extent at READY, including resident SCREEN overlap.
    history_rows: u64,
    screen: TerminalScreen,

    /// Release the decoded native screen before ownership is transferred.
    pub fn deinit(self: *Decoded) void {
        self.screen.deinit();
        self.* = undefined;
    }
};

/// Restore one SCREEN and its declared PAGE records into native terminal state.
///
/// The caller supplies terminal-wide dimensions and policy. The record sequence
/// is decoded transactionally: on failure, all page, pin, hyperlink, and
/// temporary allocations are released and no partially restored Screen escapes.
/// The returned key selects the ScreenSet slot that owns the decoded screen.
pub fn decode(
    source: *std.Io.Reader,
    io_: std.Io,
    alloc: Allocator,
    options: TerminalScreen.Options,
) DecodeError!Decoded {
    // Decode and finish the self-contained SCREEN record before consuming any
    // of the PAGE records which follow it.
    var record_reader: record.Reader = undefined;
    try record_reader.init(source);
    if (record_reader.header.tag != .screen) {
        return error.UnexpectedRecordTag;
    }

    // The optional saved cursor and cursor hyperlink are both part of the
    // SCREEN payload. Keep ownership of the decoded hyperlink locally until it
    // has been copied into the native Screen.
    const payload_reader = record_reader.payloadReader();
    const header = try Header.decode(payload_reader);
    const saved_cursor = if (header.saved_cursor_present)
        try SavedCursor.decode(payload_reader)
    else
        null;
    var cursor_hyperlink = try decodeCursorHyperlink(
        payload_reader,
        alloc,
    );
    defer if (cursor_hyperlink) |*value| value.deinit(alloc);
    try record_reader.finish();

    const key = header.key;
    if (header.page_count == 0) return error.InvalidPageCount;

    // Dimensions are terminal-wide state supplied by the enclosing snapshot.
    // Validate them, and all cursor invariants which depend on them, before
    // allocating the declared pages.
    if (options.cols == 0 or options.rows == 0) {
        return error.InvalidDimensions;
    }

    // Build the native page list transactionally. Alternate screens never
    // retain scrollback, while primary screens inherit the caller's limits.
    var result: TerminalScreen = result: {
        var builder = try TerminalPageList.Builder.init(alloc, .{
            .cols = options.cols,
            .rows = options.rows,
            .max_size = if (key == .alternate)
                0
            else
                options.max_scrollback_bytes,
            .max_lines = if (key == .alternate)
                0
            else
                options.max_scrollback_lines,
        });
        defer builder.deinit();

        // Allocate each PAGE at its declared capacity and decode directly into
        // builder-owned storage, avoiding an intermediate page representation.
        for (0..header.page_count) |_| {
            var decoder: page.Decoder = undefined;
            try decoder.init(source);
            const native_page = try builder.allocatePage(decoder.capacity());
            try decoder.decode(native_page, alloc);
        }

        // Finishing validates that the decoded suffix covers the active area
        // and establishes the PageList's active viewport.
        var pages = try builder.finish();
        errdefer pages.deinit();

        // Convert the payload-relative cursor position into the tracked native
        // pin and page-local row/cell pointers required by TerminalScreen.
        const cursor: TerminalScreen.Cursor = cursor: {
            const y = @min(header.cursor_y, options.rows - 1);

            // The active area can temporarily contain mixed-width pages after
            // a reflow. Locate the row at column zero, then clamp the encoded
            // x coordinate to the width of that physical page.
            const row_pin = pages.pin(.{ .active = .{ .y = y } }) orelse unreachable;
            const x = @min(header.cursor_x, row_pin.node.cols() - 1);
            const pin = try pages.trackPin(.{
                .node = row_pin.node,
                .x = x,
                .y = row_pin.y,
            });
            const rac = pin.rowAndCell();

            break :cursor .{
                .x = x,
                .y = y,
                .cursor_style = header.cursor_style,
                .pending_wrap = header.cursor_flags.pending_wrap and
                    x == row_pin.node.cols() - 1,
                .protected = header.cursor_flags.protected,
                .style = header.cursor_pen,
                .hyperlink_implicit_id = header.hyperlink_implicit_id,
                .semantic_content = header.cursor_flags.semantic_content,
                .semantic_content_clear_eol = header.cursor_flags
                    .semantic_content_clear_eol,
                .page_pin = pin,
                .page_row = rac.row,
                .page_cell = rac.cell,
            };
        };

        // Assemble the remaining native state from stable snapshot registries.
        // Derived state and page-local table references are repaired below.
        break :result .{
            .io = io_,
            .alloc = alloc,
            .pages = pages,
            .no_scrollback = key == .alternate or
                options.max_scrollback_bytes == 0,
            .cursor = cursor,
            .saved_cursor = if (saved_cursor) |value|
                value.terminal(options.cols, options.rows)
            else
                null,
            .charset = header.charset,
            .protected_mode = header.protected_mode,
            .kitty_keyboard = header.kitty_keyboard.terminal(),
            .semantic_prompt = .{
                .seen = false,
                .click = header.semantic_click,
            },
        };
    };
    errdefer result.deinit();

    // Reinsert the concrete cursor style into its page-local style table. This
    // existing Screen path grows or splits the page when the decoded table is
    // already full.
    try result.manualStyleUpdate();

    // Reinsert the cursor hyperlink into its page-local hyperlink table. For an
    // implicit link, temporarily seed the counter with the encoded link ID,
    // then restore the independent next-ID counter from the header.
    if (cursor_hyperlink) |value| {
        switch (value.id) {
            .explicit => |id| try result.startHyperlink(value.uri, id),
            .implicit => |id| {
                result.cursor.hyperlink_implicit_id = id;
                try result.startHyperlink(value.uri, null);
                result.cursor.hyperlink_implicit_id =
                    header.hyperlink_implicit_id;
            },
        }
    }

    // `seen` is derived state. Only resident prompt metadata participates
    // because omitted history is outside the restored Screen model.
    result.semantic_prompt.seen = seen: {
        if (result.cursor.semantic_content == .prompt) break :seen true;

        var node = result.pages.getTopLeft(.screen).node;
        while (true) {
            const native_page = node.pageAssumeResident();
            const rows = native_page.rows.ptr(
                native_page.memory,
            )[0..native_page.size.rows];
            for (rows) |row| {
                if (row.semantic_prompt != .none) break :seen true;

                const cells = row.cells.ptr(
                    native_page.memory,
                )[0..native_page.size.cols];
                for (cells) |cell| {
                    if (cell.semantic_content == .prompt) break :seen true;
                }
            }

            node = node.next orelse break :seen false;
        }

        unreachable;
    };

    // Kitty image payloads are outside this record, but the restored Screen
    // must still receive the caller's terminal-wide storage policy.
    if (comptime build_options.kitty_graphics) {
        result.kitty_images.setLimit(
            io_,
            alloc,
            &result,
            options.kitty_image_storage_limit,
        );
        result.kitty_images.image_limits = options.kitty_image_loading_limits;
    }

    // All fallible reconstruction is complete; verify the native invariants
    // before transferring ownership to the caller.
    result.pages.assertIntegrity();
    result.assertIntegrity();
    return .{
        .key = key,
        .history_rows = header.history_rows,
        .screen = result,
    };
}

/// Errors possible while decoding fixed SCREEN payload fields.
const PayloadDecodeError = std.Io.Reader.Error || error{InvalidKey};

/// Flags encoded after the cursor's visual shape.
pub const CursorFlags = packed struct(u8) {
    pending_wrap: bool = false,
    protected: bool = false,
    semantic_content: terminal_page.Cell.SemanticContent = .output,
    semantic_content_clear_eol: bool = false,
    _padding: u3 = 0,

    fn init(cursor: *const TerminalScreen.Cursor) CursorFlags {
        return .{
            .pending_wrap = cursor.pending_wrap,
            .protected = cursor.protected,
            .semantic_content = cursor.semantic_content,
            .semantic_content_clear_eol = cursor
                .semantic_content_clear_eol,
        };
    }

    /// Decode the cursor flag registry, normalizing unknown semantic state.
    pub fn decode(reader: *std.Io.Reader) std.Io.Reader.Error!CursorFlags {
        const raw = try reader.takeByte();
        const bits: CursorFlags = @bitCast(raw);
        const semantic_content_raw: u2 = @truncate(raw >> @bitOffsetOf(CursorFlags, "semantic_content"));
        const semantic_content = std.enums.fromInt(
            terminal_page.Cell.SemanticContent,
            semantic_content_raw,
        ) orelse .output;

        return .{
            .pending_wrap = bits.pending_wrap,
            .protected = bits.protected,
            .semantic_content = semantic_content,
            .semantic_content_clear_eol = bits.semantic_content_clear_eol,
        };
    }
};

/// The packed wire bits shared by current and saved cursor charset state.
///
/// Native enum values are stable, but their backing type is `c_int` in C ABI
/// builds. The wire therefore stores only checked integer values at its fixed
/// bit widths.
const CharsetBits = packed struct(u16) {
    g0: u2 = 0,
    g1: u2 = 0,
    g2: u2 = 0,
    g3: u2 = 0,
    gl: u2 = 0,
    gr: u2 = 2,
    single_shift: u3 = 0,
    _padding: u1 = 0,
};

fn enumFromInt(comptime T: type, raw: anytype) ?T {
    const Tag = @typeInfo(T).@"enum".tag_type;
    const value = std.math.cast(Tag, raw) orelse return null;
    return std.enums.fromInt(T, value);
}

fn encodeCharsetState(
    value: TerminalScreen.CharsetState,
) error{InvalidCharsetState}!u16 {
    const g0 = std.math.cast(
        u2,
        @intFromEnum(value.charsets.get(.G0)),
    ) orelse return error.InvalidCharsetState;
    const g1 = std.math.cast(
        u2,
        @intFromEnum(value.charsets.get(.G1)),
    ) orelse return error.InvalidCharsetState;
    const g2 = std.math.cast(
        u2,
        @intFromEnum(value.charsets.get(.G2)),
    ) orelse return error.InvalidCharsetState;
    const g3 = std.math.cast(
        u2,
        @intFromEnum(value.charsets.get(.G3)),
    ) orelse return error.InvalidCharsetState;
    const gl = std.math.cast(
        u2,
        @intFromEnum(value.gl),
    ) orelse return error.InvalidCharsetState;
    const gr = std.math.cast(
        u2,
        @intFromEnum(value.gr),
    ) orelse return error.InvalidCharsetState;
    const single_shift: u3 = if (value.single_shift) |slot| single_shift: {
        const raw = std.math.cast(
            u2,
            @intFromEnum(slot),
        ) orelse return error.InvalidCharsetState;
        break :single_shift @as(u3, raw) + 1;
    } else 0;

    const bits: CharsetBits = .{
        .g0 = g0,
        .g1 = g1,
        .g2 = g2,
        .g3 = g3,
        .gl = gl,
        .gr = gr,
        .single_shift = single_shift,
    };
    return @bitCast(bits);
}

fn decodeCharsetState(
    raw: u16,
) TerminalScreen.CharsetState {
    const bits: CharsetBits = @bitCast(raw);

    var result: TerminalScreen.CharsetState = .{};
    result.gl = enumFromInt(
        terminal_charsets.Slots,
        bits.gl,
    ) orelse result.gl;
    result.gr = enumFromInt(
        terminal_charsets.Slots,
        bits.gr,
    ) orelse result.gr;
    result.single_shift = if (bits.single_shift == 0)
        null
    else if (bits.single_shift <= 4)
        enumFromInt(
            terminal_charsets.Slots,
            bits.single_shift - 1,
        )
    else
        null;
    result.charsets.set(
        .G0,
        enumFromInt(
            terminal_charsets.Charset,
            bits.g0,
        ) orelse .utf8,
    );
    result.charsets.set(
        .G1,
        enumFromInt(
            terminal_charsets.Charset,
            bits.g1,
        ) orelse .utf8,
    );
    result.charsets.set(
        .G2,
        enumFromInt(
            terminal_charsets.Charset,
            bits.g2,
        ) orelse .utf8,
    );
    result.charsets.set(
        .G3,
        enumFromInt(
            terminal_charsets.Charset,
            bits.g3,
        ) orelse .utf8,
    );
    return result;
}

/// The complete fixed-size Kitty keyboard stack.
pub const KittyKeyboard = struct {
    index: u8 = 0,
    flags: [8]Flags = @splat(.{}),

    /// One byte in the fixed Kitty keyboard flag stack.
    pub const Flags = packed struct(u8) {
        disambiguate: bool = false,
        report_events: bool = false,
        report_alternates: bool = false,
        report_all: bool = false,
        report_associated: bool = false,
        _padding: u3 = 0,

        /// Decode one Kitty keyboard flag byte, ignoring reserved bits.
        pub fn decode(reader: *std.Io.Reader) std.Io.Reader.Error!Flags {
            var result: Flags = @bitCast(try reader.takeByte());
            result._padding = 0;
            return result;
        }
    };

    fn init(value: terminal_kitty.KeyFlagStack) KittyKeyboard {
        var result: KittyKeyboard = .{ .index = value.idx };
        for (value.flags, &result.flags) |native, *snapshot| {
            snapshot.* = .{
                .disambiguate = native.disambiguate,
                .report_events = native.report_events,
                .report_alternates = native.report_alternates,
                .report_all = native.report_all,
                .report_associated = native.report_associated,
            };
        }
        return result;
    }

    fn terminal(self: KittyKeyboard) terminal_kitty.KeyFlagStack {
        var result: terminal_kitty.KeyFlagStack = .{
            .idx = @intCast(self.index),
        };
        for (self.flags, &result.flags) |snapshot, *native| {
            native.* = .{
                .disambiguate = snapshot.disambiguate,
                .report_events = snapshot.report_events,
                .report_alternates = snapshot.report_alternates,
                .report_all = snapshot.report_all,
                .report_associated = snapshot.report_associated,
            };
        }
        return result;
    }

    /// Decode the complete fixed Kitty keyboard stack.
    pub fn decode(reader: *std.Io.Reader) std.Io.Reader.Error!KittyKeyboard {
        const index_raw = try reader.takeByte();
        const index = if (index_raw < 8) index_raw else 0;

        var flags: [8]Flags = undefined;
        for (&flags) |*entry| entry.* = try Flags.decode(reader);
        return .{ .index = index, .flags = flags };
    }
};

/// Decode semantic-click state, falling back to disabled for unknown values.
fn decodeSemanticClick(
    reader: *std.Io.Reader,
) std.Io.Reader.Error!TerminalScreen.SemanticPrompt.SemanticClick {
    const kind = enumFromInt(
        TerminalScreen.SemanticPrompt.SemanticClickKind,
        try reader.takeByte(),
    );
    const value = try reader.takeByte();

    return switch (kind orelse return .none) {
        .none => .none,
        .click_events => .{ .click_events = enumFromInt(
            terminal_osc.semantic_prompt.ClickEvents,
            value,
        ) orelse return .none },
        .cl => .{ .cl = enumFromInt(
            terminal_osc.semantic_prompt.Click,
            value,
        ) orelse return .none },
    };
}

/// The optional fixed-size saved cursor state.
pub const SavedCursor = struct {
    /// Number of bytes written by `encode`, calculated using the encoder.
    pub const len = computeLen();

    comptime {
        std.debug.assert(len == 23);
    }

    x: u16,
    y: u16,
    pen: TerminalStyle,
    flags: Flags,
    charset: TerminalScreen.CharsetState,

    /// Flags encoded with an optional saved cursor.
    pub const Flags = packed struct(u8) {
        protected: bool = false,
        pending_wrap: bool = false,
        origin: bool = false,
        _padding: u5 = 0,

        /// Decode saved cursor flags, ignoring reserved bits.
        pub fn decode(reader: *std.Io.Reader) std.Io.Reader.Error!Flags {
            var result: Flags = @bitCast(try reader.takeByte());
            result._padding = 0;
            return result;
        }
    };

    fn init(value: TerminalScreen.SavedCursor) SavedCursor {
        return .{
            .x = value.x,
            .y = value.y,
            .pen = value.style,
            .flags = .{
                .protected = value.protected,
                .pending_wrap = value.pending_wrap,
                .origin = value.origin,
            },
            .charset = value.charset,
        };
    }

    fn terminal(
        self: SavedCursor,
        cols: u16,
        rows: u16,
    ) TerminalScreen.SavedCursor {
        const x = @min(self.x, cols - 1);
        return .{
            .x = x,
            .y = @min(self.y, rows - 1),
            .style = self.pen,
            .protected = self.flags.protected,
            .pending_wrap = self.flags.pending_wrap and x == cols - 1,
            .origin = self.flags.origin,
            .charset = self.charset,
        };
    }

    /// Encode one optional saved cursor value.
    pub fn encode(
        self: SavedCursor,
        writer: *std.Io.Writer,
    ) PayloadEncodeError!void {
        if (self.flags._padding != 0) {
            return error.InvalidSavedCursorFlags;
        }
        const charset = try encodeCharsetState(self.charset);

        try io.writeInt(writer, u16, self.x);
        try io.writeInt(writer, u16, self.y);
        try style.encode(self.pen, writer);
        try writer.writeByte(@bitCast(self.flags));
        try io.writeInt(writer, u16, charset);
    }

    /// Decode and validate one optional saved cursor value.
    pub fn decode(reader: *std.Io.Reader) PayloadDecodeError!SavedCursor {
        return .{
            .x = try io.readInt(reader, u16),
            .y = try io.readInt(reader, u16),
            .pen = (try style.decodeOrNull(reader)) orelse .{},
            .flags = try Flags.decode(reader),
            .charset = decodeCharsetState(
                try io.readInt(reader, u16),
            ),
        };
    }

    fn computeLen() usize {
        comptime {
            var buf: [128]u8 = undefined;
            var writer: std.Io.Writer = .fixed(&buf);
            const value: SavedCursor = .{
                .x = 0,
                .y = 0,
                .pen = .{},
                .flags = .{},
                .charset = .{},
            };
            value.encode(&writer) catch unreachable;
            return writer.end;
        }
    }
};

/// The fixed fields at the start of every SCREEN payload.
pub const Header = struct {
    /// Number of bytes written by `encode`, calculated using the encoder.
    pub const len = computeLen();

    comptime {
        std.debug.assert(len == 53);
    }

    key: TerminalScreenKey,
    /// Complete pages in the minimal suffix covering the active area.
    page_count: u16,
    /// Advisory logical rows before the active area, including resident
    /// SCREEN overlap.
    history_rows: u64,
    cursor_x: u16,
    cursor_y: u16,
    cursor_style: TerminalScreen.CursorStyle,
    cursor_flags: CursorFlags,
    cursor_pen: TerminalStyle,
    hyperlink_implicit_id: u32,
    charset: TerminalScreen.CharsetState,
    protected_mode: terminal_ansi.ProtectedMode,
    kitty_keyboard: KittyKeyboard,
    semantic_click: TerminalScreen.SemanticPrompt.SemanticClick,
    saved_cursor_present: bool,

    /// Initialize the fixed header from one native screen.
    fn init(
        screen: *const TerminalScreen,
        key: TerminalScreenKey,
        page_count: u16,
    ) Header {
        return .{
            .key = key,
            .page_count = page_count,
            .history_rows = @intCast(
                screen.pages.total_rows - screen.pages.rows,
            ),
            .cursor_x = screen.cursor.x,
            .cursor_y = screen.cursor.y,
            .cursor_style = screen.cursor.cursor_style,
            .cursor_flags = .init(&screen.cursor),
            .cursor_pen = screen.cursor.style,
            .hyperlink_implicit_id = screen.cursor.hyperlink_implicit_id,
            .charset = screen.charset,
            .protected_mode = screen.protected_mode,
            .kitty_keyboard = .init(screen.kitty_keyboard),
            .semantic_click = screen.semantic_prompt.click,
            .saved_cursor_present = screen.saved_cursor != null,
        };
    }

    /// Encode the fixed SCREEN payload header field by field.
    pub fn encode(
        self: Header,
        writer: *std.Io.Writer,
    ) PayloadEncodeError!void {
        // Validate packed cursor state before writing any bytes.
        if (self.cursor_flags._padding != 0) {
            return error.InvalidCursorFlags;
        }

        // Validate and narrow native charset enum values before writing.
        const charset = try encodeCharsetState(self.charset);

        // Validate the complete Kitty keyboard stack.
        if (self.kitty_keyboard.index >= self.kitty_keyboard.flags.len) {
            return error.InvalidKittyKeyboardIndex;
        }
        for (self.kitty_keyboard.flags) |flags| {
            if (flags._padding != 0) {
                return error.InvalidKittyKeyboardFlags;
            }
        }

        // Screen identity, expected history extent, and cursor position.
        try io.writeInt(writer, u16, @intCast(@intFromEnum(self.key)));
        try io.writeInt(writer, u16, self.page_count);
        try io.writeInt(writer, u64, self.history_rows);
        try io.writeInt(writer, u16, self.cursor_x);
        try io.writeInt(writer, u16, self.cursor_y);

        // Current cursor rendering state.
        try writer.writeByte(@intCast(@intFromEnum(self.cursor_style)));
        try writer.writeByte(@bitCast(self.cursor_flags));
        try style.encode(self.cursor_pen, writer);
        try io.writeInt(writer, u32, self.hyperlink_implicit_id);

        // Charset and selective-erase state.
        try io.writeInt(writer, u16, charset);
        try writer.writeByte(@intCast(@intFromEnum(self.protected_mode)));

        // Keyboard modes and semantic-click state.
        try writer.writeByte(self.kitty_keyboard.index);
        for (self.kitty_keyboard.flags) |flags| {
            try writer.writeByte(@bitCast(flags));
        }
        try writer.writeByte(@intCast(@intFromEnum(
            std.meta.activeTag(self.semantic_click),
        )));
        switch (self.semantic_click) {
            .none => try writer.writeByte(0),
            .click_events => |value| try writer.writeByte(
                @intCast(@intFromEnum(value)),
            ),
            .cl => |value| try writer.writeByte(
                @intCast(@intFromEnum(value)),
            ),
        }

        // Presence of the optional saved-cursor suffix.
        try writer.writeByte(@intFromBool(self.saved_cursor_present));
    }

    /// Decode the fixed SCREEN payload header.
    ///
    /// The screen key remains structural because it routes the following PAGE
    /// sequence. Unknown semantic fields use native defaults instead.
    pub fn decode(reader: *std.Io.Reader) PayloadDecodeError!Header {
        // Screen identity, expected history extent, and cursor position.
        const key = enumFromInt(
            TerminalScreenKey,
            try io.readInt(reader, u16),
        ) orelse return error.InvalidKey;
        const page_count = try io.readInt(reader, u16);
        const history_rows = try io.readInt(reader, u64);
        const cursor_x = try io.readInt(reader, u16);
        const cursor_y = try io.readInt(reader, u16);

        // Current cursor rendering state.
        const cursor_style = enumFromInt(
            TerminalScreen.CursorStyle,
            try reader.takeByte(),
        ) orelse .block;
        const cursor_flags = try CursorFlags.decode(reader);
        const cursor_pen: TerminalStyle =
            (try style.decodeOrNull(reader)) orelse .{};
        const hyperlink_implicit_id = try io.readInt(reader, u32);

        // Charset and selective-erase state.
        const charset = decodeCharsetState(
            try io.readInt(reader, u16),
        );
        const protected_mode = enumFromInt(
            terminal_ansi.ProtectedMode,
            try reader.takeByte(),
        ) orelse .off;

        // Keyboard modes and semantic-click state.
        const kitty_keyboard = try KittyKeyboard.decode(reader);
        const semantic_click = try decodeSemanticClick(reader);

        // Presence of the optional saved-cursor suffix.
        const saved_cursor_present = try reader.takeByte() != 0;

        return .{
            .key = key,
            .page_count = page_count,
            .history_rows = history_rows,
            .cursor_x = cursor_x,
            .cursor_y = cursor_y,

            .cursor_style = cursor_style,
            .cursor_flags = cursor_flags,
            .cursor_pen = cursor_pen,
            .hyperlink_implicit_id = hyperlink_implicit_id,

            .charset = charset,
            .protected_mode = protected_mode,

            .kitty_keyboard = kitty_keyboard,
            .semantic_click = semantic_click,

            .saved_cursor_present = saved_cursor_present,
        };
    }

    fn computeLen() usize {
        comptime {
            var buf: [128]u8 = undefined;
            var writer: std.Io.Writer = .fixed(&buf);
            const value: Header = .{
                .key = .primary,
                .page_count = 0,
                .history_rows = 0,
                .cursor_x = 0,
                .cursor_y = 0,
                .cursor_style = .bar,
                .cursor_flags = .{},
                .cursor_pen = .{},
                .hyperlink_implicit_id = 0,
                .charset = .{},
                .protected_mode = .off,
                .kitty_keyboard = .{},
                .semantic_click = .none,
                .saved_cursor_present = false,
            };
            value.encode(&writer) catch unreachable;
            return writer.end;
        }
    }
};

/// Encode the SCREEN payload, excluding its following PAGE records.
fn encodePayload(
    screen: *const TerminalScreen,
    key: TerminalScreenKey,
    page_count: u16,
    writer: *std.Io.Writer,
) PayloadEncodeError!void {
    try Header.init(screen, key, page_count).encode(writer);

    if (screen.saved_cursor) |saved_cursor| {
        try SavedCursor.init(saved_cursor).encode(writer);
    }

    const cursor_hyperlink: ?TerminalHyperlink =
        if (screen.cursor.hyperlink) |entry| entry.* else null;
    try encodeCursorHyperlink(cursor_hyperlink, writer);
}

/// The variable cursor hyperlink at the end of every SCREEN payload.
pub const CursorHyperlink = ?TerminalHyperlink;

/// Encode the optional cursor hyperlink at the end of a SCREEN payload.
pub fn encodeCursorHyperlink(
    value: CursorHyperlink,
    writer: *std.Io.Writer,
) hyperlink.EncodeError!void {
    if (value) |entry| return hyperlink.encode(entry, writer);
    try writer.writeByte(0);
}

/// Decode one allocator-owned optional cursor hyperlink.
///
/// The caller owns a non-null returned value and must call `Hyperlink.deinit`.
pub fn decodeCursorHyperlink(
    reader: *std.Io.Reader,
    alloc: Allocator,
) std.Io.Reader.Error!CursorHyperlink {
    if (try reader.peekByte() == 0) {
        _ = try reader.takeByte();
        return null;
    }

    return hyperlink.decode(reader, alloc) catch |err| switch (err) {
        error.ReadFailed => error.ReadFailed,

        // The cursor hyperlink is the final SCREEN payload field, so its
        // record boundary lets us discard an invalid or unrepresentable value
        // without losing the following PAGE sequence.
        error.EndOfStream,
        error.OutOfMemory,
        error.InvalidKind,
        error.InvalidUri,
        error.InvalidExplicitId,
        => {
            _ = try reader.discardRemaining();
            return null;
        },
    };
}

const test_header_fixture = test_fixture.parse(@embedFile("testdata/screen-header-v1.hex"));
const test_saved_cursor_fixture = test_fixture.parse(@embedFile("testdata/screen-saved-cursor-v1.hex"));

fn testCharsetState() TerminalScreen.CharsetState {
    var result: TerminalScreen.CharsetState = .{
        .gl = .G1,
        .gr = .G3,
        .single_shift = .G2,
    };
    result.charsets.set(.G0, .utf8);
    result.charsets.set(.G1, .ascii);
    result.charsets.set(.G2, .british);
    result.charsets.set(.G3, .dec_special);
    return result;
}

fn testHeader() Header {
    return .{
        .key = .alternate,
        .page_count = 0x0203,
        .history_rows = 0x0102030405060708,
        .cursor_x = 0x0405,
        .cursor_y = 0x0607,
        .cursor_style = .block_hollow,
        .cursor_flags = .{
            .pending_wrap = true,
            .semantic_content = .prompt,
            .semantic_content_clear_eol = true,
        },
        .cursor_pen = .{
            .fg_color = .none,
            .bg_color = .{ .palette = 0x7f },
            .underline_color = .{ .rgb = .{
                .r = 0x12,
                .g = 0x34,
                .b = 0x56,
            } },
            .flags = .{
                .bold = true,
                .italic = true,
                .faint = true,
                .blink = true,
                .inverse = true,
                .invisible = true,
                .strikethrough = true,
                .overline = true,
                .underline = .curly,
            },
        },
        .hyperlink_implicit_id = 0x0a0b0c0d,
        .charset = testCharsetState(),
        .protected_mode = .dec,
        .kitty_keyboard = .{
            .index = 7,
            .flags = .{
                .{ .disambiguate = true },
                .{ .report_events = true },
                .{ .report_alternates = true },
                .{ .report_all = true },
                .{ .report_associated = true },
                .{
                    .disambiguate = true,
                    .report_events = true,
                    .report_alternates = true,
                    .report_all = true,
                    .report_associated = true,
                },
                .{},
                .{
                    .disambiguate = true,
                    .report_associated = true,
                },
            },
        },
        .semantic_click = .{ .cl = .smart_vertical },
        .saved_cursor_present = true,
    };
}

fn testSavedCursor() SavedCursor {
    return .{
        .x = 0x0102,
        .y = 0x0304,
        .pen = .{},
        .flags = .{
            .protected = true,
            .pending_wrap = true,
            .origin = true,
        },
        .charset = testCharsetState(),
    };
}

test "SCREEN header golden encoding and decoding" {
    var encoded: [Header.len]u8 = undefined;
    var writer: std.Io.Writer = .fixed(&encoded);
    try testHeader().encode(&writer);

    try test_fixture.expectEqual(
        .bytes,
        "src/terminal/snapshot/testdata/screen-header-v1.hex",
        "snapshot_fixture-screen-header-v1.hex",
        &test_header_fixture,
        writer.buffered(),
    );
    try std.testing.expectEqual(Header.len, test_header_fixture.len);

    var source: std.Io.Reader = .fixed(&test_header_fixture);
    var buffer: [1]u8 = undefined;
    var limited = source.limited(.unlimited, &buffer);

    try std.testing.expectEqualDeep(
        testHeader(),
        try Header.decode(&limited.interface),
    );
}

test "native enum values used by the SCREEN format" {
    const keys = [_]TerminalScreenKey{ .primary, .alternate };
    for (keys, 0..) |value, expected| {
        try std.testing.expectEqual(
            expected,
            @as(usize, @intCast(@intFromEnum(value))),
        );
    }

    const cursor_styles = [_]TerminalScreen.CursorStyle{
        .bar,
        .block,
        .underline,
        .block_hollow,
    };
    for (cursor_styles, 0..) |value, expected| {
        try std.testing.expectEqual(
            expected,
            @as(usize, @intCast(@intFromEnum(value))),
        );
    }

    const semantic_contents = [_]terminal_page.Cell.SemanticContent{
        .output,
        .input,
        .prompt,
    };
    for (semantic_contents, 0..) |value, expected| {
        try std.testing.expectEqual(
            expected,
            @as(usize, @intCast(@intFromEnum(value))),
        );
    }

    const charsets = [_]terminal_charsets.Charset{
        .utf8,
        .ascii,
        .british,
        .dec_special,
    };
    for (charsets, 0..) |value, expected| {
        try std.testing.expectEqual(
            expected,
            @as(usize, @intCast(@intFromEnum(value))),
        );
    }

    const slots = [_]terminal_charsets.Slots{ .G0, .G1, .G2, .G3 };
    for (slots, 0..) |value, expected| {
        try std.testing.expectEqual(
            expected,
            @as(usize, @intCast(@intFromEnum(value))),
        );
    }

    const protected_modes = [_]terminal_ansi.ProtectedMode{
        .off,
        .iso,
        .dec,
    };
    for (protected_modes, 0..) |value, expected| {
        try std.testing.expectEqual(
            expected,
            @as(usize, @intCast(@intFromEnum(value))),
        );
    }

    const click_kinds = [_]TerminalScreen.SemanticPrompt.SemanticClickKind{
        .none,
        .click_events,
        .cl,
    };
    for (click_kinds, 0..) |value, expected| {
        try std.testing.expectEqual(
            expected,
            @as(usize, @intCast(@intFromEnum(value))),
        );
    }

    const click_events = [_]terminal_osc.semantic_prompt.ClickEvents{
        .absolute,
        .relative,
    };
    for (click_events, 0..) |value, expected| {
        try std.testing.expectEqual(
            expected,
            @as(usize, @intCast(@intFromEnum(value))),
        );
    }

    const clicks = [_]terminal_osc.semantic_prompt.Click{
        .line,
        .multiple,
        .conservative_vertical,
        .smart_vertical,
    };
    for (clicks, 0..) |value, expected| {
        try std.testing.expectEqual(
            expected,
            @as(usize, @intCast(@intFromEnum(value))),
        );
    }
}

test "cursor, Kitty, and saved cursor flag bit layouts" {
    const CursorCase = struct {
        value: CursorFlags,
        expected: u8,
    };
    const cursor_cases = [_]CursorCase{
        .{ .value = .{ .pending_wrap = true }, .expected = 1 << 0 },
        .{ .value = .{ .protected = true }, .expected = 1 << 1 },
        .{
            .value = .{ .semantic_content = .input },
            .expected = 1 << 2,
        },
        .{
            .value = .{ .semantic_content = .prompt },
            .expected = 2 << 2,
        },
        .{
            .value = .{ .semantic_content_clear_eol = true },
            .expected = 1 << 4,
        },
    };
    for (cursor_cases) |case| {
        try std.testing.expectEqual(
            case.expected,
            @as(u8, @bitCast(case.value)),
        );
    }

    const KittyCase = struct {
        value: KittyKeyboard.Flags,
        expected: u8,
    };
    const kitty_cases = [_]KittyCase{
        .{ .value = .{ .disambiguate = true }, .expected = 1 << 0 },
        .{ .value = .{ .report_events = true }, .expected = 1 << 1 },
        .{
            .value = .{ .report_alternates = true },
            .expected = 1 << 2,
        },
        .{ .value = .{ .report_all = true }, .expected = 1 << 3 },
        .{
            .value = .{ .report_associated = true },
            .expected = 1 << 4,
        },
    };
    for (kitty_cases) |case| {
        try std.testing.expectEqual(
            case.expected,
            @as(u8, @bitCast(case.value)),
        );
    }

    const SavedCase = struct {
        value: SavedCursor.Flags,
        expected: u8,
    };
    const saved_cases = [_]SavedCase{
        .{ .value = .{ .protected = true }, .expected = 1 << 0 },
        .{ .value = .{ .pending_wrap = true }, .expected = 1 << 1 },
        .{ .value = .{ .origin = true }, .expected = 1 << 2 },
    };
    for (saved_cases) |case| {
        try std.testing.expectEqual(
            case.expected,
            @as(u8, @bitCast(case.value)),
        );
    }
}

test "header encoding rejects invalid state" {
    var encoded: [Header.len]u8 = undefined;

    var invalid_cursor_flags = testHeader();
    invalid_cursor_flags.cursor_flags._padding = 1;
    var cursor_flags_writer: std.Io.Writer = .fixed(&encoded);
    try std.testing.expectError(
        error.InvalidCursorFlags,
        invalid_cursor_flags.encode(&cursor_flags_writer),
    );

    var invalid_kitty_index = testHeader();
    invalid_kitty_index.kitty_keyboard.index = 8;
    var kitty_index_writer: std.Io.Writer = .fixed(&encoded);
    try std.testing.expectError(
        error.InvalidKittyKeyboardIndex,
        invalid_kitty_index.encode(&kitty_index_writer),
    );

    var invalid_kitty_flags = testHeader();
    invalid_kitty_flags.kitty_keyboard.flags[3]._padding = 1;
    var kitty_flags_writer: std.Io.Writer = .fixed(&encoded);
    try std.testing.expectError(
        error.InvalidKittyKeyboardFlags,
        invalid_kitty_flags.encode(&kitty_flags_writer),
    );
}

test "header decoding rejects structural values" {
    const valid = [_]u8{0} ** Header.len;

    var invalid_key = valid;
    invalid_key[0] = 2;
    var key_reader: std.Io.Reader = .fixed(&invalid_key);
    try std.testing.expectError(error.InvalidKey, Header.decode(&key_reader));
}

test "header decoding normalizes unknown semantic values" {
    var fixture = [_]u8{0} ** Header.len;

    fixture[16] = 4; // Unknown cursor style.
    fixture[17] = 0xFF; // Known flags, unknown semantic value, reserved bits.
    fixture[18] = 3; // Unknown cursor foreground color kind.
    fixture[39] = 0xD0; // Invalid single shift plus a reserved bit.
    fixture[40] = 3; // Unknown protected mode.
    fixture[41] = 8; // Out-of-range Kitty keyboard index.
    @memset(fixture[42..50], 0xFF); // Known flags plus reserved bits.
    fixture[50] = 3; // Unknown semantic-click kind.
    fixture[51] = 0xFF;
    fixture[52] = 2; // Noncanonical true.

    var reader: std.Io.Reader = .fixed(&fixture);
    const decoded = try Header.decode(&reader);

    try std.testing.expectEqual(
        TerminalScreen.CursorStyle.block,
        decoded.cursor_style,
    );
    try std.testing.expect(decoded.cursor_pen.default());
    try std.testing.expect(decoded.cursor_flags.pending_wrap);
    try std.testing.expect(decoded.cursor_flags.protected);
    try std.testing.expectEqual(
        terminal_page.Cell.SemanticContent.output,
        decoded.cursor_flags.semantic_content,
    );
    try std.testing.expect(
        decoded.cursor_flags.semantic_content_clear_eol,
    );
    try std.testing.expectEqual(@as(u3, 0), decoded.cursor_flags._padding);

    try std.testing.expectEqual(null, decoded.charset.single_shift);
    try std.testing.expectEqual(terminal_charsets.Slots.G0, decoded.charset.gr);
    try std.testing.expectEqual(
        terminal_ansi.ProtectedMode.off,
        decoded.protected_mode,
    );
    try std.testing.expectEqual(@as(u8, 0), decoded.kitty_keyboard.index);
    for (decoded.kitty_keyboard.flags) |flags| {
        try std.testing.expect(flags.disambiguate);
        try std.testing.expect(flags.report_events);
        try std.testing.expect(flags.report_alternates);
        try std.testing.expect(flags.report_all);
        try std.testing.expect(flags.report_associated);
        try std.testing.expectEqual(@as(u3, 0), flags._padding);
    }
    try std.testing.expectEqual(
        TerminalScreen.SemanticPrompt.SemanticClick.none,
        decoded.semantic_click,
    );
    try std.testing.expect(decoded.saved_cursor_present);

    // Known semantic-click kinds with unknown or noncanonical values also
    // degrade to disabled while consuming both fixed bytes.
    const invalid_semantic_clicks = [_][2]u8{
        .{ 0, 1 },
        .{ 1, 2 },
        .{ 2, 4 },
    };
    for (invalid_semantic_clicks) |invalid| {
        var semantic_fixture = [_]u8{0} ** Header.len;
        semantic_fixture[50] = invalid[0];
        semantic_fixture[51] = invalid[1];
        var semantic_reader: std.Io.Reader = .fixed(&semantic_fixture);
        const semantic_decoded = try Header.decode(&semantic_reader);
        try std.testing.expectEqual(
            TerminalScreen.SemanticPrompt.SemanticClick.none,
            semantic_decoded.semantic_click,
        );
    }
}

test "header decoding rejects every truncation" {
    for (0..Header.len) |fixture_len| {
        var reader: std.Io.Reader = .fixed(
            test_header_fixture[0..fixture_len],
        );
        try std.testing.expectError(error.EndOfStream, Header.decode(&reader));
    }
}

test "native SCREEN payload omits absent optional state" {
    var screen = try TerminalScreen.init(
        std.testing.io,
        std.testing.allocator,
        .{ .cols = 2, .rows = 2, .max_scrollback_bytes = 0 },
    );
    defer screen.deinit();

    var encoded: [Header.len + 1]u8 = undefined;
    var writer: std.Io.Writer = .fixed(&encoded);
    try encodePayload(&screen, .primary, 1, &writer);
    try std.testing.expectEqual(encoded.len, writer.end);

    var reader: std.Io.Reader = .fixed(writer.buffered());
    const header = try Header.decode(&reader);
    try std.testing.expectEqual(TerminalScreenKey.primary, header.key);
    try std.testing.expectEqual(@as(u16, 1), header.page_count);
    try std.testing.expectEqual(@as(u64, 0), header.history_rows);
    try std.testing.expect(!header.saved_cursor_present);
    try std.testing.expectEqual(
        null,
        try decodeCursorHyperlink(&reader, std.testing.allocator),
    );
}

test "saved cursor golden encoding and decoding" {
    var encoded: [SavedCursor.len]u8 = undefined;
    var writer: std.Io.Writer = .fixed(&encoded);
    try testSavedCursor().encode(&writer);
    try test_fixture.expectEqual(
        .bytes,
        "src/terminal/snapshot/testdata/screen-saved-cursor-v1.hex",
        "snapshot_fixture-screen-saved-cursor-v1.hex",
        &test_saved_cursor_fixture,
        writer.buffered(),
    );
    try std.testing.expectEqual(
        SavedCursor.len,
        test_saved_cursor_fixture.len,
    );

    var source: std.Io.Reader = .fixed(&test_saved_cursor_fixture);
    var buffer: [1]u8 = undefined;
    var limited = source.limited(.unlimited, &buffer);
    try std.testing.expectEqualDeep(
        testSavedCursor(),
        try SavedCursor.decode(&limited.interface),
    );
}

test "saved cursor encoding rejects and decoding normalizes invalid state" {
    var encoded: [SavedCursor.len]u8 = undefined;

    var invalid_flags = testSavedCursor();
    invalid_flags.flags._padding = 1;
    var flags_writer: std.Io.Writer = .fixed(&encoded);
    try std.testing.expectError(
        error.InvalidSavedCursorFlags,
        invalid_flags.encode(&flags_writer),
    );

    var invalid = [_]u8{0} ** SavedCursor.len;
    invalid[4] = 3; // Unknown saved-cursor foreground color kind.
    invalid[20] = 0xF9; // Protected plus reserved bits.
    invalid[22] = 0xD0; // Invalid single shift plus a reserved bit.
    var reader: std.Io.Reader = .fixed(&invalid);
    const decoded = try SavedCursor.decode(&reader);

    try std.testing.expect(decoded.pen.default());
    try std.testing.expect(decoded.flags.protected);
    try std.testing.expect(!decoded.flags.pending_wrap);
    try std.testing.expect(!decoded.flags.origin);
    try std.testing.expectEqual(@as(u5, 0), decoded.flags._padding);
    try std.testing.expectEqual(null, decoded.charset.single_shift);
    try std.testing.expectEqual(
        terminal_charsets.Slots.G0,
        decoded.charset.gr,
    );
}

test "saved cursor decoding rejects every truncation" {
    for (0..SavedCursor.len) |fixture_len| {
        var reader: std.Io.Reader = .fixed(
            test_saved_cursor_fixture[0..fixture_len],
        );
        try std.testing.expectError(
            error.EndOfStream,
            SavedCursor.decode(&reader),
        );
    }
}

test "cursor hyperlink null encoding and decoding" {
    var none_encoded: [1]u8 = undefined;
    var none_writer: std.Io.Writer = .fixed(&none_encoded);
    try encodeCursorHyperlink(null, &none_writer);
    try std.testing.expectEqualStrings("\x00", none_writer.buffered());

    var none_reader: std.Io.Reader = .fixed(none_writer.buffered());
    try std.testing.expectEqual(
        null,
        try decodeCursorHyperlink(&none_reader, std.testing.allocator),
    );
}

test "framed native SCREEN and PAGE sequence" {
    var screen = try TerminalScreen.init(
        std.testing.io,
        std.testing.allocator,
        .{ .cols = 8, .rows = 8, .max_scrollback_bytes = 0 },
    );
    defer screen.deinit();

    // Configure the live cursor state represented by the fixed header.
    screen.cursorAbsolute(7, 6);
    screen.cursor.cursor_style = .block_hollow;
    screen.cursor.pending_wrap = true;
    screen.cursor.protected = false;
    screen.cursor.semantic_content = .prompt;
    screen.cursor.semantic_content_clear_eol = true;
    screen.cursor.style = testHeader().cursor_pen;
    screen.cursor.hyperlink_implicit_id = 0x0a0b0c0d;

    // Configure the screen-wide modes and packed charset state.
    var charset: TerminalScreen.CharsetState = .{
        .gl = .G1,
        .gr = .G3,
        .single_shift = .G2,
    };
    charset.charsets.set(.G0, .utf8);
    charset.charsets.set(.G1, .ascii);
    charset.charsets.set(.G2, .british);
    charset.charsets.set(.G3, .dec_special);
    screen.charset = charset;
    screen.protected_mode = .dec;
    screen.kitty_keyboard = .{
        .idx = 7,
        .flags = .{
            .{ .disambiguate = true },
            .{ .report_events = true },
            .{ .report_alternates = true },
            .{ .report_all = true },
            .{ .report_associated = true },
            .{
                .disambiguate = true,
                .report_events = true,
                .report_alternates = true,
                .report_all = true,
                .report_associated = true,
            },
            .{},
            .{
                .disambiguate = true,
                .report_associated = true,
            },
        },
    };
    screen.semantic_prompt = .{
        .seen = true,
        .click = .{ .cl = .smart_vertical },
    };

    // Configure the optional cursor state encoded after the fixed header.
    screen.saved_cursor = .{
        .x = 0x0102,
        .y = 0x0304,
        .style = .{},
        .protected = true,
        .pending_wrap = true,
        .origin = true,
        .charset = charset,
    };
    try screen.startHyperlink("cursor-uri", null);

    var destination: std.Io.Writer.Allocating = .init(
        std.testing.allocator,
    );
    defer destination.deinit();
    try destination.writer.writeAll("prefix");
    var stream: record.Writer = .init(
        std.testing.allocator,
        &destination.writer,
    );
    defer stream.deinit();
    try encode(&screen, .alternate, &stream);

    try std.testing.expectEqualStrings(
        "prefix",
        destination.written()[0..6],
    );

    // The complete sequence restores directly into native Screen/PageList
    // state, including page-local cursor references.
    var restore_source: std.Io.Reader = .fixed(destination.written()[6..]);
    var decoded = try decode(
        &restore_source,
        std.testing.io,
        std.testing.allocator,
        .{ .cols = 8, .rows = 8, .max_scrollback_bytes = 0 },
    );
    defer decoded.deinit();
    try std.testing.expectEqual(TerminalScreenKey.alternate, decoded.key);
    const restored = &decoded.screen;

    try std.testing.expect(restored.no_scrollback);
    try std.testing.expectEqual(@as(u16, 7), restored.cursor.x);
    try std.testing.expectEqual(@as(u16, 6), restored.cursor.y);
    try std.testing.expectEqual(
        TerminalScreen.CursorStyle.block_hollow,
        restored.cursor.cursor_style,
    );
    try std.testing.expect(restored.cursor.pending_wrap);
    try std.testing.expectEqual(
        terminal_page.Cell.SemanticContent.prompt,
        restored.cursor.semantic_content,
    );
    try std.testing.expect(
        restored.cursor.style.eql(testHeader().cursor_pen),
    );
    try std.testing.expect(restored.cursor.style_id != terminal_style.default_id);
    try std.testing.expectEqual(
        @as(u32, 0x0a0b0c0e),
        restored.cursor.hyperlink_implicit_id,
    );
    const restored_hyperlink = restored.cursor.hyperlink.?.*;
    try std.testing.expectEqualStrings(
        "cursor-uri",
        restored_hyperlink.uri,
    );
    switch (restored_hyperlink.id) {
        .implicit => |id| try std.testing.expectEqual(
            @as(u32, 0x0a0b0c0d),
            id,
        ),
        .explicit => try std.testing.expect(false),
    }

    const restored_saved = restored.saved_cursor.?;
    try std.testing.expectEqual(@as(u16, 7), restored_saved.x);
    try std.testing.expectEqual(@as(u16, 7), restored_saved.y);
    try std.testing.expect(restored_saved.protected);
    try std.testing.expect(restored_saved.pending_wrap);
    try std.testing.expect(restored_saved.origin);
    try std.testing.expectEqual(
        terminal_charsets.Charset.ascii,
        restored.charset.charsets.get(.G1),
    );
    try std.testing.expectEqual(
        terminal_ansi.ProtectedMode.dec,
        restored.protected_mode,
    );
    try std.testing.expectEqual(@as(u8, 7), restored.kitty_keyboard.idx);
    try std.testing.expect(restored.semantic_prompt.seen);
    try std.testing.expectEqual(
        TerminalScreen.SemanticPrompt.SemanticClick{
            .cl = .smart_vertical,
        },
        restored.semantic_prompt.click,
    );

    // Restored page-local cursor IDs are immediately usable by normal writes.
    try restored.testWriteString("Z");
    const written = restored.pages.getCell(.{ .active = .{
        .x = 0,
        .y = 7,
    } }).?;
    try std.testing.expectEqual(@as(u21, 'Z'), written.cell.codepoint());
    try std.testing.expectEqual(
        restored.cursor.style_id,
        written.cell.style_id,
    );
    try std.testing.expectEqual(
        restored.cursor.hyperlink_id,
        written.node.page().lookupHyperlink(written.cell).?,
    );
    try std.testing.expectEqual(
        terminal_page.Cell.SemanticContent.prompt,
        written.cell.semantic_content,
    );
    try std.testing.expectError(error.EndOfStream, restore_source.takeByte());
}

test "SCREEN encodes the minimal complete-page active suffix" {
    var probe = try TerminalScreen.init(
        std.testing.io,
        std.testing.allocator,
        .{ .cols = 80, .rows = 1, .max_scrollback_bytes = 0 },
    );
    const page_rows = probe.pages.getTopLeft(.screen).node.capacity().rows;
    probe.deinit();
    const screen_rows = page_rows + 1;

    var screen = try TerminalScreen.init(
        std.testing.io,
        std.testing.allocator,
        .{
            .cols = 80,
            .rows = screen_rows,
            .max_scrollback_bytes = null,
        },
    );
    defer screen.deinit();

    // Create one complete historical page followed by a mixed page whose
    // first row is history and whose remaining rows begin the active area.
    screen.cursorAbsolute(0, screen_rows - 1);
    for (0..screen_rows) |_| try screen.testWriteString("\n");
    try std.testing.expectEqual(@as(usize, 3), screen.pages.totalPages());

    const active_top = screen.pages.getTopLeft(.active);
    const historical = screen.pages.getTopLeft(.screen).node;
    const mixed = historical.next.?;
    const newest = mixed.next.?;
    try std.testing.expectEqual(mixed, active_top.node);
    try std.testing.expectEqual(@as(u16, 1), active_top.y);
    try std.testing.expectEqual(null, newest.next);

    // Mark each native page so the encoded sequence proves both omission and
    // oldest-to-newest ordering. The mixed page's marker is in its incidental
    // history prefix and must survive because complete pages are encoded.
    historical.page().getRowAndCell(0, 0).cell.* = .init('A');
    mixed.page().getRowAndCell(0, 0).cell.* = .init('B');
    newest.page().getRowAndCell(0, 0).cell.* = .init('C');

    var destination: std.Io.Writer.Allocating = .init(
        std.testing.allocator,
    );
    defer destination.deinit();
    var stream: record.Writer = .init(
        std.testing.allocator,
        &destination.writer,
    );
    defer stream.deinit();
    try encode(&screen, .primary, &stream);

    var source: std.Io.Reader = .fixed(destination.written());
    var screen_record: record.Reader = undefined;
    try screen_record.init(&source);
    try std.testing.expectEqual(record.Tag.screen, screen_record.header.tag);

    const payload_reader = screen_record.payloadReader();
    const header = try Header.decode(payload_reader);
    try std.testing.expectEqual(TerminalScreenKey.primary, header.key);
    try std.testing.expectEqual(@as(u16, 2), header.page_count);
    try std.testing.expectEqual(
        @as(u64, @intCast(screen.pages.total_rows - screen.pages.rows)),
        header.history_rows,
    );
    try std.testing.expect(!header.saved_cursor_present);
    try std.testing.expectEqual(
        null,
        try decodeCursorHyperlink(payload_reader, std.testing.allocator),
    );
    try screen_record.finish();

    var decoded_mixed = try page.decode(&source, std.testing.allocator);
    defer decoded_mixed.deinit();
    try std.testing.expectEqual(
        @as(u21, 'B'),
        decoded_mixed.getRowAndCell(0, 0).cell.codepoint(),
    );

    var decoded_newest = try page.decode(&source, std.testing.allocator);
    defer decoded_newest.deinit();
    try std.testing.expectEqual(
        @as(u21, 'C'),
        decoded_newest.getRowAndCell(0, 0).cell.codepoint(),
    );
    try std.testing.expectError(error.EndOfStream, source.takeByte());

    // Native restoration keeps the incidental history prefix and positions
    // the active top within the first decoded page.
    var restore_source: std.Io.Reader = .fixed(destination.written());
    var decoded = try decode(
        &restore_source,
        std.testing.io,
        std.testing.allocator,
        .{
            .cols = 80,
            .rows = screen_rows,
            .max_scrollback_bytes = null,
        },
    );
    defer decoded.deinit();
    try std.testing.expectEqual(TerminalScreenKey.primary, decoded.key);
    try std.testing.expectEqual(header.history_rows, decoded.history_rows);
    const restored = &decoded.screen;

    try std.testing.expectEqual(@as(usize, 2), restored.pages.totalPages());
    const restored_top = restored.pages.getTopLeft(.active);
    try std.testing.expectEqual(@as(u16, 1), restored_top.y);
    try std.testing.expectEqual(
        @as(usize, restored_top.y),
        restored.pages.total_rows - restored.pages.rows,
    );
    try std.testing.expect(
        decoded.history_rows > @as(
            u64,
            @intCast(restored.pages.total_rows - restored.pages.rows),
        ),
    );
    try std.testing.expectEqual(
        @as(u21, 'B'),
        restored.pages.getTopLeft(.screen).node
            .page().getRowAndCell(0, 0).cell.codepoint(),
    );
    try std.testing.expectEqual(
        @as(u21, 'C'),
        restored.pages.getTopLeft(.screen).node.next.?
            .page().getRowAndCell(0, 0).cell.codepoint(),
    );

    // The restored PageList resumes ordinary scrolling and row growth.
    try restored.testWriteString("\n");
    restored.pages.assertIntegrity();
    restored.assertIntegrity();
    try std.testing.expectError(error.EndOfStream, restore_source.takeByte());
}

test "SCREEN encoding preserves a compressed suffix page" {
    const testing = std.testing;
    const compression = @import("../compress.zig");

    var screen = try TerminalScreen.init(
        testing.io,
        testing.allocator,
        .{ .cols = 8, .rows = 2, .max_scrollback_bytes = 0 },
    );
    defer screen.deinit();
    screen.pages.getCell(.{ .active = .{} }).?.cell.* = .init('A');

    // Force the active suffix into the representation that current PageList
    // policy normally reserves for history. This models a future policy change
    // and makes pageAssumeResident an invalid tagged-union access.
    const node = screen.pages.getTopLeft(.active).node;
    const resident = node.pageAssumeResident();
    const scratch = try testing.allocator.alloc(
        u8,
        try compression.Page.requiredScratch(resident.memory.len),
    );
    defer testing.allocator.free(scratch);
    var table: compression.lz4.HashTable = undefined;
    const compressed = (try compression.Page.init(
        testing.allocator,
        resident,
        scratch,
        &table,
    )).?;
    node.data = .{ .compressed = compressed };
    try testing.expectEqual(.compressed, node.storage());

    var destination: std.Io.Writer.Allocating = .init(testing.allocator);
    defer destination.deinit();
    var stream: record.Writer = .init(testing.allocator, &destination.writer);
    defer stream.deinit();
    try encode(&screen, .primary, &stream);

    // Encoding borrows or clones through PreservedPage and never changes the
    // source node's storage representation.
    try testing.expectEqual(.compressed, node.storage());

    var source: std.Io.Reader = .fixed(destination.written());
    var decoded = try decode(
        &source,
        testing.io,
        testing.allocator,
        .{ .cols = 8, .rows = 2, .max_scrollback_bytes = 0 },
    );
    defer decoded.deinit();
    try testing.expectEqual(
        @as(u21, 'A'),
        decoded.screen.pages.getCell(.{ .active = .{} }).?.cell.codepoint(),
    );
}

test "SCREEN restoration normalizes invalid cursor positions" {
    var screen = try TerminalScreen.init(
        std.testing.io,
        std.testing.allocator,
        .{ .cols = 2, .rows = 2, .max_scrollback_bytes = 0 },
    );
    defer screen.deinit();

    const Case = struct {
        x: u16,
        y: u16,
        pending_wrap: bool,
        expected_x: u16,
        expected_y: u16,
        expected_pending_wrap: bool,
    };
    const cases = [_]Case{
        // Out-of-range coordinates clamp to the bottom-right. Pending wrap is
        // valid there and can be retained.
        .{
            .x = std.math.maxInt(u16),
            .y = std.math.maxInt(u16),
            .pending_wrap = true,
            .expected_x = 1,
            .expected_y = 1,
            .expected_pending_wrap = true,
        },
        // Pending wrap away from the final column would trip native printing
        // assertions, so retain the position and clear only that flag.
        .{
            .x = 0,
            .y = 0,
            .pending_wrap = true,
            .expected_x = 0,
            .expected_y = 0,
            .expected_pending_wrap = false,
        },
    };

    for (cases) |case| {
        var destination: std.Io.Writer.Allocating = .init(
            std.testing.allocator,
        );
        defer destination.deinit();
        var stream: record.Writer = .init(
            std.testing.allocator,
            &destination.writer,
        );
        defer stream.deinit();

        var header = Header.init(&screen, .primary, 1);
        header.cursor_x = case.x;
        header.cursor_y = case.y;
        header.cursor_flags.pending_wrap = case.pending_wrap;
        header.saved_cursor_present = false;

        const screen_payload = stream.begin(.screen);
        errdefer stream.cancel();
        try header.encode(screen_payload);
        try screen_payload.writeByte(0);
        try stream.finish();

        const native_page = screen.pages.getTopLeft(.active).node
            .pageAssumeResident();
        try page.encode(native_page, &stream);

        var source: std.Io.Reader = .fixed(destination.written());
        var decoded = try decode(
            &source,
            std.testing.io,
            std.testing.allocator,
            .{ .cols = 2, .rows = 2, .max_scrollback_bytes = 0 },
        );
        defer decoded.deinit();

        try std.testing.expectEqual(case.expected_x, decoded.screen.cursor.x);
        try std.testing.expectEqual(case.expected_y, decoded.screen.cursor.y);
        try std.testing.expectEqual(
            case.expected_pending_wrap,
            decoded.screen.cursor.pending_wrap,
        );
        decoded.screen.assertIntegrity();
    }
}

test "SCREEN validates pending wrap against a mixed-width cursor page" {
    var screen = try TerminalScreen.init(
        std.testing.io,
        std.testing.allocator,
        .{ .cols = 8, .rows = 1, .max_scrollback_bytes = 0 },
    );
    defer screen.deinit();

    // Model a lazily reflowed active page that is narrower than the terminal.
    // Column three is its physical final column even though it is not column
    // seven of the current terminal dimensions.
    var narrow_page = try terminal_page.Page.init(.{ .cols = 4, .rows = 1 });
    defer narrow_page.deinit();

    var destination: std.Io.Writer.Allocating = .init(
        std.testing.allocator,
    );
    defer destination.deinit();
    var stream: record.Writer = .init(
        std.testing.allocator,
        &destination.writer,
    );
    defer stream.deinit();

    var header = Header.init(&screen, .primary, 1);
    header.cursor_x = 3;
    header.cursor_y = 0;
    header.cursor_flags.pending_wrap = true;
    header.saved_cursor_present = false;

    const screen_payload = stream.begin(.screen);
    errdefer stream.cancel();
    try header.encode(screen_payload);
    try screen_payload.writeByte(0);
    try stream.finish();
    try page.encode(&narrow_page, &stream);

    var source: std.Io.Reader = .fixed(destination.written());
    var decoded = try decode(
        &source,
        std.testing.io,
        std.testing.allocator,
        .{ .cols = 8, .rows = 1, .max_scrollback_bytes = 0 },
    );
    defer decoded.deinit();

    try std.testing.expectEqual(@as(u16, 4), decoded.screen.cursor.page_pin.node.cols());
    try std.testing.expectEqual(@as(u16, 3), decoded.screen.cursor.x);
    try std.testing.expect(decoded.screen.cursor.pending_wrap);
    decoded.screen.assertIntegrity();
}

test "SCREEN clamps a decoded saved cursor to terminal dimensions" {
    var screen = try TerminalScreen.init(
        std.testing.io,
        std.testing.allocator,
        .{ .cols = 2, .rows = 2, .max_scrollback_bytes = 0 },
    );
    defer screen.deinit();

    var destination: std.Io.Writer.Allocating = .init(
        std.testing.allocator,
    );
    defer destination.deinit();
    var stream: record.Writer = .init(
        std.testing.allocator,
        &destination.writer,
    );
    defer stream.deinit();

    var header = Header.init(&screen, .primary, 1);
    header.saved_cursor_present = true;
    const screen_payload = stream.begin(.screen);
    try header.encode(screen_payload);
    try (SavedCursor{
        .x = std.math.maxInt(u16),
        .y = std.math.maxInt(u16),
        .pen = .{},
        .flags = .{ .pending_wrap = true },
        .charset = .{},
    }).encode(screen_payload);
    try screen_payload.writeByte(0);
    try stream.finish();
    try page.encode(
        screen.pages.getTopLeft(.active).node.pageAssumeResident(),
        &stream,
    );

    var source: std.Io.Reader = .fixed(destination.written());
    var decoded = try decode(
        &source,
        std.testing.io,
        std.testing.allocator,
        .{ .cols = 2, .rows = 2, .max_scrollback_bytes = 0 },
    );
    defer decoded.deinit();

    const saved = decoded.screen.saved_cursor.?;
    try std.testing.expectEqual(@as(u16, 1), saved.x);
    try std.testing.expectEqual(@as(u16, 1), saved.y);
    try std.testing.expect(saved.pending_wrap);
}

test "SCREEN restoration rejects invalid and incomplete sequences" {
    var screen = try TerminalScreen.init(
        std.testing.io,
        std.testing.allocator,
        .{ .cols = 2, .rows = 2, .max_scrollback_bytes = 0 },
    );
    defer screen.deinit();

    var destination: std.Io.Writer.Allocating = .init(
        std.testing.allocator,
    );
    defer destination.deinit();
    var stream: record.Writer = .init(
        std.testing.allocator,
        &destination.writer,
    );
    defer stream.deinit();
    try encode(&screen, .primary, &stream);

    // Every truncation must fail without leaking a partially restored
    // PageList, cursor pin, or cursor-owned state.
    for (0..destination.written().len) |fixture_len| {
        var source: std.Io.Reader = .fixed(
            destination.written()[0..fixture_len],
        );
        var restored = decode(
            &source,
            std.testing.io,
            std.testing.allocator,
            .{ .cols = 2, .rows = 2, .max_scrollback_bytes = 0 },
        ) catch continue;
        restored.deinit();
        try std.testing.expect(false);
    }

    // Native PageList construction is transactional on allocation failure.
    {
        var failing = std.testing.FailingAllocator.init(
            std.testing.allocator,
            .{ .fail_index = 0 },
        );
        var source: std.Io.Reader = .fixed(destination.written());
        try std.testing.expectError(
            error.OutOfMemory,
            decode(
                &source,
                std.testing.io,
                failing.allocator(),
                .{ .cols = 2, .rows = 2, .max_scrollback_bytes = 0 },
            ),
        );
    }

    // A syntactically valid SCREEN cannot declare an empty PAGE sequence.
    var empty_sequence: std.Io.Writer.Allocating = .init(
        std.testing.allocator,
    );
    defer empty_sequence.deinit();
    var empty_stream: record.Writer = .init(
        std.testing.allocator,
        &empty_sequence.writer,
    );
    defer empty_stream.deinit();
    {
        const payload = empty_stream.begin(.screen);
        errdefer empty_stream.cancel();
        try Header.init(&screen, .primary, 0).encode(
            payload,
        );
        try payload.writeByte(0);
        try empty_stream.finish();
    }
    var empty_source: std.Io.Reader = .fixed(empty_sequence.written());
    try std.testing.expectError(
        error.InvalidPageCount,
        decode(
            &empty_source,
            std.testing.io,
            std.testing.allocator,
            .{ .cols = 2, .rows = 2, .max_scrollback_bytes = 0 },
        ),
    );
}

test "SCREEN sequence failure preserves preceding bytes" {
    var screen = try TerminalScreen.init(
        std.testing.io,
        std.testing.allocator,
        .{ .cols = 2, .rows = 2, .max_scrollback_bytes = 0 },
    );
    defer screen.deinit();

    var destination: std.Io.Writer.Allocating = .init(
        std.testing.allocator,
    );
    defer destination.deinit();
    try destination.writer.writeAll("prefix");

    var failing = std.testing.FailingAllocator.init(
        std.testing.allocator,
        .{ .fail_index = 0 },
    );
    var stream: record.Writer = .init(
        failing.allocator(),
        &destination.writer,
    );
    defer stream.deinit();

    try std.testing.expectError(
        error.WriteFailed,
        encode(&screen, .primary, &stream),
    );
    try std.testing.expectEqualStrings("prefix", destination.written());
}

test "SCREEN decode ignores an invalid cursor hyperlink" {
    var screen = try TerminalScreen.init(
        std.testing.io,
        std.testing.allocator,
        .{ .cols = 1, .rows = 1, .max_scrollback_bytes = 0 },
    );
    defer screen.deinit();

    var destination: std.Io.Writer.Allocating = .init(
        std.testing.allocator,
    );
    defer destination.deinit();
    var stream: record.Writer = .init(
        std.testing.allocator,
        &destination.writer,
    );
    defer stream.deinit();

    var header = testHeader();
    header.key = .primary;
    header.page_count = 1;
    header.cursor_x = 0;
    header.cursor_y = 0;
    header.cursor_flags.pending_wrap = false;
    header.saved_cursor_present = false;

    const screen_payload = stream.begin(.screen);
    errdefer stream.cancel();
    try header.encode(screen_payload);
    try screen_payload.writeByte(1); // Implicit hyperlink.
    try io.writeInt(screen_payload, u32, 1);
    try io.writeInt(screen_payload, u32, 0); // Empty URI.
    try stream.finish();

    try page.encode(
        screen.pages.getTopLeft(.active).node.pageAssumeResident(),
        &stream,
    );

    var source: std.Io.Reader = .fixed(destination.written());
    var decoded = try decode(
        &source,
        std.testing.io,
        std.testing.allocator,
        .{ .cols = 1, .rows = 1 },
    );
    defer decoded.deinit();
    try std.testing.expectEqual(null, decoded.screen.cursor.hyperlink);
}

test "SCREEN decode ignores a PAGE with an empty hyperlink URI" {
    var destination: std.Io.Writer.Allocating = .init(
        std.testing.allocator,
    );
    defer destination.deinit();
    var stream: record.Writer = .init(
        std.testing.allocator,
        &destination.writer,
    );
    defer stream.deinit();

    var header = testHeader();
    header.key = .primary;
    header.page_count = 1;
    header.cursor_x = 0;
    header.cursor_y = 0;
    header.cursor_flags.pending_wrap = false;
    header.saved_cursor_present = false;

    const screen_payload = stream.begin(.screen);
    errdefer stream.cancel();
    try header.encode(screen_payload);
    try screen_payload.writeByte(0);
    try stream.finish();

    const page_header: page.Header = .{
        .columns = 1,
        .rows = 1,
        .style_count = 0,
        .hyperlink_count = 1,
        .style_capacity = 16,
        .hyperlink_capacity_bytes = 512,
        .grapheme_capacity_bytes = 0,
        .string_capacity_bytes = 0,
    };
    const page_payload = stream.begin(.page);
    errdefer stream.cancel();
    try page_header.encode(page_payload);
    try io.writeInt(
        page_payload,
        terminal_hyperlink.Id,
        1,
    );
    try page_payload.writeByte(1); // Implicit hyperlink.
    try io.writeInt(page_payload, u32, 1);
    try io.writeInt(page_payload, u32, 0); // Empty URI.

    // One narrow codepoint cell refers to the hyperlink table entry above.
    // Since that entry is ignored, the cell must restore without a hyperlink.
    try page_payload.writeByte(0x30); // row flags, full cell width
    try io.writeInt(page_payload, u16, 1); // cell count
    try io.writeInt(page_payload, u64, @bitCast(grid.Cell{
        .content = 'A',
        .hyperlink = true,
        .hyperlink_id = 1,
    }));
    try io.writeInt(page_payload, u32, 0); // grapheme section
    try stream.finish();

    var source: std.Io.Reader = .fixed(destination.written());
    var decoded = try decode(
        &source,
        std.testing.io,
        std.testing.allocator,
        .{ .cols = 1, .rows = 1 },
    );
    defer decoded.deinit();

    try std.testing.expectEqual(
        @as(u21, 'A'),
        decoded.screen.cursor.page_cell.codepoint(),
    );
    try std.testing.expect(!decoded.screen.cursor.page_cell.hyperlink);

    // Resizing copies the restored cells into a wider page. The ignored
    // hyperlink must not leave a zero-length PageEntry to duplicate later.
    try decoded.screen.resize(.{ .cols = 2, .rows = 1 });
    try std.testing.expect(!decoded.screen.cursor.page_cell.hyperlink);
}