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    fn cursor_at(&self, _x: f32, _y: f32) -> SessionCursor {
977        SessionCursor::Default
978    }
979
980    fn form_submission(&mut self, action: &str) -> SessionFormSubmission {
981        SessionFormSubmission {
982            action: action.to_owned(),
983            ..Default::default()
984        }
985    }
986
987    /// Resolve the first laid-out occurrence of `text` to pointer endpoints.
988    /// This remains read-only: callers must drive the normal pointer lifecycle
989    /// to create selection state.
990    fn text_target(&self, _text: &str) -> Option<SessionTextTarget> {
991        None
992    }
993
994    /// Replace the retained find model for this session and reveal its first
995    /// match. Engines own their document internals; the host receives only the
996    /// portable model.
997    fn document_find(
998        &mut self,
999        _query: &DocumentFindQuery,
1000    ) -> Result<DocumentFindState, SessionError> {
1001        Err(SessionError::Unsupported(
1002            "document find is not wired for this session".into(),
1003        ))
1004    }
1005
1006    /// Step the current retained model, wrapping at either end.
1007    fn document_find_step(
1008        &mut self,
1009        _direction: DocumentFindDirection,
1010    ) -> Result<DocumentFindState, SessionError> {
1011        Err(SessionError::Unsupported(
1012            "document find is not wired for this session".into(),
1013        ))
1014    }
1015
1016    fn clear_document_find(&mut self) -> Result<(), SessionError> {
1017        Ok(())
1018    }
1019
1020    /// Present this document at an absolute page-zoom `factor` (1.0 = 100 %).
1021    ///
1022    /// This is user-agent document zoom, not CSS `zoom`: the CSS viewport
1023    /// shrinks as the factor grows, media queries re-evaluate against it, and
1024    /// the engine scales its rendered output back up. Host chrome is never
1025    /// scaled. The caller owns its own ladder and persistence — reset is
1026    /// `factor` 1.0 — while the engine owns only bounds and quantization, which
1027    /// it reports in the returned [`DocumentZoomState`].
1028    fn set_page_zoom(&mut self, _factor: f32) -> Result<DocumentZoomState, SessionError> {
1029        Err(SessionError::Unsupported(
1030            "page zoom is not wired for this session".into(),
1031        ))
1032    }
1033
1034    /// Capture immediately from this retained session. Retained sessions have
1035    /// no event queue solely for capture symmetry; a future implementation can
1036    /// return the same output vocabulary directly.
1037    fn capture_page(
1038        &mut self,
1039        _request: PageCaptureRequest,
1040    ) -> Result<PageCaptureOutput, SessionError> {
1041        Err(SessionError::Unsupported(
1042            "page capture is not wired for this session".into(),
1043        ))
1044    }
1045
1046    /// The link hit-table off the retained layout (no live-DOM query per
1047    /// click) — the mechanism all three lanes already share.
1048    fn links(&self) -> Vec<SessionLink>;
1049
1050    /// Full laid-out content height at this viewport, for hosts that band
1051    /// scenes. Sessions that scroll internally return the viewport height.
1052    fn content_height(&mut self, _width: u32, height: u32) -> u32 {
1053        height
1054    }
1055
1056    /// Absolute subresource URLs this retained session wants the host to
1057    /// fetch. The host owns transport, trust, credentials, and scheduling;
1058    /// sessions only name resources needed for their current presentation.
1059    fn subresources(&self) -> Vec<String> {
1060        Vec::new()
1061    }
1062
1063    /// Deliver one host-fetched subresource. `true` means visible session
1064    /// state changed and the host should redraw.
1065    fn provide_subresource(&mut self, _url: &str, _bytes: &[u8]) -> bool {
1066        false
1067    }
1068
1069    /// Apply one batch of host-driven DOM changes before the next
1070    /// [`Self::frame`], and report what the batch did.
1071    ///
1072    /// The batch is applied as one turn — resolve, mutate, drain, restyle —
1073    /// so a host pays one invalidation for the whole set rather than one per
1074    /// mutation. Sessions whose DOM is immutable leave this unsupported; the
1075    /// host reports the absence rather than quietly rendering an unchanged
1076    /// document.
1077    fn apply_host_mutations(
1078        &mut self,
1079        _mutations: &[HostMutation],
1080    ) -> Result<HostMutationReport, SessionError> {
1081        Err(SessionError::Unsupported(
1082            "host mutation is not wired for this session".into(),
1083        ))
1084    }
1085
1086    /// Element `id` attributes beginning with `prefix`, in document order.
1087    ///
1088    /// The companion read to [`Self::apply_host_mutations`]: a host driving a
1089    /// deterministic mutation pattern over "the controls" needs to name them
1090    /// without having counted the document by hand. Empty for sessions with no
1091    /// element-id plane.
1092    fn element_ids_with_prefix(&self, _prefix: &str) -> Vec<String> {
1093        Vec::new()
1094    }
1095
1096    /// Drive timers / pending script work (scripted lanes). No-op default.
1097    fn pump(&mut self, _now_ms: f64) {}
1098
1099    /// Cumulative garbage-collection tally since this session was spawned:
1100    /// `(reflectors_unpinned, nodes_collected)`. This is the engine-owned
1101    /// inspection seam a host correlates with its captured frame to confirm
1102    /// collection (G5's Lifetime contract), not a live API surface for
1103    /// script. Static and non-scripted lanes have nothing to report.
1104    fn collection_stats(&self) -> (usize, usize) {
1105        (0, 0)
1106    }
1107
1108    /// Report the work that should wake this session after the current turn.
1109    ///
1110    /// Static sessions remain idle. Scripted sessions report their earliest
1111    /// timer and set `external` while host-owned fetch or Worker work remains.
1112    fn pending_work(&mut self) -> SessionPendingWork {
1113        SessionPendingWork::idle()
1114    }
1115
1116    /// Whether script-visible completion has settled: no pending microtasks
1117    /// or host-owned external work. Future timers do not block completion.
1118    /// This handshake does not track layout dirtiness or establish rendered
1119    /// quiescence. Static lanes are always settled by default.
1120    fn settled(&mut self) -> bool {
1121        self.pending_work().is_settled()
1122    }
1123
1124    /// Visibility hint (a hidden tile may skip raster-adjacent work).
1125    fn set_hidden(&mut self, _hidden: bool) {}
1126
1127    /// Whether the host can suspend and resume this session's task delivery.
1128    /// A hidden presentation still runs throttled work and is distinct from
1129    /// this lifecycle control.
1130    fn supports_freeze_resume(&self) -> bool {
1131        false
1132    }
1133
1134    /// Suspend all document task delivery after its lifecycle event. Sessions
1135    /// without this capability leave the request unchanged.
1136    fn freeze(&mut self) {}
1137
1138    /// Restore task delivery and dispatch the document's resume event.
1139    fn resume(&mut self) {}
1140
1141    /// A structural [`ContentReport`] of the addressed content, for hosts that
1142    /// cannot downcast to the concrete session type (it may be private to its
1143    /// engine crate — turnstone's one registered lane is exactly that case, which
1144    /// is why this is a trait method and not an `as_any` detour). `None` for
1145    /// lanes without a structural read; the host reports the absence honestly
1146    /// rather than synthesizing one.
1147    fn inspect(&self) -> Option<ContentReport> {
1148        None
1149    }
1150
1151    /// Capture the current semantic clip. `None` means this document lane
1152    /// cannot supply clip content; hosts must not synthesize authority or
1153    /// recover source bytes by downcasting.
1154    fn clip(&self) -> Option<DocumentClip> {
1155        None
1156    }
1157
1158    /// Current renderer-neutral semantic snapshot of this retained document.
1159    ///
1160    /// The projection, when present, is the live truth about semantic
1161    /// completeness and limitations. It replaces host-side guesses based on
1162    /// concrete session type. Local IDs remain stable for the same semantic
1163    /// object across revisions and must be namespaced by a host before entering
1164    /// a global accessibility tree.
1165    fn accessibility_projection(&self) -> Option<DocumentA11yProjection> {
1166        None
1167    }
1168
1169    /// Revalidate an advertised clickable node and return its current pointer
1170    /// target. Hosts use the returned point with their ordinary `click_at`
1171    /// path, keeping link routing and host navigation custody unchanged.
1172    ///
1173    /// A `None` result means the node is stale, no longer clickable, or its
1174    /// geometry is unavailable. The returned revision must match the current
1175    /// projection before the host acts on it.
1176    fn accessibility_click_target(
1177        &self,
1178        _target: DocumentA11yNodeId,
1179    ) -> Option<DocumentA11yClickTarget> {
1180        None
1181    }
1182
1183    /// Revalidate and dispatch a non-pointer accessibility action.
1184    ///
1185    /// Engines return `true` only after accepting a request whose revision and
1186    /// target are current and whose action is advertised by that target.
1187    /// `Click` intentionally returns `false`: it travels through
1188    /// [`Self::accessibility_click_target`] and the ordinary pointer path.
1189    fn dispatch_accessibility_action(&mut self, _request: &DocumentA11yActionRequest) -> bool {
1190        false
1191    }
1192
1193    /// Lane-specific extras (a scripted lane's DOM stats, a static lane's
1194    /// content report) stay on the concrete type; hosts that need them
1195    /// downcast through here rather than the trait growing every lane's
1196    /// diagnostics.
1197    fn as_any_ref(&self) -> &dyn Any;
1198
1199    fn as_any(&mut self) -> &mut dyn Any;
1200}
1201
1202// ── Registry ───────────────────────────────────────────────────────────────
1203
1204/// Session engines keyed by engine id, one registry per host frame type.
1205#[derive(Default)]
1206pub struct SessionRegistry<F> {
1207    engines: HashMap<String, Box<dyn SessionEngine<F>>>,
1208}
1209
1210impl<F> SessionRegistry<F> {
1211    pub fn new() -> Self {
1212        Self {
1213            engines: HashMap::new(),
1214        }
1215    }
1216
1217    /// Register an engine under its own id. Last registration wins, matching
1218    /// `EngineRegistry` semantics.
1219    pub fn register(&mut self, engine: Box<dyn SessionEngine<F>>) {
1220        self.engines.insert(engine.engine_id().to_string(), engine);
1221    }
1222
1223    pub fn contains(&self, engine_id: &str) -> bool {
1224        self.engines.contains_key(engine_id)
1225    }
1226
1227    pub fn get(&self, engine_id: &str) -> Option<&dyn SessionEngine<F>> {
1228        self.engines.get(engine_id).map(|e| e.as_ref())
1229    }
1230
1231    pub fn spawn(
1232        &self,
1233        engine_id: &str,
1234        request: &SessionSpawnRequest,
1235    ) -> Result<Box<dyn DocumentSession<F>>, SessionError> {
1236        self.engines
1237            .get(engine_id)
1238            .ok_or_else(|| SessionError::EngineNotFound(engine_id.to_string()))?
1239            .spawn(request)
1240    }
1241
1242    pub fn engine_ids(&self) -> impl Iterator<Item = &str> {
1243        self.engines.keys().map(String::as_str)
1244    }
1245}
1246
1247// ── Kind facade ────────────────────────────────────────────────────────────
1248
1249/// Which registries hold an engine id. An id may be held by more than one
1250/// kind (a smolweb format can have both a block engine for cards and a
1251/// session engine for tiles); the HOST picks by surface context, so this is
1252/// reported as flags, not a single kind.
1253#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1254pub struct EngineKinds {
1255    pub document: bool,
1256    pub session: bool,
1257    pub surface: bool,
1258}
1259
1260impl EngineKinds {
1261    pub fn any(&self) -> bool {
1262        self.document || self.session || self.surface
1263    }
1264}
1265
1266/// Non-generic id-to-kind resolution: which registries hold each id is just
1267/// a map, so hosts resolve kinds without threading the frame type through
1268/// code that never touches frames. Built after registration from the
1269/// registries' id sets; host-handled ids (internal pages, ingest markers)
1270/// are the host's own vocabulary and deliberately absent.
1271#[derive(Clone, Debug, Default)]
1272pub struct EngineKindIndex {
1273    kinds: HashMap<String, EngineKinds>,
1274}
1275
1276impl EngineKindIndex {
1277    pub fn build<'a>(
1278        document_ids: impl IntoIterator<Item = &'a str>,
1279        session_ids: impl IntoIterator<Item = &'a str>,
1280        surface_ids: impl IntoIterator<Item = &'a str>,
1281    ) -> Self {
1282        let mut kinds: HashMap<String, EngineKinds> = HashMap::new();
1283        for id in document_ids {
1284            kinds.entry(id.to_string()).or_default().document = true;
1285        }
1286        for id in session_ids {
1287            kinds.entry(id.to_string()).or_default().session = true;
1288        }
1289        for id in surface_ids {
1290            kinds.entry(id.to_string()).or_default().surface = true;
1291        }
1292        Self { kinds }
1293    }
1294
1295    pub fn kinds_of(&self, engine_id: &str) -> EngineKinds {
1296        self.kinds.get(engine_id).copied().unwrap_or_default()
1297    }
1298}
1299
1300#[cfg(test)]
1301mod tests {
1302    use super::*;
1303    use crate::PageCaptureRequestId;
1304
1305    /// A frame type that just records what was rendered.
1306    type TextFrame = String;
1307
1308    struct EchoSession {
1309        address: String,
1310        scroll: f32,
1311        hidden: bool,
1312    }
1313
1314    impl DocumentSession<TextFrame> for EchoSession {
1315        fn frame(&mut self, width: u32, height: u32) -> TextFrame {
1316            format!("{} @ {width}x{height} scroll={}", self.address, self.scroll)
1317        }
1318        fn scroll_by(&mut self, _dx: f32, dy: f32) -> bool {
1319            self.scroll += dy;
1320            dy != 0.0
1321        }
1322        fn scroll_for_key(&mut self, key: SessionScrollKey) -> bool {
1323            self.scroll_by(
1324                0.0,
1325                if key == SessionScrollKey::PageDown {
1326                    100.0
1327                } else {
1328                    0.0
1329                },
1330            )
1331        }
1332        fn click_at(&mut self, x: f32, _y: f32) -> SessionClick {
1333            if x < 10.0 {
1334                SessionClick::Navigate("gemini://example.test/".into())
1335            } else {
1336                SessionClick::Miss
1337            }
1338        }
1339        fn links(&self) -> Vec<SessionLink> {
1340            vec![SessionLink {
1341                url: "gemini://example.test/".into(),
1342                rect: [0.0, 0.0, 10.0, 10.0],
1343            }]
1344        }
1345        fn set_hidden(&mut self, hidden: bool) {
1346            self.hidden = hidden;
1347        }
1348        fn as_any_ref(&self) -> &dyn Any {
1349            self
1350        }
1351        fn as_any(&mut self) -> &mut dyn Any {
1352            self
1353        }
1354    }
1355
1356    struct EchoSessionEngine;
1357
1358    impl SessionEngine<TextFrame> for EchoSessionEngine {
1359        fn engine_id(&self) -> &str {
1360            "echo.session"
1361        }
1362        fn spawn(
1363            &self,
1364            request: &SessionSpawnRequest,
1365        ) -> Result<Box<dyn DocumentSession<TextFrame>>, SessionError> {
1366            if request.address.is_empty() {
1367                return Err(SessionError::SpawnFailed("empty address".into()));
1368            }
1369            Ok(Box::new(EchoSession {
1370                address: request.address.clone(),
1371                scroll: 0.0,
1372                hidden: request.hidden,
1373            }))
1374        }
1375    }
1376
1377    #[test]
1378    fn registry_spawns_and_drives_a_session() {
1379        let mut registry = SessionRegistry::new();
1380        registry.register(Box::new(EchoSessionEngine));
1381
1382        let request = SessionSpawnRequest::new("https://example.test").with_viewport(800, 600);
1383        let mut session = registry.spawn("echo.session", &request).expect("spawns");
1384
1385        assert_eq!(
1386            session.frame(800, 600),
1387            "https://example.test @ 800x600 scroll=0"
1388        );
1389        assert!(session.scroll_by(0.0, 42.0));
1390        assert!(session.frame(800, 600).ends_with("scroll=42"));
1391        assert_eq!(
1392            session.click_at(5.0, 5.0),
1393            SessionClick::Navigate("gemini://example.test/".into())
1394        );
1395        assert_eq!(session.click_at(50.0, 5.0), SessionClick::Miss);
1396        assert_eq!(session.links().len(), 1);
1397        // Static-lane defaults: settled immediately, pump is a no-op.
1398        assert!(session.settled());
1399        session.pump(16.0);
1400    }
1401
1402    #[test]
1403    fn document_session_capture_defaults_to_unsupported() {
1404        let mut session = EchoSession {
1405            address: "https://example.test".into(),
1406            scroll: 0.0,
1407            hidden: false,
1408        };
1409        assert!(matches!(
1410            session.capture_page(PageCaptureRequest::viewport(PageCaptureRequestId::new(9))),
1411            Err(SessionError::Unsupported(_))
1412        ));
1413    }
1414
1415    #[test]
1416    fn document_session_accessibility_defaults_to_an_honest_absence() {
1417        let mut session = EchoSession {
1418            address: "https://example.test".into(),
1419            scroll: 0.0,
1420            hidden: false,
1421        };
1422        let target = DocumentA11yNodeId::new(7);
1423        assert_eq!(session.accessibility_projection(), None);
1424        assert_eq!(session.accessibility_click_target(target), None);
1425        assert!(
1426            !session.dispatch_accessibility_action(&DocumentA11yActionRequest {
1427                revision: 1,
1428                target,
1429                action: crate::DocumentA11yAction::Focus,
1430                data: None,
1431            })
1432        );
1433    }
1434
1435    #[test]
1436    fn neutral_pointer_dispatch_preserves_navigation_cursor_and_capture() {
1437        let mut registry = SessionRegistry::new();
1438        registry.register(Box::new(EchoSessionEngine));
1439        let mut session = registry
1440            .spawn(
1441                "echo.session",
1442                &SessionSpawnRequest::new("https://example.test"),
1443            )
1444            .expect("spawns");
1445
1446        let pressed = session.input(SessionInput::PointerButton {
1447            x: 5.0,
1448            y: 5.0,
1449            button: SessionPointerButton::Primary,
1450            state: SessionButtonState::Pressed,
1451            modifiers: SessionModifiers::default(),
1452        });
1453        assert_eq!(
1454            pressed.effect,
1455            SessionEffect::Navigate("gemini://example.test/".into())
1456        );
1457        assert_eq!(pressed.cursor, Some(SessionCursor::Default));
1458        assert_eq!(pressed.capture, Some(true));
1459
1460        let released = session.input(SessionInput::PointerButton {
1461            x: 5.0,
1462            y: 5.0,
1463            button: SessionPointerButton::Primary,
1464            state: SessionButtonState::Released,
1465            modifiers: SessionModifiers::default(),
1466        });
1467        assert_eq!(released.effect, SessionEffect::Ignored);
1468        assert_eq!(released.capture, Some(false));
1469    }
1470
1471    #[test]
1472    fn unknown_engine_is_a_named_error() {
1473        let registry: SessionRegistry<TextFrame> = SessionRegistry::new();
1474        let err = match registry.spawn("nope", &SessionSpawnRequest::new("x")) {
1475            Ok(_) => panic!("unknown engine must not spawn"),
1476            Err(err) => err,
1477        };
1478        assert_eq!(err, SessionError::EngineNotFound("nope".into()));
1479    }
1480
1481    #[test]
1482    fn downcast_reaches_lane_extras() {
1483        let mut registry = SessionRegistry::new();
1484        registry.register(Box::new(EchoSessionEngine));
1485        let mut session = registry
1486            .spawn("echo.session", &SessionSpawnRequest::new("a"))
1487            .unwrap();
1488        session.set_hidden(true);
1489        assert!(
1490            session.as_any_ref().downcast_ref::<EchoSession>().is_some(),
1491            "immutable hosts can reach lane extras without taking session ownership"
1492        );
1493        let echo = session
1494            .as_any()
1495            .downcast_mut::<EchoSession>()
1496            .expect("concrete lane type reachable");
1497        assert!(echo.hidden);
1498    }
1499
1500    #[test]
1501    fn kind_index_reports_flags_not_a_single_kind() {
1502        let mut sessions: SessionRegistry<TextFrame> = SessionRegistry::new();
1503        sessions.register(Box::new(EchoSessionEngine));
1504
1505        // An id may be held by more than one kind (block engine for cards +
1506        // session engine for tiles); the index reports flags, host picks.
1507        let index = EngineKindIndex::build(
1508            ["nematic.gemtext"],
1509            sessions.engine_ids().chain(["nematic.gemtext"]),
1510            ["scrying.web"],
1511        );
1512        assert!(index.kinds_of("echo.session").session);
1513        let both = index.kinds_of("nematic.gemtext");
1514        assert!(both.document && both.session && !both.surface);
1515        assert!(index.kinds_of("scrying.web").surface);
1516        assert!(!index.kinds_of("absent").any());
1517    }
1518
1519    #[test]
1520    fn page_zoom_is_a_named_absence_until_a_lane_wires_it() {
1521        let mut session = EchoSession {
1522            address: "gemini://example.test/".into(),
1523            scroll: 0.0,
1524            hidden: false,
1525        };
1526        assert!(matches!(
1527            session.set_page_zoom(1.25),
1528            Err(SessionError::Unsupported(_))
1529        ));
1530    }
1531
1532    #[test]
1533    fn zoom_state_keeps_the_request_and_clamps_only_the_applied_value() {
1534        let state = DocumentZoomState::clamped(9.0, 0.25, 5.0);
1535        assert_eq!(state.requested, 9.0);
1536        assert_eq!(state.applied, 5.0);
1537
1538        let state = DocumentZoomState::clamped(0.1, 0.25, 5.0);
1539        assert_eq!(state.requested, 0.1);
1540        assert_eq!(state.applied, 0.25);
1541
1542        assert_eq!(DocumentZoomState::clamped(1.5, 0.25, 5.0).applied, 1.5);
1543        assert_eq!(
1544            DocumentZoomState::clamped(f32::NAN, 0.25, 5.0).applied,
1545            1.0,
1546            "a non-finite request must not reach layout as a viewport divisor"
1547        );
1548    }
1549
1550    #[test]
1551    fn pending_work_exposes_a_sleepable_timer_deadline() {
1552        let now = std::time::Instant::now();
1553        let work = SessionPendingWork::timer(std::time::Duration::from_millis(25));
1554        let deadline = work.next_wake(now).expect("timer has a wake deadline");
1555        assert!(deadline >= now + std::time::Duration::from_millis(25));
1556        assert!(!work.is_idle());
1557        assert!(
1558            work.is_settled(),
1559            "a future timer is wakeable without making a live page perpetually unsettled"
1560        );
1561        assert!(
1562            !SessionPendingWork {
1563                external: true,
1564                ..SessionPendingWork::idle()
1565            }
1566            .is_settled()
1567        );
1568        assert!(SessionPendingWork::idle().next_wake(now).is_none());
1569        assert_eq!(
1570            SessionPendingWork {
1571                microtasks: true,
1572                ..SessionPendingWork::idle()
1573            }
1574            .next_wake(now),
1575            Some(now)
1576        );
1577    }
1578
1579    // TASK5 DRAFT API FIXTURES BEGIN. Missing seams have explicit absence adapters.
1580    fn t5_api_take_absent(_session: &mut dyn DocumentSession<TextFrame>) -> Option<()> {
1581        _session.take_encoded_form_submission().map(|_| ())
1582    }
1583    fn t5_api_address_absent(_session: &dyn DocumentSession<TextFrame>) -> Option<String> {
1584        _session.current_address()
1585    }
1586    fn t5_api_request_spawn_absent(
1587        _engine: &dyn SessionEngine<TextFrame>,
1588        _request: &SessionSpawnRequest,
1589        _bytes: &[u8],
1590    ) -> Result<(), SessionError> {
1591        let request = SessionDocumentRequest { url: _request.address.clone(), method: "POST".into(),
1592            headers: vec![], body: Some(_bytes.to_vec()), cache: "default".into(), redirect: "follow".into(),
1593            mode: "navigate".into(), referrer: String::new(), referrer_policy: String::new(),
1594            credentials: "include".into(), integrity: String::new() };
1595        _engine.spawn_request(_request, &request).map(|_| ())
1596    }
1597    #[test]
1598    fn phase_c_t5_api_legacy_submission_literal() {
1599        let value = SessionFormSubmission {
1600            action: "https://forms.test/send".into(), method: SessionFormMethod::Post,
1601            fields: vec![("q".into(), "café".into())],
1602        };
1603        fn retains_serde<T:serde::Serialize+for<'de>serde::Deserialize<'de>>() {}
1604        retains_serde::<SessionFormSubmission>();
1605        let copied=value.clone();
1606        let SessionFormSubmission{action,method,fields}=copied;
1607        assert_eq!((action,method,fields),("https://forms.test/send".into(),SessionFormMethod::Post,vec![("q".into(),"café".into())]));
1608    }
1609    #[test]
1610    fn phase_c_t5_api_legacy_result_literal() {
1611        let value = SessionInputResult { effect: SessionEffect::Handled,
1612            cursor: Some(SessionCursor::Text), capture: Some(false), editable: true };
1613        let SessionInputResult { effect, cursor, capture, editable } = value;
1614        let tag = match effect { SessionEffect::Ignored => 0, SessionEffect::Handled => 1,
1615            SessionEffect::Navigate(_) => 2, SessionEffect::Submit(_) => 3,
1616            SessionEffect::Cancelled => 4 };
1617        assert_eq!((tag, cursor, capture, editable), (1, Some(SessionCursor::Text), Some(false), true));
1618    }
1619    #[test]
1620    fn key_default_scroll_respects_effect_and_effective_editable_focus() {
1621        let cases = [
1622            (SessionEffect::Ignored, false, true),
1623            (SessionEffect::Ignored, true, false),
1624            (SessionEffect::Handled, false, false),
1625            (SessionEffect::Cancelled, false, false),
1626            (SessionEffect::Navigate("https://example.test/next".into()), false, false),
1627            (SessionEffect::Submit(SessionFormSubmission::default()), false, false),
1628        ];
1629        for (effect, editable, expected) in cases {
1630            assert_eq!(effect.allows_default_scroll(editable), expected, "{effect:?}, editable={editable}");
1631        }
1632
1633        // A native navigation can install a new session during dispatch. Its
1634        // editable focus, rather than the outgoing result's flag, decides the
1635        // next default action without consuming the typed input result.
1636        let result = SessionInputResult {
1637            effect: SessionEffect::Ignored,
1638            cursor: Some(SessionCursor::Text),
1639            capture: Some(false),
1640            editable: false,
1641        };
1642        assert!(result.effect.allows_default_scroll(result.editable));
1643        assert!(!result.effect.allows_default_scroll(true));
1644        assert_eq!(result.cursor, Some(SessionCursor::Text));
1645        assert_eq!(result.capture, Some(false));
1646    }
1647    #[test]
1648    fn phase_c_t5_api_legacy_spawn_unicode_body() {
1649        let request = SessionSpawnRequest { address: "https://forms.test/".into(),
1650            body: Some("café".into()), content_type: Some("text/html".into()),
1651            viewport: (320, 240), hidden: false };
1652        assert_eq!(request.body.as_deref(), Some("café"));
1653        assert_eq!(SessionSpawnRequest::new("a").with_body("café").body, request.body);
1654    }
1655    #[test]
1656    fn phase_c_t5_api_old_session_accessor_none() {
1657        let mut old = EchoSession { address: "old".into(), scroll: 0.0, hidden: false };
1658        assert!(t5_api_take_absent(&mut old).is_none());
1659        let result = old.input(SessionInput::PointerButton { x: 1.0, y: 1.0,
1660            button: SessionPointerButton::Primary, state: SessionButtonState::Pressed,
1661            modifiers: SessionModifiers::default() });
1662        assert_eq!(result.effect, SessionEffect::Navigate("gemini://example.test/".into()));
1663    }
1664    #[test]
1665    fn phase_c_t5_api_old_factory_rich_decline() {
1666        let request = SessionSpawnRequest::new("https://forms.test/");
1667        assert!(matches!(t5_api_request_spawn_absent(&EchoSessionEngine, &request, &[0,128,255]),
1668            Err(SessionError::Unsupported(_))));
1669        let mut ordinary = EchoSessionEngine.spawn(&request).unwrap();
1670        assert!(ordinary.frame(1, 1).starts_with("https://forms.test/"));
1671    }
1672    #[test]
1673    fn phase_c_t5_api_old_session_current_address_none() {
1674        let old = EchoSession { address: "legacy".into(), scroll: 0.0, hidden: false };
1675        assert!(t5_api_address_absent(&old).is_none());
1676        assert_eq!(old.address, "legacy");
1677    }
1678    // TASK5 DRAFT API FIXTURES END.
1679}