kernel/content.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//! Portable content-engine state types.
8//!
9//! Shared vocabulary the shell uses to describe content viewers,
10//! independent of which engine (Servo / Wry / `iced_webview` / Blitz /
11//! a future MiddleNet Direct Lane) is backing any given pane. The
12//! types here are WASM-clean and have no dependency on a particular
13//! content engine.
14//!
15//! Each provider is expected to convert between its native types and
16//! these portable ones at its boundary — typically in a
17//! `*_status_sync` module on the shell side, or inside the provider
18//! crate if it's already graphshell-aware. Conversion is always
19//! lossless for the states this module defines; if a provider grows a
20//! state that doesn't map, we add a variant here and update the
21//! providers in lockstep.
22
23use serde::{Deserialize, Serialize};
24
25// This module carries two portable types: `ContentLoadState` and
26// `ViewerInstanceId` (declared below, after the load-state tests). The
27// 2026-04-22 viewer-identity design pass is settled — a sum-over-providers
28// enum, not a generic parameter threaded through host session-state types, and
29// the Servo variant holds its `WebViewId` in `serde_json` form rather than the
30// packed `u64` first sketched, because `WebViewId`'s fields are private to the
31// servo crate. Per-variant encoding is documented on `ViewerInstanceId` itself.
32
33/// Life-cycle state of content loading in a viewer.
34///
35/// Models the three progress checkpoints every mainstream content
36/// engine exposes, mapped onto the WHATWG `Document.readyState`
37/// vocabulary where applicable:
38///
39/// - `Started` — fetch has kicked off; no content yet. Not a `readyState`
40/// value itself but the pre-"loading" transition every engine surfaces.
41/// - `HeadParsed` — corresponds to `document.readyState == "interactive"`:
42/// the document element is available in the DOM, subresources may still
43/// be loading.
44/// - `Complete` — corresponds to `document.readyState == "complete"`:
45/// document and all subresources have finished loading.
46///
47/// [`default`]: Default::default
48///
49/// Conversion from provider types:
50///
51/// - `servo::LoadStatus` — 1:1 on the three variants. See
52/// `shell/desktop/lifecycle/webview_status_sync.rs::content_load_state_from_servo`.
53/// - `iced_webview` — the `PageLoadStatus` / equivalent surface maps
54/// onto these three checkpoints; converter lives alongside the iced
55/// host adapter when iced lands as a production host.
56/// - `Wry` (via `WebView::is_ready`) — only exposes a binary ready/not-
57/// ready signal; provider converts by mapping not-ready → `Started`
58/// and ready → `Complete`. `HeadParsed` is never observed under Wry
59/// today, which is acceptable — the state is advisory.
60/// - MiddleNet Direct Lane (Gemini/Gopher/Markdown viewers) — emits
61/// `Complete` synchronously on first frame; `Started` only during
62/// the fetch window.
63///
64/// Defaulting to [`Self::Complete`] matches the pre-wrap behavior of
65/// the toolbar view-model and avoids spurious "loading" chrome during
66/// cold startup before any viewer has reported status.
67#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
68pub enum ContentLoadState {
69 /// Load request has been issued; no content bytes parsed yet.
70 Started,
71 /// The document's `<head>` has been parsed. Subresources may still
72 /// be loading. Equivalent to `document.readyState == "interactive"`.
73 HeadParsed,
74 /// Document and subresources complete. Equivalent to
75 /// `document.readyState == "complete"`.
76 #[default]
77 Complete,
78}
79
80impl ContentLoadState {
81 /// `true` when the viewer has loaded enough content that interaction
82 /// (scrolling, clicking links) is meaningful. Used by toolbar chrome
83 /// to gate "loading" affordances.
84 pub fn is_interactive(self) -> bool {
85 matches!(self, Self::HeadParsed | Self::Complete)
86 }
87
88 /// `true` when the viewer has fully completed loading. Used to
89 /// gate one-shot post-load side effects (thumbnail capture, title
90 /// refresh, link-preview prefetch).
91 pub fn is_complete(self) -> bool {
92 matches!(self, Self::Complete)
93 }
94
95 /// Serialize to a stable machine-readable name. Prefer this over
96 /// `{:?}` / `Debug` when round-tripping through persistence or
97 /// diagnostic channels, so renaming the Rust variant doesn't break
98 /// on-disk or on-wire data.
99 pub fn persisted_name(self) -> &'static str {
100 match self {
101 Self::Started => "started",
102 Self::HeadParsed => "head-parsed",
103 Self::Complete => "complete",
104 }
105 }
106
107 /// Inverse of [`persisted_name`]. Returns `None` for unknown names so
108 /// the caller can decide whether to fall back to [`Default`] or
109 /// surface a diagnostic.
110 ///
111 /// [`persisted_name`]: Self::persisted_name
112 /// [`Default`]: Default::default
113 pub fn from_persisted_name(raw: &str) -> Option<Self> {
114 match raw {
115 "started" => Some(Self::Started),
116 "head-parsed" => Some(Self::HeadParsed),
117 "complete" => Some(Self::Complete),
118 _ => None,
119 }
120 }
121}
122
123#[cfg(test)]
124mod tests {
125 use super::*;
126
127 #[test]
128 fn default_is_complete() {
129 // Toolbar chrome uses `Complete` as the cold-startup default to
130 // avoid flashing "loading" affordances before any viewer
131 // reports. Pin that in a test so changing the derive doesn't
132 // silently break that behavior.
133 assert_eq!(ContentLoadState::default(), ContentLoadState::Complete);
134 }
135
136 #[test]
137 fn is_interactive_matches_head_parsed_and_complete() {
138 assert!(!ContentLoadState::Started.is_interactive());
139 assert!(ContentLoadState::HeadParsed.is_interactive());
140 assert!(ContentLoadState::Complete.is_interactive());
141 }
142
143 #[test]
144 fn is_complete_only_matches_complete() {
145 assert!(!ContentLoadState::Started.is_complete());
146 assert!(!ContentLoadState::HeadParsed.is_complete());
147 assert!(ContentLoadState::Complete.is_complete());
148 }
149
150 #[test]
151 fn persisted_name_round_trips_all_variants() {
152 for state in [
153 ContentLoadState::Started,
154 ContentLoadState::HeadParsed,
155 ContentLoadState::Complete,
156 ] {
157 let name = state.persisted_name();
158 assert_eq!(
159 ContentLoadState::from_persisted_name(name),
160 Some(state),
161 "persisted_name round-trip failed for {state:?} (name={name})",
162 );
163 }
164 }
165
166 #[test]
167 fn from_persisted_name_rejects_unknown_values() {
168 assert_eq!(ContentLoadState::from_persisted_name(""), None);
169 assert_eq!(ContentLoadState::from_persisted_name("Complete"), None); // case-sensitive
170 assert_eq!(ContentLoadState::from_persisted_name("loading"), None); // not a canonical name
171 }
172
173 #[test]
174 fn persisted_names_are_lowercase_kebab() {
175 // Serialization-layer convention: persisted names are lowercase
176 // kebab-case. Enforcing this here so future contributors don't
177 // introduce a `"HeadParsed"`-style variant that breaks existing
178 // on-disk data.
179 for state in [
180 ContentLoadState::Started,
181 ContentLoadState::HeadParsed,
182 ContentLoadState::Complete,
183 ] {
184 let name = state.persisted_name();
185 assert_eq!(
186 name,
187 name.to_ascii_lowercase(),
188 "persisted name {name} must be lowercase"
189 );
190 assert!(
191 !name.contains('_'),
192 "persisted name {name} must use '-' (kebab), not '_' (snake)"
193 );
194 }
195 }
196
197 #[test]
198 fn serde_json_round_trips_all_variants() {
199 for state in [
200 ContentLoadState::Started,
201 ContentLoadState::HeadParsed,
202 ContentLoadState::Complete,
203 ] {
204 let encoded = serde_json::to_string(&state).expect("serialize");
205 let decoded: ContentLoadState = serde_json::from_str(&encoded).expect("deserialize");
206 assert_eq!(decoded, state);
207 }
208 }
209}
210
211// ---------------------------------------------------------------------------
212// Portable viewer-instance identity.
213// ---------------------------------------------------------------------------
214
215/// Provider-opaque identity for a content-viewer instance.
216///
217/// Graphshell's shell state tracks "which viewer has pending X?" across
218/// multiple content engines — Servo, Wry, `iced_webview`, MiddleNet's
219/// Direct Lane — that are expected to coexist in one shell. The enum
220/// keeps the provider explicit so mixed-provider scenarios (some panes
221/// backed by Servo, some by Wry, some by MiddleNet) work without a
222/// generic type parameter propagating through
223/// `GraphshellRuntime`, the authority bundles, or the view-model.
224///
225/// Each variant's payload is provider-chosen; each provider's boundary
226/// code (typically in `shell/desktop/lifecycle/webview_status_sync.rs`
227/// for Servo, analogous modules for other providers) converts to/from
228/// its native identity. The payload is **session-local** — not stable
229/// across app restarts — matching the lifecycle of every underlying
230/// native viewer id.
231///
232/// Current encoding choices:
233///
234/// - `Servo`: JSON-encoded `servo::WebViewId`. `WebViewId`'s fields
235/// are private to the servo crate, so the portable encoding goes
236/// through `serde_json` for a stable, deterministic round-trip. The
237/// per-op cost is a small allocation — acceptable for the low-
238/// frequency mutation sites (thumbnail in-flight, focus target,
239/// pending context-surface requests). If it becomes a hotspot, a
240/// host-side registry mapping `WebViewId` ↔ `u64` is a drop-in
241/// replacement that preserves this public API.
242/// - `Wry`, `IcedWebview`, `MiddlenetDirect`: placeholder variants
243/// representing the shape providers will fill in when they land.
244/// Kept explicit in the enum today so match arms that handle
245/// "all viewer providers" fail closed when a new one arrives.
246#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
247pub enum ViewerInstanceId {
248 /// A `servo::WebViewId` encoded as its `serde_json` representation.
249 /// The inner string is treated as opaque by host session state;
250 /// only the servo boundary inspects it.
251 Servo(String),
252 /// Reserved for future Wry viewer integration. The `u64` payload
253 /// carries Wry's native handle; encoding pattern matches Wry's
254 /// existing API when the integration lands.
255 #[doc(hidden)]
256 Wry(u64),
257 /// Reserved for future `iced_webview` integration.
258 #[doc(hidden)]
259 IcedWebview(u64),
260 /// Reserved for MiddleNet Direct Lane viewers (Gemini / Gopher /
261 /// Markdown / plain-text / RSS). These are in-process viewers with
262 /// simpler identity needs — a single `u32` namespace-local id.
263 #[doc(hidden)]
264 MiddlenetDirect(u32),
265}
266
267impl ViewerInstanceId {
268 /// Name of the content provider that produced this id. Useful for
269 /// diagnostics and for host code that needs to route dispatch per
270 /// provider.
271 pub fn provider_name(&self) -> &'static str {
272 match self {
273 Self::Servo(_) => "servo",
274 Self::Wry(_) => "wry",
275 Self::IcedWebview(_) => "iced_webview",
276 Self::MiddlenetDirect(_) => "middlenet_direct",
277 }
278 }
279}
280
281#[cfg(test)]
282mod viewer_instance_id_tests {
283 use super::*;
284 use std::collections::HashSet;
285
286 #[test]
287 fn provider_name_covers_all_variants() {
288 assert_eq!(
289 ViewerInstanceId::Servo(String::new()).provider_name(),
290 "servo"
291 );
292 assert_eq!(ViewerInstanceId::Wry(0).provider_name(), "wry");
293 assert_eq!(
294 ViewerInstanceId::IcedWebview(0).provider_name(),
295 "iced_webview"
296 );
297 assert_eq!(
298 ViewerInstanceId::MiddlenetDirect(0).provider_name(),
299 "middlenet_direct"
300 );
301 }
302
303 #[test]
304 fn different_providers_with_same_payload_dont_collide() {
305 // A u64 0 under Wry and a u64 0 under IcedWebview must NOT
306 // compare equal or hash to the same bucket. Matters for shells
307 // that run multiple providers — a thumbnail capture pending
308 // for Wry viewer #0 must not be mistaken for one pending under
309 // iced_webview viewer #0.
310 let a = ViewerInstanceId::Wry(0);
311 let b = ViewerInstanceId::IcedWebview(0);
312 assert_ne!(a, b);
313
314 let mut set = HashSet::new();
315 set.insert(a);
316 assert!(!set.contains(&b));
317 set.insert(b);
318 assert_eq!(set.len(), 2);
319 }
320
321 #[test]
322 fn servo_equal_payloads_are_equal() {
323 // Two portable ids encoded from the same underlying servo
324 // WebViewId must compare equal. Pin the string-equality
325 // contract so the JSON-encoding approach remains sound — if
326 // we switch to a host-registry-assigned u64 later, this
327 // semantic stays the same.
328 let a = ViewerInstanceId::Servo("TEST-ENCODING-1".to_string());
329 let b = ViewerInstanceId::Servo("TEST-ENCODING-1".to_string());
330 assert_eq!(a, b);
331
332 let c = ViewerInstanceId::Servo("TEST-ENCODING-2".to_string());
333 assert_ne!(a, c);
334 }
335
336 #[test]
337 fn hashset_membership_works_across_clone() {
338 let id = ViewerInstanceId::Servo("MVP-123".to_string());
339 let mut set = HashSet::new();
340 set.insert(id.clone());
341 assert!(set.contains(&id));
342 assert!(set.contains(&ViewerInstanceId::Servo("MVP-123".to_string())));
343 set.remove(&ViewerInstanceId::Servo("MVP-123".to_string()));
344 assert!(set.is_empty());
345 }
346
347 #[test]
348 fn serde_json_roundtrip_preserves_variant_and_payload() {
349 let samples = [
350 ViewerInstanceId::Servo("{encoded-servo-id}".to_string()),
351 ViewerInstanceId::Wry(42),
352 ViewerInstanceId::IcedWebview(99),
353 ViewerInstanceId::MiddlenetDirect(7),
354 ];
355 for id in samples {
356 let encoded = serde_json::to_string(&id).expect("serialize");
357 let decoded: ViewerInstanceId = serde_json::from_str(&encoded).expect("deserialize");
358 assert_eq!(decoded, id);
359 }
360 }
361}