document-session-api 0.1.1

Engine-facing document contracts: retained session traits, the accessibility projection, document capabilities, page capture, and the engine-id namespace. The half of inker an engine implements.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
// Copyright 2026 Mark Alan Boykin
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// SPDX-License-Identifier: MPL-2.0

//! Session-engine traits and registry — the third engine kind
//! (2026-07-10 session-engines plan).
//!
//! Document engines (`Engine`) are request/response: bytes in,
//! serializable `EngineDocument` blocks out — the stored/authored
//! lane. Surface engines (`SurfaceEngine`) stream GPU textures from
//! external producers. Session engines sit between: **retained document
//! sessions** that lay content out once and then produce paint frames on
//! demand, with scroll, activation, and (for scripted lanes) a tick +
//! quiescence seam. The genet HTML lanes and the smolweb native lane are
//! session engines.
//!
//! The frame type is generic (`F`) so this crate keeps zero paint
//! dependencies: a netrender host instantiates `F = netrender::Scene`; a
//! different host picks its own frame type. Lane-specific construction seams
//! (resource fetchers, cookie jars, themes) are injected into the concrete
//! `SessionEngine` at registration time, not carried in the spawn request —
//! the request stays plain data.

use std::any::Any;
use std::collections::HashMap;
use std::fmt;
use std::time::{Duration, Instant};

use serde::{Deserialize, Serialize};

use crate::a11y::{
    DocumentA11yActionRequest, DocumentA11yClickTarget, DocumentA11yNodeId, DocumentA11yProjection,
};
use crate::{A11yCapability, DocumentCapabilities, PageCaptureOutput, PageCaptureRequest};

// ── Errors ─────────────────────────────────────────────────────────────────

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SessionError {
    EngineNotFound(String),
    SpawnFailed(String),
    Unsupported(String),
}

impl fmt::Display for SessionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EngineNotFound(id) => write!(f, "session engine not registered: {id}"),
            Self::SpawnFailed(reason) => write!(f, "session spawn failed: {reason}"),
            Self::Unsupported(reason) => write!(f, "unsupported: {reason}"),
        }
    }
}

impl std::error::Error for SessionError {}

// ── Spawn request ──────────────────────────────────────────────────────────

/// Plain-data request to open a document session. The body is already
/// fetched when the host has it (mirroring `EngineInput`); a session
/// engine whose lane fetches for itself (subresources, redirects) uses the
/// seams it was constructed with.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionSpawnRequest {
    pub address: String,
    /// Fetched body, when the host fetched it. `None` asks the engine to
    /// load via its own fetcher seam.
    pub body: Option<String>,
    pub content_type: Option<String>,
    /// Initial viewport, so the first `frame` call needs no resize dance.
    pub viewport: (u32, u32),
    /// Spawn hidden (a background tile): the session may defer work the
    /// visible path would do eagerly.
    pub hidden: bool,
}

impl SessionSpawnRequest {
    pub fn new(address: impl Into<String>) -> Self {
        Self {
            address: address.into(),
            body: None,
            content_type: None,
            viewport: (0, 0),
            hidden: false,
        }
    }

    pub fn with_body(mut self, body: impl Into<String>) -> Self {
        self.body = Some(body.into());
        self
    }

    pub fn with_content_type(mut self, content_type: impl Into<String>) -> Self {
        self.content_type = Some(content_type.into());
        self
    }

    pub fn with_viewport(mut self, width: u32, height: u32) -> Self {
        self.viewport = (width, height);
        self
    }
}

// ── Interaction vocabulary ─────────────────────────────────────────────────

/// A link the session exposes for the host's hit table: url + viewport-space
/// rect (`[x, y, w, h]`, the shape the lanes already emit).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SessionLink {
    pub url: String,
    pub rect: [f32; 4],
}

/// A structural report of a session's addressed content — title, an outline
/// of role + name, outgoing links, headings. The introspection CONTRACT for
/// [`DocumentSession::inspect`]: pure data, so it lives here rather than in a
/// render crate (genet-render's `content_report` builds one from a LayoutDom
/// and re-exports these types). Hosts that cannot downcast a session to its
/// concrete type (the type may be private to its engine crate) read this
/// instead — turnstone's Inspector pane is the first such consumer.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ContentReport {
    /// The `<title>` text, if any.
    pub title: Option<String>,
    /// The element outline (painted elements only; metadata tags are skipped),
    /// in document order.
    pub outline: Vec<OutlineEntry>,
    /// Outgoing `<a href>` targets, in document order.
    pub links: Vec<String>,
    /// Heading (`<h1>`..`<h6>`) text, in document order.
    pub headings: Vec<String>,
    /// Derivation evidence when this session presents transformed source bytes.
    pub lineage: Option<ContentLineage>,
}

/// Host-neutral derivation evidence for an inspected document session.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ContentLineage {
    pub tool: String,
    pub version: String,
    pub selector: String,
    pub score: Option<i32>,
    pub block_count: usize,
}

/// The relationship between retained bytes and the representation observed by
/// a document engine.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DocumentClipArtifactRole {
    /// Bytes returned by the source transport before document execution.
    SourceResponse,
    /// A serialized representation of the state actually observed by the
    /// lowering, such as a post-script DOM snapshot.
    ObservedRepresentation,
}

/// Exact source material offered with a semantic clip. The receiving domain
/// decides whether and where to retain it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DocumentClipArtifact {
    pub role: DocumentClipArtifactRole,
    pub media_type: String,
    pub canonical_uri: String,
    pub bytes: Vec<u8>,
}

/// A host-neutral semantic fragment offered by a retained document session.
///
/// Sessions may expose the whole addressed document when they do not implement
/// range selection. The source address and optional selector keep that
/// distinction explicit for consumers such as Knot clipping.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DocumentClip {
    pub source_url: String,
    pub title: Option<String>,
    pub text: String,
    pub selector: Option<String>,
    pub links: Vec<String>,
    /// Source artifacts available from the engine's ordinary retained state.
    /// Engines must not refetch or reconstruct bytes solely for this field.
    pub artifacts: Vec<DocumentClipArtifact>,
}

/// A semantic text occurrence resolved to lane-local pointer coordinates.
///
/// Hosts use this for find-to-select and automation without learning a
/// document engine's DOM ids or text-layout representation. Driving these
/// points through [`DocumentSession::pointer_down`],
/// [`DocumentSession::pointer_move`], and [`DocumentSession::pointer_up`] still
/// exercises the ordinary input path; this is target resolution, not a second
/// selection mutation API.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SessionTextTarget {
    pub anchor: [f32; 2],
    pub focus: [f32; 2],
}

/// Direction for stepping a retained document find model.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum DocumentFindDirection {
    Previous,
    Next,
}

/// A host-neutral document find query.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct DocumentFindQuery {
    pub text: String,
    pub match_case: bool,
}

impl DocumentFindQuery {
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            match_case: false,
        }
    }
}

