Skip to main content

document_session_api/
session_engine.rs

1// Copyright 2026 Mark Alan Boykin
2// This Source Code Form is subject to the terms of the Mozilla Public
3// License, v. 2.0. If a copy of the MPL was not distributed with this
4// file, You can obtain one at https://mozilla.org/MPL/2.0/.
5// SPDX-License-Identifier: MPL-2.0
6
7//! Session-engine traits and registry — the third engine kind
8//! (2026-07-10 session-engines plan).
9//!
10//! Document engines (`Engine`) are request/response: bytes in,
11//! serializable `EngineDocument` blocks out — the stored/authored
12//! lane. Surface engines (`SurfaceEngine`) stream GPU textures from
13//! external producers. Session engines sit between: **retained document
14//! sessions** that lay content out once and then produce paint frames on
15//! demand, with scroll, activation, and (for scripted lanes) a tick +
16//! quiescence seam. The genet HTML lanes and the smolweb native lane are
17//! session engines.
18//!
19//! The frame type is generic (`F`) so this crate keeps zero paint
20//! dependencies: a netrender host instantiates `F = netrender::Scene`; a
21//! different host picks its own frame type. Lane-specific construction seams
22//! (resource fetchers, cookie jars, themes) are injected into the concrete
23//! `SessionEngine` at registration time, not carried in the spawn request —
24//! the request stays plain data.
25
26use std::any::Any;
27use std::collections::HashMap;
28use std::fmt;
29use std::time::{Duration, Instant};
30
31use serde::{Deserialize, Serialize};
32
33use crate::a11y::{
34    DocumentA11yActionRequest, DocumentA11yClickTarget, DocumentA11yNodeId, DocumentA11yProjection,
35};
36use crate::{A11yCapability, DocumentCapabilities, PageCaptureOutput, PageCaptureRequest};
37
38// ── Errors ─────────────────────────────────────────────────────────────────
39
40#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
41pub enum SessionError {
42    EngineNotFound(String),
43    SpawnFailed(String),
44    Unsupported(String),
45}
46
47impl fmt::Display for SessionError {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        match self {
50            Self::EngineNotFound(id) => write!(f, "session engine not registered: {id}"),
51            Self::SpawnFailed(reason) => write!(f, "session spawn failed: {reason}"),
52            Self::Unsupported(reason) => write!(f, "unsupported: {reason}"),
53        }
54    }
55}
56
57impl std::error::Error for SessionError {}
58
59// ── Spawn request ──────────────────────────────────────────────────────────
60
61/// Plain-data request to open a document session. The body is already
62/// fetched when the host has it (mirroring `EngineInput`); a session
63/// engine whose lane fetches for itself (subresources, redirects) uses the
64/// seams it was constructed with.
65#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
66pub struct SessionSpawnRequest {
67    pub address: String,
68    /// Fetched body, when the host fetched it. `None` asks the engine to
69    /// load via its own fetcher seam.
70    pub body: Option<String>,
71    pub content_type: Option<String>,
72    /// Initial viewport, so the first `frame` call needs no resize dance.
73    pub viewport: (u32, u32),
74    /// Spawn hidden (a background tile): the session may defer work the
75    /// visible path would do eagerly.
76    pub hidden: bool,
77}
78
79impl SessionSpawnRequest {
80    pub fn new(address: impl Into<String>) -> Self {
81        Self {
82            address: address.into(),
83            body: None,
84            content_type: None,
85            viewport: (0, 0),
86            hidden: false,
87        }
88    }
89
90    pub fn with_body(mut self, body: impl Into<String>) -> Self {
91        self.body = Some(body.into());
92        self
93    }
94
95    pub fn with_content_type(mut self, content_type: impl Into<String>) -> Self {
96        self.content_type = Some(content_type.into());
97        self
98    }
99
100    pub fn with_viewport(mut self, width: u32, height: u32) -> Self {
101        self.viewport = (width, height);
102        self
103    }
104}
105
106// ── Interaction vocabulary ─────────────────────────────────────────────────
107
108/// A link the session exposes for the host's hit table: url + viewport-space
109/// rect (`[x, y, w, h]`, the shape the lanes already emit).
110#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
111pub struct SessionLink {
112    pub url: String,
113    pub rect: [f32; 4],
114}
115
116/// A structural report of a session's addressed content — title, an outline
117/// of role + name, outgoing links, headings. The introspection CONTRACT for
118/// [`DocumentSession::inspect`]: pure data, so it lives here rather than in a
119/// render crate (genet-render's `content_report` builds one from a LayoutDom
120/// and re-exports these types). Hosts that cannot downcast a session to its
121/// concrete type (the type may be private to its engine crate) read this
122/// instead — turnstone's Inspector pane is the first such consumer.
123#[derive(Clone, Debug, Default, PartialEq)]
124pub struct ContentReport {
125    /// The `<title>` text, if any.
126    pub title: Option<String>,
127    /// The element outline (painted elements only; metadata tags are skipped),
128    /// in document order.
129    pub outline: Vec<OutlineEntry>,
130    /// Outgoing `<a href>` targets, in document order.
131    pub links: Vec<String>,
132    /// Heading (`<h1>`..`<h6>`) text, in document order.
133    pub headings: Vec<String>,
134    /// Derivation evidence when this session presents transformed source bytes.
135    pub lineage: Option<ContentLineage>,
136}
137
138/// Host-neutral derivation evidence for an inspected document session.
139#[derive(Clone, Debug, PartialEq, Eq)]
140pub struct ContentLineage {
141    pub tool: String,
142    pub version: String,
143    pub selector: String,
144    pub score: Option<i32>,
145    pub block_count: usize,
146}
147
148/// The relationship between retained bytes and the representation observed by
149/// a document engine.
150#[derive(Clone, Debug, PartialEq, Eq)]
151pub enum DocumentClipArtifactRole {
152    /// Bytes returned by the source transport before document execution.
153    SourceResponse,
154    /// A serialized representation of the state actually observed by the
155    /// lowering, such as a post-script DOM snapshot.
156    ObservedRepresentation,
157}
158
159/// Exact source material offered with a semantic clip. The receiving domain
160/// decides whether and where to retain it.
161#[derive(Clone, Debug, PartialEq, Eq)]
162pub struct DocumentClipArtifact {
163    pub role: DocumentClipArtifactRole,
164    pub media_type: String,
165    pub canonical_uri: String,
166    pub bytes: Vec<u8>,
167}
168
169/// A host-neutral semantic fragment offered by a retained document session.
170///
171/// Sessions may expose the whole addressed document when they do not implement
172/// range selection. The source address and optional selector keep that
173/// distinction explicit for consumers such as Knot clipping.
174#[derive(Clone, Debug, PartialEq, Eq)]
175pub struct DocumentClip {
176    pub source_url: String,
177    pub title: Option<String>,
178    pub text: String,
179    pub selector: Option<String>,
180    pub links: Vec<String>,
181    /// Source artifacts available from the engine's ordinary retained state.
182    /// Engines must not refetch or reconstruct bytes solely for this field.
183    pub artifacts: Vec<DocumentClipArtifact>,
184}
185
186/// A semantic text occurrence resolved to lane-local pointer coordinates.
187///
188/// Hosts use this for find-to-select and automation without learning a
189/// document engine's DOM ids or text-layout representation. Driving these
190/// points through [`DocumentSession::pointer_down`],
191/// [`DocumentSession::pointer_move`], and [`DocumentSession::pointer_up`] still
192/// exercises the ordinary input path; this is target resolution, not a second
193/// selection mutation API.
194#[derive(Clone, Copy, Debug, PartialEq)]
195pub struct SessionTextTarget {
196    pub anchor: [f32; 2],
197    pub focus: [f32; 2],
198}
199
200/// Direction for stepping a retained document find model.
201#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
202pub enum DocumentFindDirection {
203    Previous,
204    Next,
205}
206
207/// A host-neutral document find query.
208#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
209pub struct DocumentFindQuery {
210    pub text: String,
211    pub match_case: bool,
212}
213
214impl DocumentFindQuery {
215    pub fn new(text: impl Into<String>) -> Self {
216        Self {
217            text: text.into(),
218            match_case: false,
219        }
220    }
221}
222
223/// How selecting a match is revealed by its owning engine.
224#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
225pub enum DocumentFindReveal {
226    /// Retained document-space vertical offset. The session applies it when the
227    /// match becomes current; the value remains observable to automation.
228    ScrollY(f32),
229    /// A hosted engine owns selection and reveal internally.
230    EngineManaged,
231}
232
233/// One retained match, in document order.
234#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
235pub struct DocumentFindMatch {
236    /// Human-readable matched text or accessible element label.
237    pub label: String,
238    /// Coarse semantic role when the engine exposes one.
239    pub role: Option<String>,
240    pub reveal: DocumentFindReveal,
241}
242
243/// The retained result model shared by retained documents and hosted engines.
244#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
245pub struct DocumentFindState {
246    pub query: DocumentFindQuery,
247    /// Authoritative number of matches. Engines that can describe individual
248    /// matches also populate `matches`; engine-managed pages may expose only
249    /// this count and the current ordinal.
250    pub count: usize,
251    pub matches: Vec<DocumentFindMatch>,
252    /// Zero-based index into `matches`.
253    pub current: Option<usize>,
254    /// Hosted engines may report progressive counts. Static sessions are
255    /// complete in their first answer.
256    pub complete: bool,
257}
258
259impl DocumentFindState {
260    pub fn empty(query: DocumentFindQuery) -> Self {
261        Self {
262            query,
263            count: 0,
264            matches: Vec::new(),
265            current: None,
266            complete: true,
267        }
268    }
269
270    /// Adapt an engine-managed count/current callback into the same retained
271    /// model used by static sessions. The engine remains responsible for
272    /// revealing the selected occurrence.
273    pub fn engine_managed(
274        query: DocumentFindQuery,
275        count: usize,
276        active_match: Option<usize>,
277        complete: bool,
278    ) -> Self {
279        Self {
280            query,
281            count,
282            matches: Vec::new(),
283            current: active_match.filter(|index| *index < count),
284            complete,
285        }
286    }
287
288    pub fn current_match(&self) -> Option<&DocumentFindMatch> {
289        self.current.and_then(|index| self.matches.get(index))
290    }
291}
292
293/// The retained page-zoom model shared by retained documents and hosted
294/// engines.
295///
296/// `requested` is the caller's own value, echoed back unchanged: the host
297/// persists it per node and steps its own ladder. `applied` is what the engine
298/// actually used after clamping and any quantization of its own, and `min` /
299/// `max` name the engine's bounds so a host can grey out a step it cannot take.
300#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
301pub struct DocumentZoomState {
302    /// The absolute factor the caller asked for (1.0 = 100 %).
303    pub requested: f32,
304    /// The effective factor this engine is presenting at.
305    pub applied: f32,
306    pub min: f32,
307    pub max: f32,
308}
309
310impl DocumentZoomState {
311    /// Clamp `requested` into `[min, max]` and report both halves. Engines that
312    /// quantize further overwrite `applied` after calling this.
313    pub fn clamped(requested: f32, min: f32, max: f32) -> Self {
314        // A non-finite request is a caller bug rather than a zoom level, and
315        // must never reach layout as a NaN viewport divisor.
316        let applied = if requested.is_finite() {
317            requested.clamp(min, max)
318        } else {
319            1.0_f32.clamp(min, max)
320        };
321        Self {
322            requested,
323            applied,
324            min,
325            max,
326        }
327    }
328}
329
330/// One element in the structural outline.
331#[derive(Clone, Debug, PartialEq)]
332pub struct OutlineEntry {
333    /// Nesting depth among painted elements (the document root is depth 0).
334    pub depth: usize,
335    /// A coarse semantic role (`"link"`, `"heading"`, `"paragraph"`, …).
336    pub role: &'static str,
337    /// The element's accessible name — its direct text content, trimmed.
338    pub name: String,
339}
340
341/// What a click did, unifying the lanes' divergent returns
342/// (`ClickOutcome` / `bool` / `Option<String>`).
343#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
344pub enum SessionClick {
345    /// The click resolved to a navigation the HOST performs (a link).
346    Navigate(String),
347    /// The click resolved to a mutation endpoint. The host must collect and
348    /// confirm a body before submitting it.
349    Submit(String),
350    /// The session consumed the click itself (focus, a scripted handler).
351    Handled,
352    /// Nothing interactive at that point.
353    Miss,
354}
355
356/// Modifier state carried with host-neutral session input.
357#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
358pub struct SessionModifiers {
359    pub shift: bool,
360    pub control: bool,
361    pub alt: bool,
362    pub meta: bool,
363}
364
365/// Pointer buttons understood by a retained document session.
366#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
367pub enum SessionPointerButton {
368    Primary,
369    Secondary,
370    Auxiliary,
371}
372
373/// Press/release state shared by pointer and keyboard events.
374#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
375pub enum SessionButtonState {
376    Pressed,
377    Released,
378}
379
380/// Cursor requested by the retained content under the pointer.
381#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
382pub enum SessionCursor {
383    #[default]
384    Default,
385    Pointer,
386    Text,
387}
388
389/// Keyboard keys with document-level meaning. Text-bearing keys retain the
390/// produced character string so this vocabulary does not assume ASCII.
391#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
392pub enum SessionKey {
393    Character(String),
394    Enter,
395    Tab,
396    Backspace,
397    Delete,
398    Escape,
399    Space,
400    ArrowLeft,
401    ArrowRight,
402    ArrowUp,
403    ArrowDown,
404    Home,
405    End,
406    PageUp,
407    PageDown,
408    Unidentified,
409}
410
411/// Direction requested by focus traversal.
412#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
413pub enum SessionFocusDirection {
414    Forward,
415    Backward,
416}
417
418/// Platform composition lifecycle translated without exposing a windowing
419/// crate to document engines.
420#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
421pub enum SessionIme {
422    Enabled,
423    Preedit {
424        text: String,
425        selection: Option<(usize, usize)>,
426    },
427    Commit(String),
428    Disabled,
429}
430
431/// Input delivered by a host to one retained session. For a printable key,
432/// send `Key` first and then its produced `KeyboardText`. `Key` owns keyboard
433/// events and non-text defaults; `KeyboardText` owns that key's character edit
434/// and can be suppressed by a canceled keydown. `Text` is independent input,
435/// including paste and accessibility, and is never canceled by an earlier key.
436/// An IME commit uses `Ime::Commit`. Send control keys such as Enter only as
437/// `Key`; independent `Text` may contain newlines.
438#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
439pub enum SessionInput {
440    PointerMoved {
441        x: f32,
442        y: f32,
443        modifiers: SessionModifiers,
444    },
445    PointerButton {
446        x: f32,
447        y: f32,
448        button: SessionPointerButton,
449        state: SessionButtonState,
450        modifiers: SessionModifiers,
451    },
452    Key {
453        key: SessionKey,
454        state: SessionButtonState,
455        modifiers: SessionModifiers,
456        repeat: bool,
457    },
458    KeyboardText(String),
459    Text(String),
460    Ime(SessionIme),
461    Focus(bool),
462    FocusMove(SessionFocusDirection),
463    Cancel,
464}
465
466/// The transport method requested by a form submission.
467#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
468pub enum SessionFormMethod {
469    #[default]
470    Get,
471    Post,
472}
473
474/// A form submission assembled by the engine from its retained form state.
475/// The host still owns URL resolution, transport, policy, and navigation.
476#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
477pub struct SessionFormSubmission {
478    pub action: String,
479    pub method: SessionFormMethod,
480    pub fields: Vec<(String, String)>,
481}
482
483/// Semantic effect of one session input. Navigation remains a host action;
484/// sessions name the target or submission and never fetch a replacement page.
485#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
486pub enum SessionEffect {
487    Ignored,
488    Handled,
489    Navigate(String),
490    Submit(SessionFormSubmission),
491    Cancelled,
492}
493
494impl SessionEffect {
495    pub fn is_handled(&self) -> bool {
496        !matches!(self, Self::Ignored)
497    }
498
499    /// Whether the host may apply a keyboard scroll default after this input.
500    pub fn allows_default_scroll(&self, editable: bool) -> bool {
501        !self.is_handled() && !editable
502    }
503}
504
505/// Complete result of one input dispatch, including presentation requests
506/// that belong to the host adapter rather than the document engine.
507#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
508pub struct SessionInputResult {
509    pub effect: SessionEffect,
510    pub cursor: Option<SessionCursor>,
511    /// `Some(true)` begins primary-pointer capture and `Some(false)` releases it.
512    pub capture: Option<bool>,
513    /// Whether keyboard defaults such as arrow-key scrolling must yield to an
514    /// editable control after this dispatch.
515    pub editable: bool,
516}
517
518impl SessionInputResult {
519    fn new(effect: SessionEffect, editable: bool) -> Self {
520        Self {
521            effect,
522            cursor: None,
523            capture: None,
524            editable,
525        }
526    }
527}
528
529/// Navigation commands owned by the host around a retained session.
530#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
531pub enum SessionNavigationCommand {
532    Address(String),
533    Reload,
534    Stop,
535    Back,
536    Forward,
537}
538
539/// Keyboard scroll intents, host-neutral. Adapters map these onto their
540/// document lane's own scroll vocabulary; this contract does not drag a
541/// layout dependency into Inker.
542#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
543pub enum SessionScrollKey {
544    LineUp,
545    LineDown,
546    PageUp,
547    PageDown,
548    Home,
549    End,
550}
551
552/// A same-device producer texture placed within the latest session frame.
553/// Keys identify host-registered textures, never arbitrary document resources.
554#[derive(Clone, Debug, PartialEq)]
555pub struct SessionExternalTextureDraw {
556    pub texture_key: u64,
557    pub dest_rect: [f32; 4],
558    pub opacity: f32,
559    /// Insert immediately before this operation index in the returned frame.
560    pub scene_op_boundary: usize,
561}
562
563// ── Traits ─────────────────────────────────────────────────────────────────
564
565/// Work a hosted document still owns after the current turn.
566///
567/// The delay is relative to the host clock at the point of inspection. A
568/// session with no pending work returns [`Self::idle`]. The source flags keep
569/// the completion receipt honest while the wake deadline lets a host sleep
570/// until a timer is due instead of repainting continuously.
571#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
572pub struct SessionPendingWork {
573    /// Time until the earliest runtime timer is due, if the session exposes
574    /// one. A zero delay means the host should wake immediately.
575    pub timer: Option<Duration>,
576    /// Whether the session still has microtasks to drain on its next pump.
577    pub microtasks: bool,
578    /// Whether a host-owned asynchronous source may complete the session.
579    pub external: bool,
580}
581
582impl SessionPendingWork {
583    pub const fn idle() -> Self {
584        Self {
585            timer: None,
586            microtasks: false,
587            external: false,
588        }
589    }
590
591    pub const fn timer(delay: Duration) -> Self {
592        Self {
593            timer: Some(delay),
594            microtasks: false,
595            external: false,
596        }
597    }
598
599    pub const fn is_idle(self) -> bool {
600        self.timer.is_none() && !self.microtasks && !self.external
601    }
602
603    /// Whether script-visible completion has settled. A future timer may still
604    /// repaint the page, but it does not keep a completion receipt open; host
605    /// external work and microtasks do.
606    pub const fn is_settled(self) -> bool {
607        !self.microtasks && !self.external
608    }
609
610    /// Convert the session-relative delay into the host's next wake deadline.
611    pub fn next_wake(self, now: Instant) -> Option<Instant> {
612        if self.microtasks {
613            Some(now)
614        } else {
615            self.timer.map(|delay| now + delay)
616        }
617    }
618}
619
620// ── Host mutation ──────────────────────────────────────────────────────────
621
622/// One host-driven DOM change, named in engine-neutral terms.
623///
624/// This is the **non-script** mutation entry: a Rust host changes the loaded
625/// document directly, the way Cambium's Rootstock drives its own DOM through
626/// `LayoutDomMut`, without a script engine in the picture. Sessions translate
627/// it into their own node ids and their own `drain_mutations` / restyle path;
628/// nothing about node identity, dirty bits, or style crosses this boundary.
629///
630/// The target is an element's `id` attribute rather than an opaque node
631/// handle, because a host that did not build the document has no other stable
632/// name for one of its elements.
633#[derive(Clone, Debug, PartialEq, Eq)]
634pub struct HostMutation {
635    /// The value of the target element's `id` attribute.
636    pub target_id: String,
637    pub op: HostMutationOp,
638}
639
640impl HostMutation {
641    pub fn new(target_id: impl Into<String>, op: HostMutationOp) -> Self {
642        Self {
643            target_id: target_id.into(),
644            op,
645        }
646    }
647}
648
649/// What a [`HostMutation`] does to its target. The four shapes the T3
650/// instrument needs: replace an attribute (`style`, `class`), drop one, grow
651/// the subtree, shrink it.
652#[derive(Clone, Debug, PartialEq, Eq)]
653pub enum HostMutationOp {
654    /// Set or replace an attribute in the null namespace.
655    SetAttribute { name: String, value: String },
656    /// Remove an attribute; absent is not an error.
657    RemoveAttribute { name: String },
658    /// Append one element child, optionally carrying a class and one text node.
659    AppendChild {
660        tag: String,
661        class: Option<String>,
662        text: Option<String>,
663    },
664    /// Remove the target's last element child. A target with no element child
665    /// is reported as a miss, not an error.
666    RemoveLastChild,
667}
668
669/// What one [`DocumentSession::apply_host_mutations`] batch actually did.
670///
671/// `restyled_elements` is the engine's own count for the batch, so a host
672/// receipt can say the mutation reached style rather than assuming it did.
673#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
674pub struct HostMutationReport {
675    /// Mutations whose target resolved and whose operation was performed.
676    pub applied: usize,
677    /// Mutations whose target id did not resolve, or whose operation had
678    /// nothing to act on (a `RemoveLastChild` on a childless element).
679    pub missed: usize,
680    /// Elements whose cascade the engine recomputed for this batch.
681    pub restyled_elements: usize,
682}
683
684/// Spawns retained document sessions for the engine id it claims. Registered
685/// once per host; holds its lane's construction seams (fetcher, cookie jar,
686/// theme) so the spawn request stays plain data.
687/// Exact document request intent, independent of any transport crate.
688#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
689pub struct SessionDocumentRequest {
690    pub url: String,
691    pub method: String,
692    pub headers: Vec<(String, String)>,
693    pub body: Option<Vec<u8>>,
694    pub cache: String,
695    pub redirect: String,
696    pub mode: String,
697    /// Raw initiating document URL, also needed for origin eligibility.
698    pub referrer: String,
699    pub referrer_policy: String,
700    pub credentials: String,
701    pub integrity: String,
702}
703#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
704pub struct SessionEncodedFormSubmission {
705    pub request: SessionDocumentRequest,
706    pub target: String,
707}
708pub struct SessionRequestSpawnResult<F> {
709    pub session: Box<dyn DocumentSession<F>>,
710    pub navigation_address: String,
711}
712
713/// The compatibility input dispatcher, shared by lanes which clear pending
714/// request state before delegating to these actual interaction hooks.
715pub fn dispatch_session_input<F, S: DocumentSession<F> + ?Sized>(
716    session: &mut S, input: SessionInput,
717) -> SessionInputResult {
718        match input {
719            SessionInput::PointerMoved { x, y, .. } => {
720                let cursor = session.cursor_at(x, y);
721                let effect = if session.pointer_move(x, y) {
722                    SessionEffect::Handled
723                } else {
724                    SessionEffect::Ignored
725                };
726                let mut result = SessionInputResult::new(effect, session.editable_focus());
727                result.cursor = Some(cursor);
728                result
729            },
730            SessionInput::PointerButton {
731                x,
732                y,
733                button: SessionPointerButton::Primary,
734                state,
735                ..
736            } => {
737                let cursor = session.cursor_at(x, y);
738                let click = match state {
739                    SessionButtonState::Pressed => session.pointer_down(x, y),
740                    SessionButtonState::Released => session.pointer_up(x, y),
741                };
742                let effect = session.effect_for_click(click);
743                let handled = effect.is_handled();
744                let mut result = SessionInputResult::new(effect, session.editable_focus());
745                result.cursor = Some(cursor);
746                result.capture = Some(matches!(state, SessionButtonState::Pressed) && handled);
747                result
748            },
749            SessionInput::PointerButton { x, y, .. } => {
750                let mut result =
751                    SessionInputResult::new(SessionEffect::Ignored, session.editable_focus());
752                result.cursor = Some(session.cursor_at(x, y));
753                result
754            },
755            SessionInput::Key {
756                key,
757                state,
758                modifiers,
759                repeat,
760            } => SessionInputResult::new(
761                session.key_input(key, state, modifiers, repeat),
762                session.editable_focus(),
763            ),
764            SessionInput::KeyboardText(text) => {
765                let effect = if session.keyboard_text_input(&text) {
766                    SessionEffect::Handled
767                } else {
768                    SessionEffect::Ignored
769                };
770                SessionInputResult::new(effect, session.editable_focus())
771            },
772            SessionInput::Text(text) => {
773                let effect = if session.text_input(&text) {
774                    SessionEffect::Handled
775                } else {
776                    SessionEffect::Ignored
777                };
778                SessionInputResult::new(effect, session.editable_focus())
779            },
780            SessionInput::Ime(ime) => {
781                let effect = if session.ime_input(ime) {
782                    SessionEffect::Handled
783                } else {
784                    SessionEffect::Ignored
785                };
786                SessionInputResult::new(effect, session.editable_focus())
787            },
788            SessionInput::Focus(focused) => {
789                session.focus_input(focused);
790                SessionInputResult::new(SessionEffect::Handled, session.editable_focus())
791            },
792            SessionInput::FocusMove(direction) => {
793                let effect = if session.focus_move(direction) {
794                    SessionEffect::Handled
795                } else {
796                    SessionEffect::Ignored
797                };
798                SessionInputResult::new(effect, session.editable_focus())
799            },
800            SessionInput::Cancel => {
801                let effect = if session.cancel_input() {
802                    SessionEffect::Cancelled
803                } else {
804                    SessionEffect::Ignored
805                };
806                SessionInputResult::new(effect, session.editable_focus())
807            },
808        }
809    }
810
811pub trait SessionEngine<F>: Send + Sync {
812    /// Stable engine identifier. Must match the `engine_id` of the
813    /// `EngineRouteDecision` that selected this engine.
814    fn engine_id(&self) -> &str;
815
816    fn spawn(
817        &self,
818        request: &SessionSpawnRequest,
819    ) -> Result<Box<dyn DocumentSession<F>>, SessionError>;
820
821    /// Optional exact-request construction through this selected factory.
822    fn spawn_request(
823        &self,
824        _spawn: &SessionSpawnRequest,
825        _request: &SessionDocumentRequest,
826    ) -> Result<SessionRequestSpawnResult<F>, SessionError> {
827        Err(SessionError::Unsupported("request-aware document construction".into()))
828    }
829
830    /// Sessions lay real content out through a real layout engine, so unlike
831    /// surface engines they default to [`A11yCapability::Partial`]; a lane
832    /// with a full semantic tree overrides to `Full`.
833    fn a11y_capability(&self) -> A11yCapability {
834        A11yCapability::Partial
835    }
836}
837
838/// A live document: a retained layout session producing paint frames.
839///
840/// All methods take `&mut self`; the session is single-owner, driven from the
841/// host's content thread — exactly how the lane types are driven today. Not
842/// `Send` by default (scripted lanes hold JS engine state).
843pub trait DocumentSession<F>: Any {
844    /// Consume the encoded request paired with the latest input's Submit.
845    fn take_encoded_form_submission(&mut self) -> Option<SessionEncodedFormSubmission> { None }
846    /// Visible top-document identity, distinct from an effective resource base.
847    fn current_address(&self) -> Option<String> { None }
848
849    /// Document-facing controls this retained session can presently serve.
850    ///
851    /// A session can expose find while leaving page zoom and raster capture to
852    /// its host. Retained navigation is commonly partial because the host owns
853    /// lineage, policy, and refetch.
854    fn document_capabilities(&self) -> DocumentCapabilities {
855        DocumentCapabilities::default()
856    }
857
858    /// Lay out (if needed) and paint at the given viewport. Resize is
859    /// implicit: a size change re-lays-out, same as the lanes today.
860    fn frame(&mut self, width: u32, height: u32) -> F;
861
862    /// Paint a frame while preserving an engine's refusal reason. Existing
863    /// infallible sessions inherit the ordinary frame path.
864    fn try_frame(&mut self, width: u32, height: u32) -> Result<F, String> {
865        Ok(self.frame(width, height))
866    }
867
868    /// Producer draws associated with the most recent [`Self::frame`].
869    fn external_texture_draws(&self) -> &[SessionExternalTextureDraw] {
870        &[]
871    }
872
873    /// Scroll the viewport; `true` if the offset changed.
874    fn scroll_by(&mut self, dx: f32, dy: f32) -> bool;
875
876    /// Scroll the scrollable under `(x, y)` (nested scrollers); `true` if an
877    /// offset changed. Defaults to viewport scroll for single-scroller lanes.
878    fn scroll_at(&mut self, _x: f32, _y: f32, dx: f32, dy: f32) -> bool {
879        self.scroll_by(dx, dy)
880    }
881
882    fn scroll_for_key(&mut self, key: SessionScrollKey) -> bool;
883
884    /// Jump to an absolute vertical offset (anchor / fragment navigation).
885    /// Defaulted no-op for lanes without absolute addressing; lanes that
886    /// track their offset override.
887    fn scroll_to(&mut self, _y: f32) {}
888
889    fn click_at(&mut self, x: f32, y: f32) -> SessionClick;
890
891    /// Begin a primary-pointer gesture in lane-local coordinates.
892    ///
893    /// The default preserves the original click-on-press contract for lanes
894    /// that have not adopted gesture state. Text-selecting lanes override this
895    /// to retain an anchor and defer link activation until pointer-up.
896    fn pointer_down(&mut self, x: f32, y: f32) -> SessionClick {
897        self.click_at(x, y)
898    }
899
900    /// Extend the captured primary-pointer gesture. `true` means visible
901    /// session state changed and the host should redraw.
902    fn pointer_move(&mut self, _x: f32, _y: f32) -> bool {
903        false
904    }
905
906    /// Finish the captured primary-pointer gesture.
907    ///
908    /// Lanes retaining text selection return [`SessionClick::Handled`] for a
909    /// non-collapsed selection, or the ordinary click result when the gesture
910    /// collapsed.
911    fn pointer_up(&mut self, _x: f32, _y: f32) -> SessionClick {
912        SessionClick::Miss
913    }
914
915    /// Dispatch host-neutral input through the lane's retained interaction
916    /// hooks. Existing click/pointer implementations remain the compatibility
917    /// floor; richer lanes override the focused keyboard, text, IME, cursor,
918    /// and form hooks below.
919    fn input(&mut self, input: SessionInput) -> SessionInputResult {
920        dispatch_session_input(self, input)
921    }
922
923    fn effect_for_click(&mut self, click: SessionClick) -> SessionEffect {
924        match click {
925            SessionClick::Navigate(target) => SessionEffect::Navigate(target),
926            SessionClick::Submit(action) => SessionEffect::Submit(self.form_submission(&action)),
927            SessionClick::Handled => SessionEffect::Handled,
928            SessionClick::Miss => SessionEffect::Ignored,
929        }
930    }
931
932    /// Dispatch a keyboard event and non-text default. Printable text arrives
933    /// separately through `keyboard_text_input` for the same press.
934    fn key_input(
935        &mut self,
936        _key: SessionKey,
937        _state: SessionButtonState,
938        _modifiers: SessionModifiers,
939        _repeat: bool,
940    ) -> SessionEffect {
941        SessionEffect::Ignored
942    }
943
944    /// Insert text paired with the preceding physical key. Override to honor
945    /// cancellation while keeping independent `text_input` available.
946    fn keyboard_text_input(&mut self, text: &str) -> bool {
947        self.text_input(text)
948    }
949
950    /// Insert independent text, including paste or accessibility edits.
951    fn text_input(&mut self, _text: &str) -> bool {
952        false
953    }
954
955    fn ime_input(&mut self, ime: SessionIme) -> bool {
956        match ime {
957            SessionIme::Commit(text) => self.text_input(&text),
958            SessionIme::Enabled | SessionIme::Preedit { .. } | SessionIme::Disabled => false,
959        }
960    }
961
962    fn focus_input(&mut self, _focused: bool) {}
963
964    fn focus_move(&mut self, _direction: SessionFocusDirection) -> bool {
965        false
966    }
967
968    fn cancel_input(&mut self) -> bool {
969        false
970    }
971
972    fn editable_focus(&self) -> bool {
973        false
974    }
975
976    /// Observe the focused writable text control against a current completed
977    /// layout. `None` means there is no usable text-control observation (or
978    /// this session does not implement it). This read must not trigger layout.
979    /// Hosts publish refreshed geometry after preparing the next frame.
980    fn text_input_state(&self) -> Option<crate::SessionTextInputState> {
981        None
982    }
983
984    /// Plain text of the current selection, for host Copy and Cut. A focused
985    /// text control's non-collapsed selection wins over the document's
986    /// retained range; password controls never answer. `None` means nothing
987    /// is selected or this lane retains no selection. This read must not
988    /// trigger layout.
989    fn selected_text(&self) -> Option<String> {
990        None
991    }
992
993    fn cursor_at(&self, _x: f32, _y: f32) -> SessionCursor {
994        SessionCursor::Default
995    }
996
997    fn form_submission(&mut self, action: &str) -> SessionFormSubmission {
998        SessionFormSubmission {
999            action: action.to_owned(),
1000            ..Default::default()
1001        }
1002    }
1003
1004    /// Resolve the first laid-out occurrence of `text` to pointer endpoints.
1005    /// This remains read-only: callers must drive the normal pointer lifecycle
1006    /// to create selection state.
1007    fn text_target(&self, _text: &str) -> Option<SessionTextTarget> {
1008        None
1009    }
1010
1011    /// Replace the retained find model for this session and reveal its first
1012    /// match. Engines own their document internals; the host receives only the
1013    /// portable model.
1014    fn document_find(
1015        &mut self,
1016        _query: &DocumentFindQuery,
1017    ) -> Result<DocumentFindState, SessionError> {
1018        Err(SessionError::Unsupported(
1019            "document find is not wired for this session".into(),
1020        ))
1021    }
1022
1023    /// Step the current retained model, wrapping at either end.
1024    fn document_find_step(
1025        &mut self,
1026        _direction: DocumentFindDirection,
1027    ) -> Result<DocumentFindState, SessionError> {
1028        Err(SessionError::Unsupported(
1029            "document find is not wired for this session".into(),
1030        ))
1031    }
1032
1033    fn clear_document_find(&mut self) -> Result<(), SessionError> {
1034        Ok(())
1035    }
1036
1037    /// Present this document at an absolute page-zoom `factor` (1.0 = 100 %).
1038    ///
1039    /// This is user-agent document zoom, not CSS `zoom`: the CSS viewport
1040    /// shrinks as the factor grows, media queries re-evaluate against it, and
1041    /// the engine scales its rendered output back up. Host chrome is never
1042    /// scaled. The caller owns its own ladder and persistence — reset is
1043    /// `factor` 1.0 — while the engine owns only bounds and quantization, which
1044    /// it reports in the returned [`DocumentZoomState`].
1045    fn set_page_zoom(&mut self, _factor: f32) -> Result<DocumentZoomState, SessionError> {
1046        Err(SessionError::Unsupported(
1047            "page zoom is not wired for this session".into(),
1048        ))
1049    }
1050
1051    /// Capture immediately from this retained session. Retained sessions have
1052    /// no event queue solely for capture symmetry; a future implementation can
1053    /// return the same output vocabulary directly.
1054    fn capture_page(
1055        &mut self,
1056        _request: PageCaptureRequest,
1057    ) -> Result<PageCaptureOutput, SessionError> {
1058        Err(SessionError::Unsupported(
1059            "page capture is not wired for this session".into(),
1060        ))
1061    }
1062
1063    /// The link hit-table off the retained layout (no live-DOM query per
1064    /// click) — the mechanism all three lanes already share.
1065    fn links(&self) -> Vec<SessionLink>;
1066
1067    /// Full laid-out content height at this viewport, for hosts that band
1068    /// scenes. Sessions that scroll internally return the viewport height.
1069    fn content_height(&mut self, _width: u32, height: u32) -> u32 {
1070        height
1071    }
1072
1073    /// Absolute subresource URLs this retained session wants the host to
1074    /// fetch. The host owns transport, trust, credentials, and scheduling;
1075    /// sessions only name resources needed for their current presentation.
1076    fn subresources(&self) -> Vec<String> {
1077        Vec::new()
1078    }
1079
1080    /// Deliver one host-fetched subresource. `true` means visible session
1081    /// state changed and the host should redraw.
1082    fn provide_subresource(&mut self, _url: &str, _bytes: &[u8]) -> bool {
1083        false
1084    }
1085
1086    /// Apply one batch of host-driven DOM changes before the next
1087    /// [`Self::frame`], and report what the batch did.
1088    ///
1089    /// The batch is applied as one turn — resolve, mutate, drain, restyle —
1090    /// so a host pays one invalidation for the whole set rather than one per
1091    /// mutation. Sessions whose DOM is immutable leave this unsupported; the
1092    /// host reports the absence rather than quietly rendering an unchanged
1093    /// document.
1094    fn apply_host_mutations(
1095        &mut self,
1096        _mutations: &[HostMutation],
1097    ) -> Result<HostMutationReport, SessionError> {
1098        Err(SessionError::Unsupported(
1099            "host mutation is not wired for this session".into(),
1100        ))
1101    }
1102
1103    /// Element `id` attributes beginning with `prefix`, in document order.
1104    ///
1105    /// The companion read to [`Self::apply_host_mutations`]: a host driving a
1106    /// deterministic mutation pattern over "the controls" needs to name them
1107    /// without having counted the document by hand. Empty for sessions with no
1108    /// element-id plane.
1109    fn element_ids_with_prefix(&self, _prefix: &str) -> Vec<String> {
1110        Vec::new()
1111    }
1112
1113    /// Drive timers / pending script work (scripted lanes). No-op default.
1114    fn pump(&mut self, _now_ms: f64) {}
1115
1116    /// Cumulative garbage-collection tally since this session was spawned:
1117    /// `(reflectors_unpinned, nodes_collected)`. This is the engine-owned
1118    /// inspection seam a host correlates with its captured frame to confirm
1119    /// collection (G5's Lifetime contract), not a live API surface for
1120    /// script. Static and non-scripted lanes have nothing to report.
1121    fn collection_stats(&self) -> (usize, usize) {
1122        (0, 0)
1123    }
1124
1125    /// Report the work that should wake this session after the current turn.
1126    ///
1127    /// Static sessions remain idle. Scripted sessions report their earliest
1128    /// timer and set `external` while host-owned fetch or Worker work remains.
1129    fn pending_work(&mut self) -> SessionPendingWork {
1130        SessionPendingWork::idle()
1131    }
1132
1133    /// Whether script-visible completion has settled: no pending microtasks
1134    /// or host-owned external work. Future timers do not block completion.
1135    /// This handshake does not track layout dirtiness or establish rendered
1136    /// quiescence. Static lanes are always settled by default.
1137    fn settled(&mut self) -> bool {
1138        self.pending_work().is_settled()
1139    }
1140
1141    /// Visibility hint (a hidden tile may skip raster-adjacent work).
1142    fn set_hidden(&mut self, _hidden: bool) {}
1143
1144    /// Whether the host can suspend and resume this session's task delivery.
1145    /// A hidden presentation still runs throttled work and is distinct from
1146    /// this lifecycle control.
1147    fn supports_freeze_resume(&self) -> bool {
1148        false
1149    }
1150
1151    /// Suspend all document task delivery after its lifecycle event. Sessions
1152    /// without this capability leave the request unchanged.
1153    fn freeze(&mut self) {}
1154
1155    /// Restore task delivery and dispatch the document's resume event.
1156    fn resume(&mut self) {}
1157
1158    /// A structural [`ContentReport`] of the addressed content, for hosts that
1159    /// cannot downcast to the concrete session type (it may be private to its
1160    /// engine crate — turnstone's one registered lane is exactly that case, which
1161    /// is why this is a trait method and not an `as_any` detour). `None` for
1162    /// lanes without a structural read; the host reports the absence honestly
1163    /// rather than synthesizing one.
1164    fn inspect(&self) -> Option<ContentReport> {
1165        None
1166    }
1167
1168    /// Capture the current semantic clip. `None` means this document lane
1169    /// cannot supply clip content; hosts must not synthesize authority or
1170    /// recover source bytes by downcasting.
1171    fn clip(&self) -> Option<DocumentClip> {
1172        None
1173    }
1174
1175    /// Current renderer-neutral semantic snapshot of this retained document.
1176    ///
1177    /// The projection, when present, is the live truth about semantic
1178    /// completeness and limitations. It replaces host-side guesses based on
1179    /// concrete session type. Local IDs remain stable for the same semantic
1180    /// object across revisions and must be namespaced by a host before entering
1181    /// a global accessibility tree.
1182    fn accessibility_projection(&self) -> Option<DocumentA11yProjection> {
1183        None
1184    }
1185
1186    /// Revalidate an advertised clickable node and return its current pointer
1187    /// target. Hosts use the returned point with their ordinary `click_at`
1188    /// path, keeping link routing and host navigation custody unchanged.
1189    ///
1190    /// A `None` result means the node is stale, no longer clickable, or its
1191    /// geometry is unavailable. The returned revision must match the current
1192    /// projection before the host acts on it.
1193    fn accessibility_click_target(
1194        &self,
1195        _target: DocumentA11yNodeId,
1196    ) -> Option<DocumentA11yClickTarget> {
1197        None
1198    }
1199
1200    /// Revalidate and dispatch a non-pointer accessibility action.
1201    ///
1202    /// Engines return `true` only after accepting a request whose revision and
1203    /// target are current and whose action is advertised by that target.
1204    /// `Click` intentionally returns `false`: it travels through
1205    /// [`Self::accessibility_click_target`] and the ordinary pointer path.
1206    fn dispatch_accessibility_action(&mut self, _request: &DocumentA11yActionRequest) -> bool {
1207        false
1208    }
1209
1210    /// Lane-specific extras (a scripted lane's DOM stats, a static lane's
1211    /// content report) stay on the concrete type; hosts that need them
1212    /// downcast through here rather than the trait growing every lane's
1213    /// diagnostics.
1214    fn as_any_ref(&self) -> &dyn Any;
1215
1216    fn as_any(&mut self) -> &mut dyn Any;
1217}
1218
1219// ── Registry ───────────────────────────────────────────────────────────────
1220
1221/// Session engines keyed by engine id, one registry per host frame type.
1222#[derive(Default)]
1223pub struct SessionRegistry<F> {
1224    engines: HashMap<String, Box<dyn SessionEngine<F>>>,
1225}
1226
1227impl<F> SessionRegistry<F> {
1228    pub fn new() -> Self {
1229        Self {
1230            engines: HashMap::new(),
1231        }
1232    }
1233
1234    /// Register an engine under its own id. Last registration wins, matching
1235    /// `EngineRegistry` semantics.
1236    pub fn register(&mut self, engine: Box<dyn SessionEngine<F>>) {
1237        self.engines.insert(engine.engine_id().to_string(), engine);
1238    }
1239
1240    pub fn contains(&self, engine_id: &str) -> bool {
1241        self.engines.contains_key(engine_id)
1242    }
1243
1244    pub fn get(&self, engine_id: &str) -> Option<&dyn SessionEngine<F>> {
1245        self.engines.get(engine_id).map(|e| e.as_ref())
1246    }
1247
1248    pub fn spawn(
1249        &self,
1250        engine_id: &str,
1251        request: &SessionSpawnRequest,
1252    ) -> Result<Box<dyn DocumentSession<F>>, SessionError> {
1253        self.engines
1254            .get(engine_id)
1255            .ok_or_else(|| SessionError::EngineNotFound(engine_id.to_string()))?
1256            .spawn(request)
1257    }
1258
1259    pub fn engine_ids(&self) -> impl Iterator<Item = &str> {
1260        self.engines.keys().map(String::as_str)
1261    }
1262}
1263
1264// ── Kind facade ────────────────────────────────────────────────────────────
1265
1266/// Which registries hold an engine id. An id may be held by more than one
1267/// kind (a smolweb format can have both a block engine for cards and a
1268/// session engine for tiles); the HOST picks by surface context, so this is
1269/// reported as flags, not a single kind.
1270#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1271pub struct EngineKinds {
1272    pub document: bool,
1273    pub session: bool,
1274    pub surface: bool,
1275}
1276
1277impl EngineKinds {
1278    pub fn any(&self) -> bool {
1279        self.document || self.session || self.surface
1280    }
1281}
1282
1283/// Non-generic id-to-kind resolution: which registries hold each id is just
1284/// a map, so hosts resolve kinds without threading the frame type through
1285/// code that never touches frames. Built after registration from the
1286/// registries' id sets; host-handled ids (internal pages, ingest markers)
1287/// are the host's own vocabulary and deliberately absent.
1288#[derive(Clone, Debug, Default)]
1289pub struct EngineKindIndex {
1290    kinds: HashMap<String, EngineKinds>,
1291}
1292
1293impl EngineKindIndex {
1294    pub fn build<'a>(
1295        document_ids: impl IntoIterator<Item = &'a str>,
1296        session_ids: impl IntoIterator<Item = &'a str>,
1297        surface_ids: impl IntoIterator<Item = &'a str>,
1298    ) -> Self {
1299        let mut kinds: HashMap<String, EngineKinds> = HashMap::new();
1300        for id in document_ids {
1301            kinds.entry(id.to_string()).or_default().document = true;
1302        }
1303        for id in session_ids {
1304            kinds.entry(id.to_string()).or_default().session = true;
1305        }
1306        for id in surface_ids {
1307            kinds.entry(id.to_string()).or_default().surface = true;
1308        }
1309        Self { kinds }
1310    }
1311
1312    pub fn kinds_of(&self, engine_id: &str) -> EngineKinds {
1313        self.kinds.get(engine_id).copied().unwrap_or_default()
1314    }
1315}
1316
1317#[cfg(test)]
1318mod tests {
1319    use super::*;
1320    use crate::PageCaptureRequestId;
1321
1322    /// A frame type that just records what was rendered.
1323    type TextFrame = String;
1324
1325    struct EchoSession {
1326        address: String,
1327        scroll: f32,
1328        hidden: bool,
1329    }
1330
1331    impl DocumentSession<TextFrame> for EchoSession {
1332        fn frame(&mut self, width: u32, height: u32) -> TextFrame {
1333            format!("{} @ {width}x{height} scroll={}", self.address, self.scroll)
1334        }
1335        fn scroll_by(&mut self, _dx: f32, dy: f32) -> bool {
1336            self.scroll += dy;
1337            dy != 0.0
1338        }
1339        fn scroll_for_key(&mut self, key: SessionScrollKey) -> bool {
1340            self.scroll_by(
1341                0.0,
1342                if key == SessionScrollKey::PageDown {
1343                    100.0
1344                } else {
1345                    0.0
1346                },
1347            )
1348        }
1349        fn click_at(&mut self, x: f32, _y: f32) -> SessionClick {
1350            if x < 10.0 {
1351                SessionClick::Navigate("gemini://example.test/".into())
1352            } else {
1353                SessionClick::Miss
1354            }
1355        }
1356        fn links(&self) -> Vec<SessionLink> {
1357            vec![SessionLink {
1358                url: "gemini://example.test/".into(),
1359                rect: [0.0, 0.0, 10.0, 10.0],
1360            }]
1361        }
1362        fn set_hidden(&mut self, hidden: bool) {
1363            self.hidden = hidden;
1364        }
1365        fn as_any_ref(&self) -> &dyn Any {
1366            self
1367        }
1368        fn as_any(&mut self) -> &mut dyn Any {
1369            self
1370        }
1371    }
1372
1373    struct EchoSessionEngine;
1374
1375    impl SessionEngine<TextFrame> for EchoSessionEngine {
1376        fn engine_id(&self) -> &str {
1377            "echo.session"
1378        }
1379        fn spawn(
1380            &self,
1381            request: &SessionSpawnRequest,
1382        ) -> Result<Box<dyn DocumentSession<TextFrame>>, SessionError> {
1383            if request.address.is_empty() {
1384                return Err(SessionError::SpawnFailed("empty address".into()));
1385            }
1386            Ok(Box::new(EchoSession {
1387                address: request.address.clone(),
1388                scroll: 0.0,
1389                hidden: request.hidden,
1390            }))
1391        }
1392    }
1393
1394    #[test]
1395    fn registry_spawns_and_drives_a_session() {
1396        let mut registry = SessionRegistry::new();
1397        registry.register(Box::new(EchoSessionEngine));
1398
1399        let request = SessionSpawnRequest::new("https://example.test").with_viewport(800, 600);
1400        let mut session = registry.spawn("echo.session", &request).expect("spawns");
1401
1402        assert_eq!(
1403            session.frame(800, 600),
1404            "https://example.test @ 800x600 scroll=0"
1405        );
1406        assert!(session.scroll_by(0.0, 42.0));
1407        assert!(session.frame(800, 600).ends_with("scroll=42"));
1408        assert_eq!(
1409            session.click_at(5.0, 5.0),
1410            SessionClick::Navigate("gemini://example.test/".into())
1411        );
1412        assert_eq!(session.click_at(50.0, 5.0), SessionClick::Miss);
1413        assert_eq!(session.links().len(), 1);
1414        // Static-lane defaults: settled immediately, pump is a no-op.
1415        assert!(session.settled());
1416        session.pump(16.0);
1417    }
1418
1419    #[test]
1420    fn document_session_capture_defaults_to_unsupported() {
1421        let mut session = EchoSession {
1422            address: "https://example.test".into(),
1423            scroll: 0.0,
1424            hidden: false,
1425        };
1426        assert!(matches!(
1427            session.capture_page(PageCaptureRequest::viewport(PageCaptureRequestId::new(9))),
1428            Err(SessionError::Unsupported(_))
1429        ));
1430    }
1431
1432    #[test]
1433    fn document_session_accessibility_defaults_to_an_honest_absence() {
1434        let mut session = EchoSession {
1435            address: "https://example.test".into(),
1436            scroll: 0.0,
1437            hidden: false,
1438        };
1439        let target = DocumentA11yNodeId::new(7);
1440        assert_eq!(session.accessibility_projection(), None);
1441        assert_eq!(session.accessibility_click_target(target), None);
1442        assert!(
1443            !session.dispatch_accessibility_action(&DocumentA11yActionRequest {
1444                revision: 1,
1445                target,
1446                action: crate::DocumentA11yAction::Focus,
1447                data: None,
1448            })
1449        );
1450    }
1451
1452    #[test]
1453    fn neutral_pointer_dispatch_preserves_navigation_cursor_and_capture() {
1454        let mut registry = SessionRegistry::new();
1455        registry.register(Box::new(EchoSessionEngine));
1456        let mut session = registry
1457            .spawn(
1458                "echo.session",
1459                &SessionSpawnRequest::new("https://example.test"),
1460            )
1461            .expect("spawns");
1462
1463        let pressed = session.input(SessionInput::PointerButton {
1464            x: 5.0,
1465            y: 5.0,
1466            button: SessionPointerButton::Primary,
1467            state: SessionButtonState::Pressed,
1468            modifiers: SessionModifiers::default(),
1469        });
1470        assert_eq!(
1471            pressed.effect,
1472            SessionEffect::Navigate("gemini://example.test/".into())
1473        );
1474        assert_eq!(pressed.cursor, Some(SessionCursor::Default));
1475        assert_eq!(pressed.capture, Some(true));
1476
1477        let released = session.input(SessionInput::PointerButton {
1478            x: 5.0,
1479            y: 5.0,
1480            button: SessionPointerButton::Primary,
1481            state: SessionButtonState::Released,
1482            modifiers: SessionModifiers::default(),
1483        });
1484        assert_eq!(released.effect, SessionEffect::Ignored);
1485        assert_eq!(released.capture, Some(false));
1486    }
1487
1488    #[test]
1489    fn unknown_engine_is_a_named_error() {
1490        let registry: SessionRegistry<TextFrame> = SessionRegistry::new();
1491        let err = match registry.spawn("nope", &SessionSpawnRequest::new("x")) {
1492            Ok(_) => panic!("unknown engine must not spawn"),
1493            Err(err) => err,
1494        };
1495        assert_eq!(err, SessionError::EngineNotFound("nope".into()));
1496    }
1497
1498    #[test]
1499    fn downcast_reaches_lane_extras() {
1500        let mut registry = SessionRegistry::new();
1501        registry.register(Box::new(EchoSessionEngine));
1502        let mut session = registry
1503            .spawn("echo.session", &SessionSpawnRequest::new("a"))
1504            .unwrap();
1505        session.set_hidden(true);
1506        assert!(
1507            session.as_any_ref().downcast_ref::<EchoSession>().is_some(),
1508            "immutable hosts can reach lane extras without taking session ownership"
1509        );
1510        let echo = session
1511            .as_any()
1512            .downcast_mut::<EchoSession>()
1513            .expect("concrete lane type reachable");
1514        assert!(echo.hidden);
1515    }
1516
1517    #[test]
1518    fn kind_index_reports_flags_not_a_single_kind() {
1519        let mut sessions: SessionRegistry<TextFrame> = SessionRegistry::new();
1520        sessions.register(Box::new(EchoSessionEngine));
1521
1522        // An id may be held by more than one kind (block engine for cards +
1523        // session engine for tiles); the index reports flags, host picks.
1524        let index = EngineKindIndex::build(
1525            ["nematic.gemtext"],
1526            sessions.engine_ids().chain(["nematic.gemtext"]),
1527            ["scrying.web"],
1528        );
1529        assert!(index.kinds_of("echo.session").session);
1530        let both = index.kinds_of("nematic.gemtext");
1531        assert!(both.document && both.session && !both.surface);
1532        assert!(index.kinds_of("scrying.web").surface);
1533        assert!(!index.kinds_of("absent").any());
1534    }
1535
1536    #[test]
1537    fn page_zoom_is_a_named_absence_until_a_lane_wires_it() {
1538        let mut session = EchoSession {
1539            address: "gemini://example.test/".into(),
1540            scroll: 0.0,
1541            hidden: false,
1542        };
1543        assert!(matches!(
1544            session.set_page_zoom(1.25),
1545            Err(SessionError::Unsupported(_))
1546        ));
1547    }
1548
1549    #[test]
1550    fn zoom_state_keeps_the_request_and_clamps_only_the_applied_value() {
1551        let state = DocumentZoomState::clamped(9.0, 0.25, 5.0);
1552        assert_eq!(state.requested, 9.0);
1553        assert_eq!(state.applied, 5.0);
1554
1555        let state = DocumentZoomState::clamped(0.1, 0.25, 5.0);
1556        assert_eq!(state.requested, 0.1);
1557        assert_eq!(state.applied, 0.25);
1558
1559        assert_eq!(DocumentZoomState::clamped(1.5, 0.25, 5.0).applied, 1.5);
1560        assert_eq!(
1561            DocumentZoomState::clamped(f32::NAN, 0.25, 5.0).applied,
1562            1.0,
1563            "a non-finite request must not reach layout as a viewport divisor"
1564        );
1565    }
1566
1567    #[test]
1568    fn pending_work_exposes_a_sleepable_timer_deadline() {
1569        let now = std::time::Instant::now();
1570        let work = SessionPendingWork::timer(std::time::Duration::from_millis(25));
1571        let deadline = work.next_wake(now).expect("timer has a wake deadline");
1572        assert!(deadline >= now + std::time::Duration::from_millis(25));
1573        assert!(!work.is_idle());
1574        assert!(
1575            work.is_settled(),
1576            "a future timer is wakeable without making a live page perpetually unsettled"
1577        );
1578        assert!(
1579            !SessionPendingWork {
1580                external: true,
1581                ..SessionPendingWork::idle()
1582            }
1583            .is_settled()
1584        );
1585        assert!(SessionPendingWork::idle().next_wake(now).is_none());
1586        assert_eq!(
1587            SessionPendingWork {
1588                microtasks: true,
1589                ..SessionPendingWork::idle()
1590            }
1591            .next_wake(now),
1592            Some(now)
1593        );
1594    }
1595
1596    // TASK5 DRAFT API FIXTURES BEGIN. Missing seams have explicit absence adapters.
1597    fn t5_api_take_absent(_session: &mut dyn DocumentSession<TextFrame>) -> Option<()> {
1598        _session.take_encoded_form_submission().map(|_| ())
1599    }
1600    fn t5_api_address_absent(_session: &dyn DocumentSession<TextFrame>) -> Option<String> {
1601        _session.current_address()
1602    }
1603    fn t5_api_request_spawn_absent(
1604        _engine: &dyn SessionEngine<TextFrame>,
1605        _request: &SessionSpawnRequest,
1606        _bytes: &[u8],
1607    ) -> Result<(), SessionError> {
1608        let request = SessionDocumentRequest { url: _request.address.clone(), method: "POST".into(),
1609            headers: vec![], body: Some(_bytes.to_vec()), cache: "default".into(), redirect: "follow".into(),
1610            mode: "navigate".into(), referrer: String::new(), referrer_policy: String::new(),
1611            credentials: "include".into(), integrity: String::new() };
1612        _engine.spawn_request(_request, &request).map(|_| ())
1613    }
1614    #[test]
1615    fn phase_c_t5_api_legacy_submission_literal() {
1616        let value = SessionFormSubmission {
1617            action: "https://forms.test/send".into(), method: SessionFormMethod::Post,
1618            fields: vec![("q".into(), "café".into())],
1619        };
1620        fn retains_serde<T:serde::Serialize+for<'de>serde::Deserialize<'de>>() {}
1621        retains_serde::<SessionFormSubmission>();
1622        let copied=value.clone();
1623        let SessionFormSubmission{action,method,fields}=copied;
1624        assert_eq!((action,method,fields),("https://forms.test/send".into(),SessionFormMethod::Post,vec![("q".into(),"café".into())]));
1625    }
1626    #[test]
1627    fn phase_c_t5_api_legacy_result_literal() {
1628        let value = SessionInputResult { effect: SessionEffect::Handled,
1629            cursor: Some(SessionCursor::Text), capture: Some(false), editable: true };
1630        let SessionInputResult { effect, cursor, capture, editable } = value;
1631        let tag = match effect { SessionEffect::Ignored => 0, SessionEffect::Handled => 1,
1632            SessionEffect::Navigate(_) => 2, SessionEffect::Submit(_) => 3,
1633            SessionEffect::Cancelled => 4 };
1634        assert_eq!((tag, cursor, capture, editable), (1, Some(SessionCursor::Text), Some(false), true));
1635    }
1636    #[test]
1637    fn key_default_scroll_respects_effect_and_effective_editable_focus() {
1638        let cases = [
1639            (SessionEffect::Ignored, false, true),
1640            (SessionEffect::Ignored, true, false),
1641            (SessionEffect::Handled, false, false),
1642            (SessionEffect::Cancelled, false, false),
1643            (SessionEffect::Navigate("https://example.test/next".into()), false, false),
1644            (SessionEffect::Submit(SessionFormSubmission::default()), false, false),
1645        ];
1646        for (effect, editable, expected) in cases {
1647            assert_eq!(effect.allows_default_scroll(editable), expected, "{effect:?}, editable={editable}");
1648        }
1649
1650        // A native navigation can install a new session during dispatch. Its
1651        // editable focus, rather than the outgoing result's flag, decides the
1652        // next default action without consuming the typed input result.
1653        let result = SessionInputResult {
1654            effect: SessionEffect::Ignored,
1655            cursor: Some(SessionCursor::Text),
1656            capture: Some(false),
1657            editable: false,
1658        };
1659        assert!(result.effect.allows_default_scroll(result.editable));
1660        assert!(!result.effect.allows_default_scroll(true));
1661        assert_eq!(result.cursor, Some(SessionCursor::Text));
1662        assert_eq!(result.capture, Some(false));
1663    }
1664    #[test]
1665    fn phase_c_t5_api_legacy_spawn_unicode_body() {
1666        let request = SessionSpawnRequest { address: "https://forms.test/".into(),
1667            body: Some("café".into()), content_type: Some("text/html".into()),
1668            viewport: (320, 240), hidden: false };
1669        assert_eq!(request.body.as_deref(), Some("café"));
1670        assert_eq!(SessionSpawnRequest::new("a").with_body("café").body, request.body);
1671    }
1672    #[test]
1673    fn phase_c_t5_api_old_session_accessor_none() {
1674        let mut old = EchoSession { address: "old".into(), scroll: 0.0, hidden: false };
1675        assert!(t5_api_take_absent(&mut old).is_none());
1676        let result = old.input(SessionInput::PointerButton { x: 1.0, y: 1.0,
1677            button: SessionPointerButton::Primary, state: SessionButtonState::Pressed,
1678            modifiers: SessionModifiers::default() });
1679        assert_eq!(result.effect, SessionEffect::Navigate("gemini://example.test/".into()));
1680    }
1681    #[test]
1682    fn phase_c_t5_api_old_factory_rich_decline() {
1683        let request = SessionSpawnRequest::new("https://forms.test/");
1684        assert!(matches!(t5_api_request_spawn_absent(&EchoSessionEngine, &request, &[0,128,255]),
1685            Err(SessionError::Unsupported(_))));
1686        let mut ordinary = EchoSessionEngine.spawn(&request).unwrap();
1687        assert!(ordinary.frame(1, 1).starts_with("https://forms.test/"));
1688    }
1689    #[test]
1690    fn phase_c_t5_api_old_session_current_address_none() {
1691        let old = EchoSession { address: "legacy".into(), scroll: 0.0, hidden: false };
1692        assert!(t5_api_address_absent(&old).is_none());
1693        assert_eq!(old.address, "legacy");
1694    }
1695    // TASK5 DRAFT API FIXTURES END.
1696}