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