/// How selecting a match is revealed by its owning engine.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub enum DocumentFindReveal {
    /// Retained document-space vertical offset. The session applies it when the
    /// match becomes current; the value remains observable to automation.
    ScrollY(f32),
    /// A hosted engine owns selection and reveal internally.
    EngineManaged,
}

/// One retained match, in document order.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DocumentFindMatch {
    /// Human-readable matched text or accessible element label.
    pub label: String,
    /// Coarse semantic role when the engine exposes one.
    pub role: Option<String>,
    pub reveal: DocumentFindReveal,
}

/// The retained result model shared by retained documents and hosted engines.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DocumentFindState {
    pub query: DocumentFindQuery,
    /// Authoritative number of matches. Engines that can describe individual
    /// matches also populate `matches`; engine-managed pages may expose only
    /// this count and the current ordinal.
    pub count: usize,
    pub matches: Vec<DocumentFindMatch>,
    /// Zero-based index into `matches`.
    pub current: Option<usize>,
    /// Hosted engines may report progressive counts. Static sessions are
    /// complete in their first answer.
    pub complete: bool,
}

impl DocumentFindState {
    pub fn empty(query: DocumentFindQuery) -> Self {
        Self {
            query,
            count: 0,
            matches: Vec::new(),
            current: None,
            complete: true,
        }
    }

    /// Adapt an engine-managed count/current callback into the same retained
    /// model used by static sessions. The engine remains responsible for
    /// revealing the selected occurrence.
    pub fn engine_managed(
        query: DocumentFindQuery,
        count: usize,
        active_match: Option<usize>,
        complete: bool,
    ) -> Self {
        Self {
            query,
            count,
            matches: Vec::new(),
            current: active_match.filter(|index| *index < count),
            complete,
        }
    }

    pub fn current_match(&self) -> Option<&DocumentFindMatch> {
        self.current.and_then(|index| self.matches.get(index))
    }
}

/// The retained page-zoom model shared by retained documents and hosted
/// engines.
///
/// `requested` is the caller's own value, echoed back unchanged: the host
/// persists it per node and steps its own ladder. `applied` is what the engine
/// actually used after clamping and any quantization of its own, and `min` /
/// `max` name the engine's bounds so a host can grey out a step it cannot take.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct DocumentZoomState {
    /// The absolute factor the caller asked for (1.0 = 100 %).
    pub requested: f32,
    /// The effective factor this engine is presenting at.
    pub applied: f32,
    pub min: f32,
    pub max: f32,
}

impl DocumentZoomState {
    /// Clamp `requested` into `[min, max]` and report both halves. Engines that
    /// quantize further overwrite `applied` after calling this.
    pub fn clamped(requested: f32, min: f32, max: f32) -> Self {
        // A non-finite request is a caller bug rather than a zoom level, and
        // must never reach layout as a NaN viewport divisor.
        let applied = if requested.is_finite() {
            requested.clamp(min, max)
        } else {
            1.0_f32.clamp(min, max)
        };
        Self {
            requested,
            applied,
            min,
            max,
        }
    }
}

/// One element in the structural outline.
#[derive(Clone, Debug, PartialEq)]
pub struct OutlineEntry {
    /// Nesting depth among painted elements (the document root is depth 0).
    pub depth: usize,
    /// A coarse semantic role (`"link"`, `"heading"`, `"paragraph"`, …).
    pub role: &'static str,
    /// The element's accessible name — its direct text content, trimmed.
    pub name: String,
}

/// What a click did, unifying the lanes' divergent returns
/// (`ClickOutcome` / `bool` / `Option<String>`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SessionClick {
    /// The click resolved to a navigation the HOST performs (a link).
    Navigate(String),
    /// The click resolved to a mutation endpoint. The host must collect and
    /// confirm a body before submitting it.
    Submit(String),
    /// The session consumed the click itself (focus, a scripted handler).
    Handled,
    /// Nothing interactive at that point.
    Miss,
}

/// Modifier state carried with host-neutral session input.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionModifiers {
    pub shift: bool,
    pub control: bool,
    pub alt: bool,
    pub meta: bool,
}

/// Pointer buttons understood by a retained document session.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SessionPointerButton {
    Primary,
    Secondary,
    Auxiliary,
}

/// Press/release state shared by pointer and keyboard events.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SessionButtonState {
    Pressed,
    Released,
}

/// Cursor requested by the retained content under the pointer.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum SessionCursor {
    #[default]
    Default,
    Pointer,
    Text,
}

/// Keyboard keys with document-level meaning. Text-bearing keys retain the
/// produced character string so this vocabulary does not assume ASCII.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SessionKey {
    Character(String),
    Enter,
    Tab,
    Backspace,
    Delete,
    Escape,
    Space,
    ArrowLeft,
    ArrowRight,
    ArrowUp,
    ArrowDown,
    Home,
    End,
    PageUp,
    PageDown,
    Unidentified,
}

/// Direction requested by focus traversal.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SessionFocusDirection {
    Forward,
    Backward,
}

/// Platform composition lifecycle translated without exposing a windowing
/// crate to document engines.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SessionIme {
    Enabled,
    Preedit {
        text: String,
        selection: Option<(usize, usize)>,
    },
    Commit(String),
    Disabled,
}

/// Input delivered by a host to one retained session. For a printable key,
/// send `Key` first and then its produced `KeyboardText`. `Key` owns keyboard
/// events and non-text defaults; `KeyboardText` owns that key's character edit
/// and can be suppressed by a canceled keydown. `Text` is independent input,
/// including paste and accessibility, and is never canceled by an earlier key.
/// An IME commit uses `Ime::Commit`. Send control keys such as Enter only as
/// `Key`; independent `Text` may contain newlines.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum SessionInput {
    PointerMoved {
        x: f32,
        y: f32,
        modifiers: SessionModifiers,
    },
    PointerButton {
        x: f32,
        y: f32,
        button: SessionPointerButton,
        state: SessionButtonState,
        modifiers: SessionModifiers,
    },
    Key {
        key: SessionKey,
        state: SessionButtonState,
        modifiers: SessionModifiers,
        repeat: bool,
    },
    KeyboardText(String),
    Text(String),
    Ime(SessionIme),
    Focus(bool),
    FocusMove(SessionFocusDirection),
    Cancel,
}

/// The transport method requested by a form submission.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum SessionFormMethod {
    #[default]
    Get,
    Post,
}

/// A form submission assembled by the engine from its retained form state.
/// The host still owns URL resolution, transport, policy, and navigation.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionFormSubmission {
    pub action: String,
    pub method: SessionFormMethod,
    pub fields: Vec<(String, String)>,
}

/// Semantic effect of one session input. Navigation remains a host action;
/// sessions name the target or submission and never fetch a replacement page.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SessionEffect {
    Ignored,
    Handled,
    Navigate(String),
    Submit(SessionFormSubmission),
    Cancelled,
}

impl SessionEffect {
    pub fn is_handled(&self) -> bool {
        !matches!(self, Self::Ignored)
    }

    /// Whether the host may apply a keyboard scroll default after this input.
    pub fn allows_default_scroll(&self, editable: bool) -> bool {
        !self.is_handled() && !editable
    }
}

/// Complete result of one input dispatch, including presentation requests
/// that belong to the host adapter rather than the document engine.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionInputResult {
    pub effect: SessionEffect,
    pub cursor: Option<SessionCursor>,
    /// `Some(true)` begins primary-pointer capture and `Some(false)` releases it.
    pub capture: Option<bool>,
    /// Whether keyboard defaults such as arrow-key scrolling must yield to an
    /// editable control after this dispatch.
    pub editable: bool,
}

impl SessionInputResult {
    fn new(effect: SessionEffect, editable: bool) -> Self {
        Self {
            effect,
            cursor: None,
            capture: None,
            editable,
        }
    }
}

/// Navigation commands owned by the host around a retained session.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SessionNavigationCommand {
    Address(String),
    Reload,
    Stop,
    Back,
    Forward,
}

/// Keyboard scroll intents, host-neutral. Adapters map these onto their
/// document lane's own scroll vocabulary; this contract does not drag a
/// layout dependency into Inker.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SessionScrollKey {
    LineUp,
    LineDown,
    PageUp,
    PageDown,
    Home,
    End,
}

/// A same-device producer texture placed within the latest session frame.
/// Keys identify host-registered textures, never arbitrary document resources.
#[derive(Clone, Debug, PartialEq)]
pub struct SessionExternalTextureDraw {
    pub texture_key: u64,
    pub dest_rect: [f32; 4],
    pub opacity: f32,
    /// Insert immediately before this operation index in the returned frame.
    pub scene_op_boundary: usize,
}

// ── Traits ─────────────────────────────────────────────────────────────────

/// Work a hosted document still owns after the current turn.
///
/// The delay is relative to the host clock at the point of inspection. A
/// session with no pending work returns [`Self::idle`]. The source flags keep
/// the completion receipt honest while the wake deadline lets a host sleep
/// until a timer is due instead of repainting continuously.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SessionPendingWork {
    /// Time until the earliest runtime timer is due, if the session exposes
    /// one. A zero delay means the host should wake immediately.
    pub timer: Option<Duration>,
    /// Whether the session still has microtasks to drain on its next pump.
    pub microtasks: bool,
    /// Whether a host-owned asynchronous source may complete the session.
    pub external: bool,
}

impl SessionPendingWork {
    pub const fn idle() -> Self {
        Self {
            timer: None,
            microtasks: false,
            external: false,
        }
    }

    pub const fn timer(delay: Duration) -> Self {
        Self {
            timer: Some(delay),
            microtasks: false,
            external: false,
        }
    }

    pub const fn is_idle(self) -> bool {
        self.timer.is_none() && !self.microtasks && !self.external
    }

    /// Whether script-visible completion has settled. A future timer may still
    /// repaint the page, but it does not keep a completion receipt open; host
    /// external work and microtasks do.
    pub const fn is_settled(self) -> bool {
        !self.microtasks && !self.external
    }

    /// Convert the session-relative delay into the host's next wake deadline.
    pub fn next_wake(self, now: Instant) -> Option<Instant> {
        if self.microtasks {
            Some(now)
        } else {
            self.timer.map(|delay| now + delay)
        }
    }
}

// ── Host mutation ──────────────────────────────────────────────────────────

/// One host-driven DOM change, named in engine-neutral terms.
///
/// This is the **non-script** mutation entry: a Rust host changes the loaded
/// document directly, the way Cambium's Rootstock drives its own DOM through
/// `LayoutDomMut`, without a script engine in the picture. Sessions translate
/// it into their own node ids and their own `drain_mutations` / restyle path;
/// nothing about node identity, dirty bits, or style crosses this boundary.
///
/// The target is an element's `id` attribute rather than an opaque node
/// handle, because a host that did not build the document has no other stable
/// name for one of its elements.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HostMutation {
    /// The value of the target element's `id` attribute.
    pub target_id: String,
    pub op: HostMutationOp,
}

impl HostMutation {
    pub fn new(target_id: impl Into<String>, op: HostMutationOp) -> Self {
        Self {
            target_id: target_id.into(),
            op,
        }
    }
}

/// What a [`HostMutation`] does to its target. The four shapes the T3
/// instrument needs: replace an attribute (`style`, `class`), drop one, grow
/// the subtree, shrink it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum HostMutationOp {
    /// Set or replace an attribute in the null namespace.
    SetAttribute { name: String, value: String },
    /// Remove an attribute; absent is not an error.
    RemoveAttribute { name: String },
    /// Append one element child, optionally carrying a class and one text node.
    AppendChild {
        tag: String,
        class: Option<String>,
        text: Option<String>,
    },
    /// Remove the target's last element child. A target with no element child
    /// is reported as a miss, not an error.
    RemoveLastChild,
}

/// What one [`DocumentSession::apply_host_mutations`] batch actually did.
///
/// `restyled_elements` is the engine's own count for the batch, so a host
/// receipt can say the mutation reached style rather than assuming it did.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct HostMutationReport {
    /// Mutations whose target resolved and whose operation was performed.
    pub applied: usize,
    /// Mutations whose target id did not resolve, or whose operation had
    /// nothing to act on (a `RemoveLastChild` on a childless element).
    pub missed: usize,
    /// Elements whose cascade the engine recomputed for this batch.
    pub restyled_elements: usize,
}

/// Spawns retained document sessions for the engine id it claims. Registered
/// once per host; holds its lane's construction seams (fetcher, cookie jar,
/// theme) so the spawn request stays plain data.
/// Exact document request intent, independent of any transport crate.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionDocumentRequest {
    pub url: String,
    pub method: String,
    pub headers: Vec<(String, String)>,
    pub body: Option<Vec<u8>>,
    pub cache: String,
    pub redirect: String,
    pub mode: String,
    /// Raw initiating document URL, also needed for origin eligibility.
    pub referrer: String,
    pub referrer_policy: String,
    pub credentials: String,
    pub integrity: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionEncodedFormSubmission {
    pub request: SessionDocumentRequest,
    pub target: String,
}
pub struct SessionRequestSpawnResult<F> {
    pub session: Box<dyn DocumentSession<F>>,
    pub navigation_address: String,
}

/// The compatibility input dispatcher, shared by lanes which clear pending
/// request state before delegating to these actual interaction hooks.
pub fn dispatch_session_input<F, S: DocumentSession<F> + ?Sized>(
    session: &mut S, input: SessionInput,
) -> SessionInputResult {
        match input {
            SessionInput::PointerMoved { x, y, .. } => {
                let cursor = session.cursor_at(x, y);
                let effect = if session.pointer_move(x, y) {
                    SessionEffect::Handled
                } else {
                    SessionEffect::Ignored
                };
                let mut result = SessionInputResult::new(effect, session.editable_focus());
                result.cursor = Some(cursor);
                result
            },
            SessionInput::PointerButton {
                x,
                y,
                button: SessionPointerButton::Primary,
                state,
                ..
            } => {
                let cursor = session.cursor_at(x, y);
                let click = match state {
                    SessionButtonState::Pressed => session.pointer_down(x, y),
                    SessionButtonState::Released => session.pointer_up(x, y),
                };
                let effect = session.effect_for_click(click);
                let handled = effect.is_handled();
                let mut result = SessionInputResult::new(effect, session.editable_focus());
                result.cursor = Some(cursor);
                result.capture = Some(matches!(state, SessionButtonState::Pressed) && handled);
                result
            },
            SessionInput::PointerButton { x, y, .. } => {
                let mut result =
                    SessionInputResult::new(SessionEffect::Ignored, session.editable_focus());
                result.cursor = Some(session.cursor_at(x, y));
                result
            },
            SessionInput::Key {
                key,
                state,
                modifiers,
                repeat,
            } => SessionInputResult::new(
                session.key_input(key, state, modifiers, repeat),
                session.editable_focus(),
            ),
            SessionInput::KeyboardText(text) => {
                let effect = if session.keyboard_text_input(&text) {
                    SessionEffect::Handled
                } else {
                    SessionEffect::Ignored
                };
                SessionInputResult::new(effect, session.editable_focus())
            },
            SessionInput::Text(text) => {
                let effect = if session.text_input(&text) {
                    SessionEffect::Handled
                } else {
                    SessionEffect::Ignored
                };
                SessionInputResult::new(effect, session.editable_focus())
            },
            SessionInput::Ime(ime) => {
                let effect = if session.ime_input(ime) {
                    SessionEffect::Handled
                } else {
                    SessionEffect::Ignored
                };
                SessionInputResult::new(effect, session.editable_focus())
            },
            SessionInput::Focus(focused) => {
                session.focus_input(focused);
                SessionInputResult::new(SessionEffect::Handled, session.editable_focus())
            },
            SessionInput::FocusMove(direction) => {
                let effect = if session.focus_move(direction) {
                    SessionEffect::Handled
                } else {
                    SessionEffect::Ignored
                };
                SessionInputResult::new(effect, session.editable_focus())
            },
            SessionInput::Cancel => {
                let effect = if session.cancel_input() {
                    SessionEffect::Cancelled
                } else {
                    SessionEffect::Ignored
                };
                SessionInputResult::new(effect, session.editable_focus())
            },
        }
    }

pub trait SessionEngine<F>: Send + Sync {
    /// Stable engine identifier. Must match the `engine_id` of the
    /// `EngineRouteDecision` that selected this engine.
    fn engine_id(&self) -> &str;

    fn spawn(
        &self,
        request: &SessionSpawnRequest,
    ) -> Result<Box<dyn DocumentSession<F>>, SessionError>;

    /// Optional exact-request construction through this selected factory.
    fn spawn_request(
        &self,
        _spawn: &SessionSpawnRequest,
        _request: &SessionDocumentRequest,
    ) -> Result<SessionRequestSpawnResult<F>, SessionError> {
        Err(SessionError::Unsupported("request-aware document construction".into()))
    }

    /// Sessions lay real content out through a real layout engine, so unlike
    /// surface engines they default to [`A11yCapability::Partial`]; a lane
    /// with a full semantic tree overrides to `Full`.
    fn a11y_capability(&self) -> A11yCapability {
        A11yCapability::Partial
    }
}

/// A live document: a retained layout session producing paint frames.
///
/// All methods take `&mut self`; the session is single-owner, driven from the
/// host's content thread — exactly how the lane types are driven today. Not
/// `Send` by default (scripted lanes hold JS engine state).
pub trait DocumentSession<F>: Any {
    /// Consume the encoded request paired with the latest input's Submit.
    fn take_encoded_form_submission(&mut self) -> Option<SessionEncodedFormSubmission> { None }
    /// Visible top-document identity, distinct from an effective resource base.
    fn current_address(&self) -> Option<String> { None }

    /// Document-facing controls this retained session can presently serve.
    ///
    /// A session can expose find while leaving page zoom and raster capture to
    /// its host. Retained navigation is commonly partial because the host owns
    /// lineage, policy, and refetch.
    fn document_capabilities(&self) -> DocumentCapabilities {
        DocumentCapabilities::default()
    }

    /// Lay out (if needed) and paint at the given viewport. Resize is
    /// implicit: a size change re-lays-out, same as the lanes today.
    fn frame(&mut self, width: u32, height: u32) -> F;

    /// Paint a frame while preserving an engine's refusal reason. Existing
    /// infallible sessions inherit the ordinary frame path.
    fn try_frame(&mut self, width: u32, height: u32) -> Result<F, String> {
        Ok(self.frame(width, height))
    }

    /// Producer draws associated with the most recent [`Self::frame`].
    fn external_texture_draws(&self) -> &[SessionExternalTextureDraw] {
        &[]
    }

    /// Scroll the viewport; `true` if the offset changed.
    fn scroll_by(&mut self, dx: f32, dy: f32) -> bool;

    /// Scroll the scrollable under `(x, y)` (nested scrollers); `true` if an
    /// offset changed. Defaults to viewport scroll for single-scroller lanes.
    fn scroll_at(&mut self, _x: f32, _y: f32, dx: f32, dy: f32) -> bool {
        self.scroll_by(dx, dy)
    }

    fn scroll_for_key(&mut self, key: SessionScrollKey) -> bool;

    /// Jump to an absolute vertical offset (anchor / fragment navigation).
    /// Defaulted no-op for lanes without absolute addressing; lanes that
    /// track their offset override.
    fn scroll_to(&mut self, _y: f32) {}

    fn click_at(&mut self, x: f32, y: f32) -> SessionClick;

    /// Begin a primary-pointer gesture in lane-local coordinates.
    ///
    /// The default preserves the original click-on-press contract for lanes
    /// that have not adopted gesture state. Text-selecting lanes override this
    /// to retain an anchor and defer link activation until pointer-up.
    fn pointer_down(&mut self, x: f32, y: f32) -> SessionClick {
        self.click_at(x, y)
    }

    /// Extend the captured primary-pointer gesture. `true` means visible
    /// session state changed and the host should redraw.
    fn pointer_move(&mut self, _x: f32, _y: f32) -> bool {
        false
    }

    /// Finish the captured primary-pointer gesture.
    ///
    /// Lanes retaining text selection return [`SessionClick::Handled`] for a
    /// non-collapsed selection, or the ordinary click result when the gesture
    /// collapsed.
    fn pointer_up(&mut self, _x: f32, _y: f32) -> SessionClick {
        SessionClick::Miss
    }

    /// Dispatch host-neutral input through the lane's retained interaction
    /// hooks. Existing click/pointer implementations remain the compatibility
    /// floor; richer lanes override the focused keyboard, text, IME, cursor,
    /// and form hooks below.
    fn input(&mut self, input: SessionInput) -> SessionInputResult {
        dispatch_session_input(self, input)
    }

    fn effect_for_click(&mut self, click: SessionClick) -> SessionEffect {
        match click {
            SessionClick::Navigate(target) => SessionEffect::Navigate(target),
            SessionClick::Submit(action) => SessionEffect::Submit(self.form_submission(&action)),
            SessionClick::Handled => SessionEffect::Handled,
            SessionClick::Miss => SessionEffect::Ignored,
        }
    }

    /// Dispatch a keyboard event and non-text default. Printable text arrives
    /// separately through `keyboard_text_input` for the same press.
    fn key_input(
        &mut self,
        _key: SessionKey,
        _state: SessionButtonState,
        _modifiers: SessionModifiers,
        _repeat: bool,
    ) -> SessionEffect {
        SessionEffect::Ignored
    }

    /// Insert text paired with the preceding physical key. Override to honor
    /// cancellation while keeping independent `text_input` available.
    fn keyboard_text_input(&mut self, text: &str) -> bool {
        self.text_input(text)
    }

    /// Insert independent text, including paste or accessibility edits.
    fn text_input(&mut self, _text: &str) -> bool {
        false
    }

    fn ime_input(&mut self, ime: SessionIme) -> bool {
        match ime {
            SessionIme::Commit(text) => self.text_input(&text),
            SessionIme::Enabled | SessionIme::Preedit { .. } | SessionIme::Disabled => false,
        }
    }

    fn focus_input(&mut self, _focused: bool) {}

    fn focus_move(&mut self, _direction: SessionFocusDirection) -> bool {
        false
    }

    fn cancel_input(&mut self) -> bool {
        false
    }

    fn editable_focus(&self) -> bool {
        false
    }

    /// Observe the focused writable text control against a current completed
    /// layout. `None` means there is no usable text-control observation (or
    /// this session does not implement it). This read must not trigger layout.
    /// Hosts publish refreshed geometry after preparing the next frame.
    fn text_input_state(&self) -> Option<crate::SessionTextInputState> {
        None
    }

    fn cursor_at(&self, _x: f32, _y: f32) -> SessionCursor {
        SessionCursor::Default
    }

    fn form_submission(&mut self, action: &str) -> SessionFormSubmission {
        SessionFormSubmission {
            action: action.to_owned(),
            ..Default::default()
        }
    }

    /// Resolve the first laid-out occurrence of `text` to pointer endpoints.
    /// This remains read-only: callers must drive the normal pointer lifecycle
    /// to create selection state.
    fn text_target(&self, _text: &str) -> Option<SessionTextTarget> {
        None
    }

    /// Replace the retained find model for this session and reveal its first
    /// match. Engines own their document internals; the host receives only the
    /// portable model.
    fn document_find(
        &mut self,
        _query: &DocumentFindQuery,
    ) -> Result<DocumentFindState, SessionError> {
        Err(SessionError::Unsupported(
            "document find is not wired for this session".into(),
        ))
    }

    /// Step the current retained model, wrapping at either end.
    fn document_find_step(
        &mut self,
        _direction: DocumentFindDirection,
    ) -> Result<DocumentFindState, SessionError> {
        Err(SessionError::Unsupported(
            "document find is not wired for this session".into(),
        ))
    }

    fn clear_document_find(&mut self) -> Result<(), SessionError> {
        Ok(())
    }

    /// Present this document at an absolute page-zoom `factor` (1.0 = 100 %).
    ///
    /// This is user-agent document zoom, not CSS `zoom`: the CSS viewport
    /// shrinks as the factor grows, media queries re-evaluate against it, and
    /// the engine scales its rendered output back up. Host chrome is never
    /// scaled. The caller owns its own ladder and persistence — reset is
    /// `factor` 1.0 — while the engine owns only bounds and quantization, which
    /// it reports in the returned [`DocumentZoomState`].
    fn set_page_zoom(&mut self, _factor: f32) -> Result<DocumentZoomState, SessionError> {
        Err(SessionError::Unsupported(
            "page zoom is not wired for this session".into(),
        ))
    }

    /// Capture immediately from this retained session. Retained sessions have
    /// no event queue solely for capture symmetry; a future implementation can
    /// return the same output vocabulary directly.
    fn capture_page(
        &mut self,
        _request: PageCaptureRequest,
    ) -> Result<PageCaptureOutput, SessionError> {
        Err(SessionError::Unsupported(
            "page capture is not wired for this session".into(),
        ))
    }

    /// The link hit-table off the retained layout (no live-DOM query per
    /// click) — the mechanism all three lanes already share.
    fn links(&self) -> Vec<SessionLink>;

    /// Full laid-out content height at this viewport, for hosts that band
    /// scenes. Sessions that scroll internally return the viewport height.
    fn content_height(&mut self, _width: u32, height: u32) -> u32 {
        height
    }

    /// Absolute subresource URLs this retained session wants the host to
    /// fetch. The host owns transport, trust, credentials, and scheduling;
    /// sessions only name resources needed for their current presentation.
    fn subresources(&self) -> Vec<String> {
        Vec::new()
    }

    /// Deliver one host-fetched subresource. `true` means visible session
    /// state changed and the host should redraw.
    fn provide_subresource(&mut self, _url: &str, _bytes: &[u8]) -> bool {
        false
    }

    /// Apply one batch of host-driven DOM changes before the next
    /// [`Self::frame`], and report what the batch did.
    ///
    /// The batch is applied as one turn — resolve, mutate, drain, restyle —
    /// so a host pays one invalidation for the whole set rather than one per
    /// mutation. Sessions whose DOM is immutable leave this unsupported; the
    /// host reports the absence rather than quietly rendering an unchanged
    /// document.
    fn apply_host_mutations(
        &mut self,
        _mutations: &[HostMutation],
    ) -> Result<HostMutationReport, SessionError> {
        Err(SessionError::Unsupported(
            "host mutation is not wired for this session".into(),
        ))
    }

    /// Element `id` attributes beginning with `prefix`, in document order.
    ///
    /// The companion read to [`Self::apply_host_mutations`]: a host driving a
    /// deterministic mutation pattern over "the controls" needs to name them
    /// without having counted the document by hand. Empty for sessions with no
    /// element-id plane.
    fn element_ids_with_prefix(&self, _prefix: &str) -> Vec<String> {
        Vec::new()
    }

    /// Drive timers / pending script work (scripted lanes). No-op default.
    fn pump(&mut self, _now_ms: f64) {}

    /// Cumulative garbage-collection tally since this session was spawned:
    /// `(reflectors_unpinned, nodes_collected)`. This is the engine-owned
    /// inspection seam a host correlates with its captured frame to confirm
    /// collection (G5's Lifetime contract), not a live API surface for
    /// script. Static and non-scripted lanes have nothing to report.
    fn collection_stats(&self) -> (usize, usize) {
        (0, 0)
    }

    /// Report the work that should wake this session after the current turn.
    ///
    /// Static sessions remain idle. Scripted sessions report their earliest
    /// timer and set `external` while host-owned fetch or Worker work remains.
    fn pending_work(&mut self) -> SessionPendingWork {
        SessionPendingWork::idle()
    }

    /// Whether script-visible completion has settled: no pending microtasks
    /// or host-owned external work. Future timers do not block completion.
    /// This handshake does not track layout dirtiness or establish rendered
    /// quiescence. Static lanes are always settled by default.
    fn settled(&mut self) -> bool {
        self.pending_work().is_settled()
    }

    /// Visibility hint (a hidden tile may skip raster-adjacent work).
    fn set_hidden(&mut self, _hidden: bool) {}

    /// Whether the host can suspend and resume this session's task delivery.
    /// A hidden presentation still runs throttled work and is distinct from
    /// this lifecycle control.
    fn supports_freeze_resume(&self) -> bool {
        false
    }

    /// Suspend all document task delivery after its lifecycle event. Sessions
    /// without this capability leave the request unchanged.
    fn freeze(&mut self) {}

    /// Restore task delivery and dispatch the document's resume event.
    fn resume(&mut self) {}

    /// A structural [`ContentReport`] of the addressed content, for hosts that
    /// cannot downcast to the concrete session type (it may be private to its
    /// engine crate — turnstone's one registered lane is exactly that case, which
    /// is why this is a trait method and not an `as_any` detour). `None` for
    /// lanes without a structural read; the host reports the absence honestly
    /// rather than synthesizing one.
    fn inspect(&self) -> Option<ContentReport> {
        None
    }

    /// Capture the current semantic clip. `None` means this document lane
    /// cannot supply clip content; hosts must not synthesize authority or
    /// recover source bytes by downcasting.
    fn clip(&self) -> Option<DocumentClip> {
        None
    }

    /// Current renderer-neutral semantic snapshot of this retained document.
    ///
    /// The projection, when present, is the live truth about semantic
    /// completeness and limitations. It replaces host-side guesses based on
    /// concrete session type. Local IDs remain stable for the same semantic
    /// object across revisions and must be namespaced by a host before entering
    /// a global accessibility tree.
    fn accessibility_projection(&self) -> Option<DocumentA11yProjection> {
        None
    }

    /// Revalidate an advertised clickable node and return its current pointer
    /// target. Hosts use the returned point with their ordinary `click_at`
    /// path, keeping link routing and host navigation custody unchanged.
    ///
    /// A `None` result means the node is stale, no longer clickable, or its
    /// geometry is unavailable. The returned revision must match the current
    /// projection before the host acts on it.
    fn accessibility_click_target(
        &self,
        _target: DocumentA11yNodeId,
    ) -> Option<DocumentA11yClickTarget> {
        None
    }

    /// Revalidate and dispatch a non-pointer accessibility action.
    ///
    /// Engines return `true` only after accepting a request whose revision and
    /// target are current and whose action is advertised by that target.
    /// `Click` intentionally returns `false`: it travels through
    /// [`Self::accessibility_click_target`] and the ordinary pointer path.
    fn dispatch_accessibility_action(&mut self, _request: &DocumentA11yActionRequest) -> bool {
        false
    }

    /// Lane-specific extras (a scripted lane's DOM stats, a static lane's
    /// content report) stay on the concrete type; hosts that need them
    /// downcast through here rather than the trait growing every lane's
    /// diagnostics.
    fn as_any_ref(&self) -> &dyn Any;

    fn as_any(&mut self) -> &mut dyn Any;
}

// ── Registry ───────────────────────────────────────────────────────────────

/// Session engines keyed by engine id, one registry per host frame type.
#[derive(Default)]
pub struct SessionRegistry<F> {
    engines: HashMap<String, Box<dyn SessionEngine<F>>>,
}

impl<F> SessionRegistry<F> {
    pub fn new() -> Self {
        Self {
            engines: HashMap::new(),
        }
    }

    /// Register an engine under its own id. Last registration wins, matching
    /// `EngineRegistry` semantics.
    pub fn register(&mut self, engine: Box<dyn SessionEngine<F>>) {
        self.engines.insert(engine.engine_id().to_string(), engine);
    }

    pub fn contains(&self, engine_id: &str) -> bool {
        self.engines.contains_key(engine_id)
    }

    pub fn get(&self, engine_id: &str) -> Option<&dyn SessionEngine<F>> {
        self.engines.get(engine_id).map(|e| e.as_ref())
    }

    pub fn spawn(
        &self,
        engine_id: &str,
        request: &SessionSpawnRequest,
    ) -> Result<Box<dyn DocumentSession<F>>, SessionError> {
        self.engines
            .get(engine_id)
            .ok_or_else(|| SessionError::EngineNotFound(engine_id.to_string()))?
            .spawn(request)
    }

    pub fn engine_ids(&self) -> impl Iterator<Item = &str> {
        self.engines.keys().map(String::as_str)
    }
}

// ── Kind facade ────────────────────────────────────────────────────────────

/// Which registries hold an engine id. An id may be held by more than one
/// kind (a smolweb format can have both a block engine for cards and a
/// session engine for tiles); the HOST picks by surface context, so this is
/// reported as flags, not a single kind.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct EngineKinds {
    pub document: bool,
    pub session: bool,
    pub surface: bool,
}

impl EngineKinds {
    pub fn any(&self) -> bool {
        self.document || self.session || self.surface
    }
}

/// Non-generic id-to-kind resolution: which registries hold each id is just
/// a map, so hosts resolve kinds without threading the frame type through
/// code that never touches frames. Built after registration from the
/// registries' id sets; host-handled ids (internal pages, ingest markers)
/// are the host's own vocabulary and deliberately absent.
#[derive(Clone, Debug, Default)]
pub struct EngineKindIndex {
    kinds: HashMap<String, EngineKinds>,
}

impl EngineKindIndex {
    pub fn build<'a>(
        document_ids: impl IntoIterator<Item = &'a str>,
        session_ids: impl IntoIterator<Item = &'a str>,
        surface_ids: impl IntoIterator<Item = &'a str>,
    ) -> Self {
        let mut kinds: HashMap<String, EngineKinds> = HashMap::new();
        for id in document_ids {
            kinds.entry(id.to_string()).or_default().document = true;
        }
        for id in session_ids {
            kinds.entry(id.to_string()).or_default().session = true;
        }
        for id in surface_ids {
            kinds.entry(id.to_string()).or_default().surface = true;
        }
        Self { kinds }
    }

    pub fn kinds_of(&self, engine_id: &str) -> EngineKinds {
        self.kinds.get(engine_id).copied().unwrap_or_default()
    }
}

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

    /// A frame type that just records what was rendered.
    type TextFrame = String;

    struct EchoSession {
        address: String,
        scroll: f32,
        hidden: bool,
    }

    impl DocumentSession<TextFrame> for EchoSession {
        fn frame(&mut self, width: u32, height: u32) -> TextFrame {
            format!("{} @ {width}x{height} scroll={}", self.address, self.scroll)
        }
        fn scroll_by(&mut self, _dx: f32, dy: f32) -> bool {
            self.scroll += dy;
            dy != 0.0
        }
        fn scroll_for_key(&mut self, key: SessionScrollKey) -> bool {
            self.scroll_by(
                0.0,
                if key == SessionScrollKey::PageDown {
                    100.0
                } else {
                    0.0
                },
            )
        }
        fn click_at(&mut self, x: f32, _y: f32) -> SessionClick {
            if x < 10.0 {
                SessionClick::Navigate("gemini://example.test/".into())
            } else {
                SessionClick::Miss
            }
        }
        fn links(&self) -> Vec<SessionLink> {
            vec![SessionLink {
                url: "gemini://example.test/".into(),
                rect: [0.0, 0.0, 10.0, 10.0],
            }]
        }
        fn set_hidden(&mut self, hidden: bool) {
            self.hidden = hidden;
        }
        fn as_any_ref(&self) -> &dyn Any {
            self
        }
        fn as_any(&mut self) -> &mut dyn Any {
            self
        }
    }

    struct EchoSessionEngine;

    impl SessionEngine<TextFrame> for EchoSessionEngine {
        fn engine_id(&self) -> &str {
            "echo.session"
        }
        fn spawn(
            &self,
            request: &SessionSpawnRequest,
        ) -> Result<Box<dyn DocumentSession<TextFrame>>, SessionError> {
            if request.address.is_empty() {
                return Err(SessionError::SpawnFailed("empty address".into()));
            }
            Ok(Box::new(EchoSession {
                address: request.address.clone(),
                scroll: 0.0,
                hidden: request.hidden,
            }))
        }
    }

    #[test]
    fn registry_spawns_and_drives_a_session() {
        let mut registry = SessionRegistry::new();
        registry.register(Box::new(EchoSessionEngine));

        let request = SessionSpawnRequest::new("https://example.test").with_viewport(800, 600);
        let mut session = registry.spawn("echo.session", &request).expect("spawns");

        assert_eq!(
            session.frame(800, 600),
            "https://example.test @ 800x600 scroll=0"
        );
        assert!(session.scroll_by(0.0, 42.0));
        assert!(session.frame(800, 600).ends_with("scroll=42"));
        assert_eq!(
            session.click_at(5.0, 5.0),
            SessionClick::Navigate("gemini://example.test/".into())
        );
        assert_eq!(session.click_at(50.0, 5.0), SessionClick::Miss);
        assert_eq!(session.links().len(), 1);
        // Static-lane defaults: settled immediately, pump is a no-op.
        assert!(session.settled());
        session.pump(16.0);
    }

    #[test]
    fn document_session_capture_defaults_to_unsupported() {
        let mut session = EchoSession {
            address: "https://example.test".into(),
            scroll: 0.0,
            hidden: false,
        };
        assert!(matches!(
            session.capture_page(PageCaptureRequest::viewport(PageCaptureRequestId::new(9))),
            Err(SessionError::Unsupported(_))
        ));
    }

    #[test]
    fn document_session_accessibility_defaults_to_an_honest_absence() {
        let mut session = EchoSession {
            address: "https://example.test".into(),
            scroll: 0.0,
            hidden: false,
        };
        let target = DocumentA11yNodeId::new(7);
        assert_eq!(session.accessibility_projection(), None);
        assert_eq!(session.accessibility_click_target(target), None);
        assert!(
            !session.dispatch_accessibility_action(&DocumentA11yActionRequest {
                revision: 1,
                target,
                action: crate::DocumentA11yAction::Focus,
                data: None,
            })
        );
    }

    #[test]
    fn neutral_pointer_dispatch_preserves_navigation_cursor_and_capture() {
        let mut registry = SessionRegistry::new();
        registry.register(Box::new(EchoSessionEngine));
        let mut session = registry
            .spawn(
                "echo.session",
                &SessionSpawnRequest::new("https://example.test"),
            )
            .expect("spawns");

        let pressed = session.input(SessionInput::PointerButton {
            x: 5.0,
            y: 5.0,
            button: SessionPointerButton::Primary,
            state: SessionButtonState::Pressed,
            modifiers: SessionModifiers::default(),
        });
        assert_eq!(
            pressed.effect,
            SessionEffect::Navigate("gemini://example.test/".into())
        );
        assert_eq!(pressed.cursor, Some(SessionCursor::Default));
        assert_eq!(pressed.capture, Some(true));

        let released = session.input(SessionInput::PointerButton {
            x: 5.0,
            y: 5.0,
            button: SessionPointerButton::Primary,
            state: SessionButtonState::Released,
            modifiers: SessionModifiers::default(),
        });
        assert_eq!(released.effect, SessionEffect::Ignored);
        assert_eq!(released.capture, Some(false));
    }

    #[test]
    fn unknown_engine_is_a_named_error() {
        let registry: SessionRegistry<TextFrame> = SessionRegistry::new();
        let err = match registry.spawn("nope", &SessionSpawnRequest::new("x")) {
            Ok(_) => panic!("unknown engine must not spawn"),
            Err(err) => err,
        };
        assert_eq!(err, SessionError::EngineNotFound("nope".into()));
    }

    #[test]
    fn downcast_reaches_lane_extras() {
        let mut registry = SessionRegistry::new();
        registry.register(Box::new(EchoSessionEngine));
        let mut session = registry
            .spawn("echo.session", &SessionSpawnRequest::new("a"))
            .unwrap();
        session.set_hidden(true);
        assert!(
            session.as_any_ref().downcast_ref::<EchoSession>().is_some(),
            "immutable hosts can reach lane extras without taking session ownership"
        );
        let echo = session
            .as_any()
            .downcast_mut::<EchoSession>()
            .expect("concrete lane type reachable");
        assert!(echo.hidden);
    }

    #[test]
    fn kind_index_reports_flags_not_a_single_kind() {
        let mut sessions: SessionRegistry<TextFrame> = SessionRegistry::new();
        sessions.register(Box::new(EchoSessionEngine));

        // An id may be held by more than one kind (block engine for cards +
        // session engine for tiles); the index reports flags, host picks.
        let index = EngineKindIndex::build(
            ["nematic.gemtext"],
            sessions.engine_ids().chain(["nematic.gemtext"]),
            ["scrying.web"],
        );
        assert!(index.kinds_of("echo.session").session);
        let both = index.kinds_of("nematic.gemtext");
        assert!(both.document && both.session && !both.surface);
        assert!(index.kinds_of("scrying.web").surface);
        assert!(!index.kinds_of("absent").any());
    }

    #[test]
    fn page_zoom_is_a_named_absence_until_a_lane_wires_it() {
        let mut session = EchoSession {
            address: "gemini://example.test/".into(),
            scroll: 0.0,
            hidden: false,
        };
        assert!(matches!(
            session.set_page_zoom(1.25),
            Err(SessionError::Unsupported(_))
        ));
    }

    #[test]
    fn zoom_state_keeps_the_request_and_clamps_only_the_applied_value() {
        let state = DocumentZoomState::clamped(9.0, 0.25, 5.0);
        assert_eq!(state.requested, 9.0);
        assert_eq!(state.applied, 5.0);

        let state = DocumentZoomState::clamped(0.1, 0.25, 5.0);
        assert_eq!(state.requested, 0.1);
        assert_eq!(state.applied, 0.25);

        assert_eq!(DocumentZoomState::clamped(1.5, 0.25, 5.0).applied, 1.5);
        assert_eq!(
            DocumentZoomState::clamped(f32::NAN, 0.25, 5.0).applied,
            1.0,
            "a non-finite request must not reach layout as a viewport divisor"
        );
    }

    #[test]
    fn pending_work_exposes_a_sleepable_timer_deadline() {
        let now = std::time::Instant::now();
        let work = SessionPendingWork::timer(std::time::Duration::from_millis(25));
        let deadline = work.next_wake(now).expect("timer has a wake deadline");
        assert!(deadline >= now + std::time::Duration::from_millis(25));
        assert!(!work.is_idle());
        assert!(
            work.is_settled(),
            "a future timer is wakeable without making a live page perpetually unsettled"
        );
        assert!(
            !SessionPendingWork {
                external: true,
                ..SessionPendingWork::idle()
            }
            .is_settled()
        );
        assert!(SessionPendingWork::idle().next_wake(now).is_none());
        assert_eq!(
            SessionPendingWork {
                microtasks: true,
                ..SessionPendingWork::idle()
            }
            .next_wake(now),
            Some(now)
        );
    }

    // TASK5 DRAFT API FIXTURES BEGIN. Missing seams have explicit absence adapters.
    fn t5_api_take_absent(_session: &mut dyn DocumentSession<TextFrame>) -> Option<()> {
        _session.take_encoded_form_submission().map(|_| ())
    }
    fn t5_api_address_absent(_session: &dyn DocumentSession<TextFrame>) -> Option<String> {
        _session.current_address()
    }
    fn t5_api_request_spawn_absent(
        _engine: &dyn SessionEngine<TextFrame>,
        _request: &SessionSpawnRequest,
        _bytes: &[u8],
    ) -> Result<(), SessionError> {
        let request = SessionDocumentRequest { url: _request.address.clone(), method: "POST".into(),
            headers: vec![], body: Some(_bytes.to_vec()), cache: "default".into(), redirect: "follow".into(),
            mode: "navigate".into(), referrer: String::new(), referrer_policy: String::new(),
            credentials: "include".into(), integrity: String::new() };
        _engine.spawn_request(_request, &request).map(|_| ())
    }
    #[test]
    fn phase_c_t5_api_legacy_submission_literal() {
        let value = SessionFormSubmission {
            action: "https://forms.test/send".into(), method: SessionFormMethod::Post,
            fields: vec![("q".into(), "café".into())],
        };
        fn retains_serde<T:serde::Serialize+for<'de>serde::Deserialize<'de>>() {}
        retains_serde::<SessionFormSubmission>();
        let copied=value.clone();
        let SessionFormSubmission{action,method,fields}=copied;
        assert_eq!((action,method,fields),("https://forms.test/send".into(),SessionFormMethod::Post,vec![("q".into(),"café".into())]));
    }
    #[test]
    fn phase_c_t5_api_legacy_result_literal() {
        let value = SessionInputResult { effect: SessionEffect::Handled,
            cursor: Some(SessionCursor::Text), capture: Some(false), editable: true };
        let SessionInputResult { effect, cursor, capture, editable } = value;
        let tag = match effect { SessionEffect::Ignored => 0, SessionEffect::Handled => 1,
            SessionEffect::Navigate(_) => 2, SessionEffect::Submit(_) => 3,
            SessionEffect::Cancelled => 4 };
        assert_eq!((tag, cursor, capture, editable), (1, Some(SessionCursor::Text), Some(false), true));
    }
    #[test]
    fn key_default_scroll_respects_effect_and_effective_editable_focus() {
        let cases = [
            (SessionEffect::Ignored, false, true),
            (SessionEffect::Ignored, true, false),
            (SessionEffect::Handled, false, false),
            (SessionEffect::Cancelled, false, false),
            (SessionEffect::Navigate("https://example.test/next".into()), false, false),
            (SessionEffect::Submit(SessionFormSubmission::default()), false, false),
        ];
        for (effect, editable, expected) in cases {
            assert_eq!(effect.allows_default_scroll(editable), expected, "{effect:?}, editable={editable}");
        }

        // A native navigation can install a new session during dispatch. Its
        // editable focus, rather than the outgoing result's flag, decides the
        // next default action without consuming the typed input result.
        let result = SessionInputResult {
            effect: SessionEffect::Ignored,
            cursor: Some(SessionCursor::Text),
            capture: Some(false),
            editable: false,
        };
        assert!(result.effect.allows_default_scroll(result.editable));
        assert!(!result.effect.allows_default_scroll(true));
        assert_eq!(result.cursor, Some(SessionCursor::Text));
        assert_eq!(result.capture, Some(false));
    }
    #[test]
    fn phase_c_t5_api_legacy_spawn_unicode_body() {
        let request = SessionSpawnRequest { address: "https://forms.test/".into(),
            body: Some("café".into()), content_type: Some("text/html".into()),
            viewport: (320, 240), hidden: false };
        assert_eq!(request.body.as_deref(), Some("café"));
        assert_eq!(SessionSpawnRequest::new("a").with_body("café").body, request.body);
    }
    #[test]
    fn phase_c_t5_api_old_session_accessor_none() {
        let mut old = EchoSession { address: "old".into(), scroll: 0.0, hidden: false };
        assert!(t5_api_take_absent(&mut old).is_none());
        let result = old.input(SessionInput::PointerButton { x: 1.0, y: 1.0,
            button: SessionPointerButton::Primary, state: SessionButtonState::Pressed,
            modifiers: SessionModifiers::default() });
        assert_eq!(result.effect, SessionEffect::Navigate("gemini://example.test/".into()));
    }
    #[test]
    fn phase_c_t5_api_old_factory_rich_decline() {
        let request = SessionSpawnRequest::new("https://forms.test/");
        assert!(matches!(t5_api_request_spawn_absent(&EchoSessionEngine, &request, &[0,128,255]),
            Err(SessionError::Unsupported(_))));
        let mut ordinary = EchoSessionEngine.spawn(&request).unwrap();
        assert!(ordinary.frame(1, 1).starts_with("https://forms.test/"));
    }
    #[test]
    fn phase_c_t5_api_old_session_current_address_none() {
        let old = EchoSession { address: "legacy".into(), scroll: 0.0, hidden: false };
        assert!(t5_api_address_absent(&old).is_none());
        assert_eq!(old.address, "legacy");
    }
    // TASK5 DRAFT API FIXTURES END.
}