Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(renderer): stabilize style observations and screencast polling

ldm07608292c78b2
diff --git a/README.md b/README.md
index b847af2b0..273253ad4 100644
--- a/README.md
+++ b/README.md
@@ -179,7 +179,8 @@ operations that genuinely require them.
| --- | --- |
| Extract HTML/Markdown, query the DOM, run JS, inspect network/storage | Reads browser runtime state directly — does not trigger layout or paint |
| Read an element's box, hit-test coordinates, send coordinate input | Runs one layout calculation and retains only the latest frozen layout tree |
-| Capture a screenshot or refresh a screencast | Rebuilds from the current DOM/style, replaces the frozen tree, renders a fresh frame, and discards the frame after use |
+| Capture a screenshot | Rebuilds from the current DOM/style, replaces the frozen tree, renders a fresh frame, and discards its paint state after use |
+| Poll a screencast | Compares generation metadata only; clean state emits no frame, while changed state rebuilds and emits one fresh frame |
<p align="center">
<a href="assets/moli_ondemand_rendering_flow.svg">
@@ -242,9 +243,10 @@ Layout is an on-demand snapshot rather than continuously maintained state. The
first geometry request (a cold start) builds a working layout tree from the
current DOM/style, freezes its canonical geometry into an immutable,
DOM-independent `FrozenLayoutTree`, and retains only that latest tree. Ordinary
-geometry reads may reuse it even if the page has changed; screenshots and
-screencasts always rebuild, replace the frozen tree, and never reuse stale
-paint results.
+geometry reads may reuse it even if the page has changed. Screenshots always
+rebuild and replace the frozen tree. Each screencast subscription remembers
+only an opaque visual-state token: an unchanged token suppresses the poll,
+while a changed token triggers one fresh frame. Paint results are never reused.
## Architecture
@@ -263,6 +265,7 @@ integration. Every real refresh builds a temporary working tree from that
source, optionally produces and consumes one fresh paint snapshot, freezes the
canonical box/fragment geometry into a compact `FrozenLayoutTree`, and discards
the working tree, style borrows, layout caches, diagnostics, and paint state.
+Screencast tokens contain generation metadata, never layout or paint data.
Source lookup and hit-test candidates are derived from the frozen tree when
queried. The system has no incrementally maintained layout tree, damage graph,
retained display list, GPU compositor, or persistent window.
diff --git a/docs/README.es.md b/docs/README.es.md
index eb3b34d89..6df37d362 100644
--- a/docs/README.es.md
+++ b/docs/README.es.md
@@ -155,7 +155,8 @@ Lo que la mayoría de las tareas de automatización de navegador necesitan de ve
| --- | --- |
| Extraer HTML/Markdown, consultar el DOM, ejecutar JS, inspeccionar la red o el almacenamiento | Lee el estado del runtime del navegador directamente, sin disparar layout ni pintado |
| Leer el bounding box de un elemento, comprobar coordenadas, enviar entradas por coordenadas | Calcula el layout y se queda solo con el árbol de layout congelado más reciente |
-| Capturar una pantalla o actualizar un screencast | Reconstruye a partir del DOM y los estilos actuales, sustituye el árbol congelado, renderiza un frame nuevo y lo descarta después de usarlo |
+| Capturar una pantalla | Reconstruye a partir del DOM y los estilos actuales, sustituye el árbol congelado, renderiza un frame nuevo y descarta su estado de pintado |
+| Sondear un screencast | Compara solo metadatos de generación; si el estado no ha cambiado no emite ningún frame, y si ha cambiado genera un frame nuevo |
<p align="center">
<a href="../assets/moli_ondemand_rendering_flow.svg">
@@ -195,7 +196,7 @@ En Moli, las operaciones caras del navegador hay que activarlas explícitamente:
| `--image`, `--font`, `--audio`, `--video`, `--media`, `--text-track` | Activa por separado una familia concreta de recursos opcionales |
| `--profile-dir`, `--http-cache-dir`, `--cookie-file` | Activa de forma selectiva la persistencia que necesite tu carga de trabajo |
-El resultado del layout es una instantánea tomada bajo demanda, no un estado que se mantiene todo el tiempo: la primera petición de geometría (cold start) construye un árbol de trabajo temporal a partir del DOM y los estilos actuales, congela su geometría canónica en un `FrozenLayoutTree` inmutable e independiente del DOM, y se queda solo con ese árbol, el más reciente. Las lecturas de geometría normales pueden reutilizarlo aunque la página haya cambiado entretanto; las capturas de pantalla y los screencasts, en cambio, siempre reconstruyen y sustituyen el árbol congelado, y nunca reutilizan resultados de pintado antiguos.
+El resultado del layout es una instantánea tomada bajo demanda, no un estado que se mantiene todo el tiempo: la primera petición de geometría (cold start) construye un árbol de trabajo temporal a partir del DOM y los estilos actuales, congela su geometría canónica en un `FrozenLayoutTree` inmutable e independiente del DOM, y se queda solo con ese árbol, el más reciente. Las lecturas de geometría normales pueden reutilizarlo aunque la página haya cambiado entretanto. Las capturas de pantalla siempre reconstruyen y sustituyen el árbol congelado. Cada suscripción de screencast solo conserva un token opaco del estado visual: un token sin cambios evita el trabajo, mientras que un cambio genera un frame nuevo. Los resultados de pintado nunca se reutilizan.
## Arquitectura
@@ -208,7 +209,7 @@ Moli es un motor de navegador independiente, no un wrapper de Chromium. Está co
- Taffy + Parley — layout de cajas y de texto
- AnyRender/Vello CPU, `usvg` y el ecosistema de imágenes de Rust — renderizado por software
-El documento y los estilos tienen una única fuente de verdad: la integración del DOM nativo con Stylo. Cada actualización real crea un árbol de trabajo temporal, genera y consume bajo demanda una nueva instantánea de pintado, congela la geometría final de cajas y fragmentos en un `FrozenLayoutTree` compacto, y después descarta el árbol de trabajo, las referencias de estilo, las cachés de layout, los diagnósticos y el estado de pintado. Los índices de origen y los candidatos de hit-test se derivan del árbol congelado en el momento de la consulta. No hay ningún árbol de layout mantenido de forma incremental, ni damage graph, ni display list retenida, ni compositor de GPU, ni ventana persistente.
+El documento y los estilos tienen una única fuente de verdad: la integración del DOM nativo con Stylo. Cada actualización real crea un árbol de trabajo temporal, genera y consume bajo demanda una nueva instantánea de pintado, congela la geometría final de cajas y fragmentos en un `FrozenLayoutTree` compacto, y después descarta el árbol de trabajo, las referencias de estilo, las cachés de layout, los diagnósticos y el estado de pintado. Los tokens de screencast contienen metadatos de generación, nunca datos de layout o pintado. Los índices de origen y los candidatos de hit-test se derivan del árbol congelado en el momento de la consulta. No hay ningún árbol de layout mantenido de forma incremental, ni damage graph, ni display list retenida, ni compositor de GPU, ni ventana persistente.
## Datos de las pruebas
diff --git a/docs/README.fr.md b/docs/README.fr.md
index d1977a1bc..5fd3f7627 100644
--- a/docs/README.fr.md
+++ b/docs/README.fr.md
@@ -155,7 +155,8 @@ Ce dont la plupart des tâches d'automatisation ont réellement besoin, c'est de
| --- | --- |
| Extraire du HTML/Markdown, interroger le DOM, exécuter du JS, inspecter le réseau ou le stockage | Lit directement l'état du moteur du navigateur, sans déclencher ni mise en page ni rendu |
| Lire la boîte englobante d'un élément, tester des coordonnées, envoyer une entrée par coordonnées | Calcule la mise en page à la volée et ne conserve que le dernier arbre figé |
-| Prendre une capture d'écran ou actualiser un screencast | Reconstruit à partir du DOM et des styles actuels, remplace l'arbre figé, produit une nouvelle image, puis la libère aussitôt après usage |
+| Prendre une capture d'écran | Reconstruit à partir du DOM et des styles actuels, remplace l'arbre figé, produit une nouvelle image, puis libère son état de rendu |
+| Sonder un screencast | Compare uniquement les métadonnées de génération ; un état inchangé n'émet aucune image, tandis qu'un changement produit une image fraîche |
<p align="center">
<a href="../assets/moli_ondemand_rendering_flow.svg">
@@ -195,7 +196,7 @@ Dans Moli, les opérations coûteuses du navigateur ne sont jamais activées par
| `--image`, `--font`, `--audio`, `--video`, `--media`, `--text-track` | Active une famille spécifique de ressources optionnelles |
| `--profile-dir`, `--http-cache-dir`, `--cookie-file` | Active, au cas par cas, la persistance dont la charge de travail a besoin |
-Le résultat de la mise en page est un instantané produit à la demande, pas un état maintenu en continu : la première requête de géométrie (« à froid ») construit un arbre de travail temporaire à partir du DOM et des styles courants, fige sa géométrie canonique dans un `FrozenLayoutTree` immuable et indépendant du DOM, puis ne conserve que ce dernier. Les lectures de géométrie ultérieures peuvent réutiliser cet arbre figé, même si la page a changé entre-temps. Les captures d'écran et les screencasts, eux, reconstruisent et remplacent systématiquement l'arbre figé, sans jamais réutiliser un ancien résultat de rendu.
+Le résultat de la mise en page est un instantané produit à la demande, pas un état maintenu en continu : la première requête de géométrie (« à froid ») construit un arbre de travail temporaire à partir du DOM et des styles courants, fige sa géométrie canonique dans un `FrozenLayoutTree` immuable et indépendant du DOM, puis ne conserve que ce dernier. Les lectures de géométrie ultérieures peuvent réutiliser cet arbre figé, même si la page a changé entre-temps. Les captures d'écran reconstruisent toujours et remplacent l'arbre figé. Chaque abonnement de screencast ne mémorise qu'un jeton opaque d'état visuel : un jeton inchangé supprime le travail, tandis qu'un changement produit une image fraîche. Les résultats de rendu ne sont jamais réutilisés.
## Architecture
@@ -208,7 +209,7 @@ Moli est un noyau de navigateur autonome — pas une surcouche posée sur Chromi
- Taffy + Parley — mise en page des boîtes et du texte
- AnyRender/Vello CPU, `usvg` et l'écosystème d'images Rust — rendu logiciel
-Le document et les styles n'ont qu'une seule source de vérité : le DOM natif, intégré à Stylo. Chaque véritable rafraîchissement crée un arbre de travail temporaire, produit et consomme au besoin un nouvel instantané de rendu, fige la géométrie finale des boîtes et des fragments dans un `FrozenLayoutTree` compact, puis élimine l'arbre de travail, les références de style, les caches de mise en page, les diagnostics et l'état de rendu. Les associations aux sources et les candidats au hit-testing sont dérivés de l'arbre figé au moment des requêtes. Il n'y a ici ni arbre de mise en page maintenu de façon incrémentale, ni graphe de dommages, ni liste d'affichage persistante, ni compositeur GPU, ni fenêtre persistante.
+Le document et les styles n'ont qu'une seule source de vérité : le DOM natif, intégré à Stylo. Chaque véritable rafraîchissement crée un arbre de travail temporaire, produit et consomme au besoin un nouvel instantané de rendu, fige la géométrie finale des boîtes et des fragments dans un `FrozenLayoutTree` compact, puis élimine l'arbre de travail, les références de style, les caches de mise en page, les diagnostics et l'état de rendu. Les jetons de screencast contiennent des métadonnées de génération, jamais des données de mise en page ou de rendu. Les associations aux sources et les candidats au hit-testing sont dérivés de l'arbre figé au moment des requêtes. Il n'y a ici ni arbre de mise en page maintenu de façon incrémentale, ni graphe de dommages, ni liste d'affichage persistante, ni compositeur GPU, ni fenêtre persistante.
## Données de test
diff --git a/docs/README.zh-CN.md b/docs/README.zh-CN.md
index 5044700e4..e3897d323 100644
--- a/docs/README.zh-CN.md
+++ b/docs/README.zh-CN.md
@@ -194,7 +194,7 @@ Moli 是 Lexmount 旗下的开源无头浏览器;Lexmount Browser 则是围绕
| `--image`、`--font`、`--audio`、`--video`、`--media`、`--text-track` | 单独启用某一类可选资源 |
| `--profile-dir`、`--http-cache-dir`、`--cookie-file` | 按工作负载需要,选择性开启持久化能力 |
-布局结果是按需采样的一份快照,而不是持续维护的状态:第一次几何请求(冷启动)会根据当前 DOM/样式构建临时工作布局树,再把工作树丢弃后无法重算的几何冻结成一棵与 DOM 无关、不可变的 `FrozenLayoutTree`,长期只保留最新的这一棵树。在此之后,即便页面发生了变化,普通几何读取也可能复用旧树;截图和屏幕串流则每次都会重新构建并替换冻结树,不会复用旧的绘制结果。
+布局结果是按需采样的一份快照,而不是持续维护的状态:第一次几何请求(冷启动)会根据当前 DOM/样式构建临时工作布局树,再把工作树丢弃后无法重算的几何冻结成一棵与 DOM 无关、不可变的 `FrozenLayoutTree`,长期只保留最新的这一棵树。在此之后,即便页面发生了变化,普通几何读取也可能复用旧树。截图始终重新构建并替换冻结树。每个屏幕串流订阅只记录一个不透明的视觉状态 token:状态未变时不产帧,状态变化时才新鲜渲染一帧;绘制结果不会被复用。
## 架构
@@ -207,7 +207,7 @@ Moli 是一个独立的浏览器内核,而不是对 Chromium 的封装。它
- Taffy + Parley——盒模型与文本布局
- AnyRender/Vello CPU、`usvg` 以及 Rust 图像生态——软件渲染
-文档和样式只有一个事实来源:原生 DOM 与 Stylo 的集成。每次真正的刷新,都会据此构建临时工作树,按需生成并消费一份新的绘制快照,把最终的盒与文字分片几何冻结成紧凑的 `FrozenLayoutTree`,随后丢弃工作树、样式借用、布局缓存、诊断和绘制状态。来源查询表和命中测试候选不再长期保存,而是在查询时从冻结树派生。整个系统没有增量维护的布局树、损伤区域图、保留式显示列表、GPU 合成器或持久化窗口。
+文档和样式只有一个事实来源:原生 DOM 与 Stylo 的集成。每次真正的刷新,都会据此构建临时工作树,按需生成并消费一份新的绘制快照,把最终的盒与文字分片几何冻结成紧凑的 `FrozenLayoutTree`,随后丢弃工作树、样式借用、布局缓存、诊断和绘制状态。屏幕串流 token 只包含 generation 元数据,不包含布局或绘制数据。来源查询表和命中测试候选仍在查询时从冻结树派生。整个系统没有增量维护的布局树、损伤区域图、保留式显示列表、GPU 合成器或持久化窗口。
## 测试数据
diff --git a/moli-cdp-smoke/README.md b/moli-cdp-smoke/README.md
index 38d731040..fb1954513 100644
--- a/moli-cdp-smoke/README.md
+++ b/moli-cdp-smoke/README.md
@@ -103,7 +103,7 @@ Covered well:
`open()` state reset, duplicate `send()`, synchronous event order, pending
asynchronous request cancellation, and suppression of asynchronous events and
timers while a synchronous request owns the main thread.
-- The focused `layout-screenshot` group drives a real raw WebSocket session through target creation/attachment, fixed viewport, lifecycle-gated navigation, DevTools-style PNG capture (`quality: 100`), paint/layout mutations, page clips, `captureBeyondViewport`, and the Chromium DevTools node-screenshot chain (`DOM.getBoxModel` + `Page.getLayoutMetrics` + page clip). It also covers Moli's uncached 1 FPS JPEG screencast: initial-frame delivery, 400x300 scaling, metadata/session routing, ACK backpressure, minimum cadence, mutation freshness, stop cleanup, and a separately restarted default-Mock boundary without `--layout`. The screenshot surface sequence can also run against Chromium as a coarse reference; the fixed-1-FPS and default-Mock branches are Moli-only.
+- The focused `layout-screenshot` group drives a real raw WebSocket session through target creation/attachment, fixed viewport, lifecycle-gated navigation, DevTools-style PNG capture (`quality: 100`), paint/layout mutations, page clips, `captureBeyondViewport`, and the Chromium DevTools node-screenshot chain (`DOM.getBoxModel` + `Page.getLayoutMetrics` + page clip). Its Moli-only TreeScope fixture also captures 104 open/closed Shadow Roots, nested roots, and 24 roots in an iframe twice, requiring stable pixels and completion within the protocol timeout. The group covers Moli's generation-gated 1 FPS JPEG screencast as well: initial-frame delivery, clean-state frame suppression without ACK backpressure, 400x300 scaling, metadata/session routing, mutation freshness, stop cleanup, and a separately restarted default-Mock boundary without `--layout`. The screenshot surface sequence can also run against Chromium as a coarse reference; the TreeScope, fixed-1-FPS, and default-Mock branches are Moli-only.
- The default raw `action-window` group holds Moli's on-demand input policy at
the public CDP boundary. Three acknowledged `Input.dispatchMouseEvent`
wheel commands remain delayed until one fixed one-second deadline, preserve
@@ -254,7 +254,7 @@ Runner layout:
- `groups/document_content.py`: Playwright and raw-CDP `Page.setDocumentContent` replacement identity, parser pause/resume, child-frame, and error-atomicity workflows.
- `groups/error_document.py`: failed main-document transport error Document identity, lifecycle, realm replacement, recovery, and multi-target isolation.
- `groups/dom_parser_mutations.py`: cross-engine raw-CDP parser-tail mutation publication and commit/DCL DOM binding barriers.
-- `groups/layout_screenshot.py`: raw current-viewport PNG, DevTools parameter compatibility, paint/layout mutation freshness, uncached 1 FPS JPEG screencast/ACK behavior, and Moli default-Mock restart boundary.
+- `groups/layout_screenshot.py`: raw current-viewport PNG, DevTools parameter compatibility, paint/layout mutation freshness, open/closed Shadow Root and iframe TreeScope stability, generation-gated 1 FPS JPEG screencast/ACK behavior, and Moli default-Mock restart boundary.
- `groups/action_window.py`: raw wheel admission/deadline batching, screenshot
flush/reset, derived-effect coalescing, and exact-Document retirement.
- `groups/pdf.py`: raw `Page.printToPDF` base64 and `ReturnAsStream` transport, `IO.read`, pagination, page ranges, orientation, PDF structure, and Chromium-shaped validation errors.
diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/layout_screenshot.py b/moli-cdp-smoke/moli_cdp_smoke/groups/layout_screenshot.py
index d862c36af..b9acc99e2 100644
--- a/moli-cdp-smoke/moli_cdp_smoke/groups/layout_screenshot.py
+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/layout_screenshot.py
@@ -431,50 +431,34 @@ async def _run_moli_screencast(
1.15,
"unacknowledged frame backpressure",
)
- _, _, ack_seen = await _success(
+ await _success(
client,
"Page.screencastFrameAck",
{"sessionId": generation},
session_id=session_id,
)
- second_event = await _next_screencast_frame(
+ await _assert_no_screencast_frame(
client,
session_id,
generation,
- initial_messages=ack_seen,
+ 1.25,
+ "clean visual-state poll",
)
- second_jpeg, second_metadata = _decode_screencast_frame(second_event)
- if second_metadata.get("timestamp", 0) - initial_metadata.get("timestamp", 0) < 0.9:
- raise SmokeError("screencast emitted acknowledged frames faster than 1 FPS")
await _evaluate(
client,
session_id,
"document.querySelector('#cards').style.display = 'none'",
)
- _, _, ack_seen = await _success(
- client,
- "Page.screencastFrameAck",
- {"sessionId": generation},
- session_id=session_id,
- )
- await _assert_no_screencast_frame(
- client,
- session_id,
- generation,
- 0.75,
- "1 FPS monotonic deadline",
- )
mutated_event = await _next_screencast_frame(
client,
session_id,
generation,
- initial_messages=ack_seen,
)
mutated_jpeg, mutated_metadata = _decode_screencast_frame(mutated_event)
- if mutated_metadata.get("timestamp", 0) - second_metadata.get("timestamp", 0) < 0.9:
+ if mutated_metadata.get("timestamp", 0) - initial_metadata.get("timestamp", 0) < 0.9:
raise SmokeError("screencast mutation frame violated the 1 FPS deadline")
- if mutated_jpeg == second_jpeg:
+ if mutated_jpeg == initial_jpeg:
raise SmokeError("screencast mutation reused the previous encoded frame")
await _success(
@@ -502,11 +486,83 @@ async def _run_moli_screencast(
"encodedWidth": 400,
"encodedHeight": 300,
"ackBackpressure": True,
+ "cleanFrameSuppressed": True,
+ "cleanPollRequiresNoAck": True,
"mutationChangedFrame": True,
},
)
+async def _run_moli_tree_scope_universe_capture(
+ client: RawCdpClient,
+ session_id: str,
+ results: list[dict[str, Any]],
+) -> None:
+ await _evaluate(
+ client,
+ session_id,
+ r"""
+(() => {
+ document.documentElement.style.cssText = 'margin:0;background:white';
+ document.body.style.cssText = 'margin:0;width:800px';
+ document.body.replaceChildren();
+ for (let index = 0; index < 104; index += 1) {
+ const host = document.createElement('section');
+ host.style.cssText = 'display:inline-block;width:4px;height:4px;background:rgb(20,90,160)';
+ document.body.appendChild(host);
+ const root = host.attachShadow({mode: index % 2 === 0 ? 'open' : 'closed'});
+ root.append(String(index % 10));
+ if (index % 16 === 0) {
+ const nestedHost = document.createElement('article');
+ root.appendChild(nestedHost);
+ nestedHost.attachShadow({mode: 'open'}).append('nested');
+ }
+ }
+ const frame = document.createElement('iframe');
+ frame.style.cssText = 'display:block;width:320px;height:120px;border:0';
+ document.body.appendChild(frame);
+ const child = frame.contentDocument;
+ child.documentElement.style.cssText = 'margin:0;background:rgb(240,245,250)';
+ child.body.style.cssText = 'margin:0';
+ for (let index = 0; index < 24; index += 1) {
+ const host = child.createElement('section');
+ host.style.cssText = 'display:inline-block;width:8px;height:8px';
+ child.body.appendChild(host);
+ host.attachShadow({mode: index % 2 === 0 ? 'open' : 'closed'}).append('child');
+ }
+})()
+""",
+ )
+
+ loop = asyncio.get_running_loop()
+ started = loop.time()
+ first_png, _ = await _capture(client, session_id)
+ first_elapsed_ms = round((loop.time() - started) * 1000)
+ started = loop.time()
+ second_png, _ = await _capture(client, session_id)
+ second_elapsed_ms = round((loop.time() - started) * 1000)
+ if second_png != first_png:
+ raise SmokeError("stable Shadow Root universe changed consecutive screenshot pixels")
+ decoded = decode_png(second_png)
+ assert_equal(
+ (decoded.width, decoded.height),
+ (800, 600),
+ "Shadow Root universe screenshot dimensions",
+ )
+ record(
+ results,
+ "layout_shadow_tree_scope_universe",
+ {
+ "documentShadowRoots": 111,
+ "childDocumentShadowRoots": 24,
+ "openAndClosedRoots": True,
+ "stableConsecutivePixels": True,
+ "firstCaptureMs": first_elapsed_ms,
+ "secondCaptureMs": second_elapsed_ms,
+ },
+ )
+
+
async def run_layout_screenshot_group(
endpoint: str,
fixture: str,
@@ -575,6 +631,7 @@ async def run_layout_screenshot_group(
)
if is_moli:
await _run_moli_screencast(client, session_id, results)
+ await _run_moli_tree_scope_universe_capture(client, session_id, results)
finally:
if target_id is not None:
try:
diff --git a/moli-cdp-smoke/moli_cdp_smoke/runner.py b/moli-cdp-smoke/moli_cdp_smoke/runner.py
index ff261b89b..5c2301c17 100644
--- a/moli-cdp-smoke/moli_cdp_smoke/runner.py
+++ b/moli-cdp-smoke/moli_cdp_smoke/runner.py
@@ -125,7 +125,7 @@ RAW_GROUPS: tuple[SmokeGroup, ...] = (
),
SmokeGroup(
"layout-screenshot",
- "Raw viewport PNG plus uncached 1 FPS JPEG screencast, ACK, mutation, and default-Mock boundaries.",
+ "Raw viewport PNG, stable Shadow/iframe TreeScopes, generation-gated 1 FPS JPEG screencast, ACK, mutation, and default-Mock boundaries.",
"raw",
run_layout_screenshot_group,
),
diff --git a/moli-core/src/page/mod.rs b/moli-core/src/page/mod.rs
index 79d3b7294..2846d8317 100644
--- a/moli-core/src/page/mod.rs
+++ b/moli-core/src/page/mod.rs
@@ -127,8 +127,8 @@ pub use moli_renderer_v8::{
RendererServiceWorkerTargetInfo, RendererServiceWorkerVersionStatus,
RendererSetDocumentContentResult, RendererSharedWorkerConsoleMessage,
RendererSharedWorkerTargetEvent, RendererSharedWorkerTargetInfo, RendererSyntheticResponseBody,
- RendererTextSearchMatch, RendererTouchPoint, RendererWindowDocumentSource,
- RuntimeConsoleMessageSnapshot,
+ RendererTextSearchMatch, RendererTouchPoint, RendererVisualStateToken,
+ RendererWindowDocumentSource, RuntimeConsoleMessageSnapshot,
};
pub use moli_renderer_v8::{
RendererAppManifest, RendererAppManifestDisplayMode, RendererAppManifestError,
diff --git a/moli-protocol-server/src/cdp_scheduler.rs b/moli-protocol-server/src/cdp_scheduler.rs
index f6418d220..56ba8e1b5 100644
--- a/moli-protocol-server/src/cdp_scheduler.rs
+++ b/moli-protocol-server/src/cdp_scheduler.rs
@@ -5,6 +5,7 @@ use std::{
};
use moli_cookie_jar::StoredCookie;
+use moli_core::page::RendererVisualStateToken;
use moli_core::{
RendererOutputTransportMessage, page::RendererDocumentLifecycleMilestone,
runtime::NavigationRuntimeConfig,
@@ -134,12 +135,14 @@ struct PageScreencastSchedule {
registration: PageScreencastRegistration,
interval: Duration,
next_due_at: TokioInstant,
+ known_visual_state: Option<RendererVisualStateToken>,
}
pub(crate) struct ScheduledPageScreencastFrame {
event: BackgroundProtocolEvent,
session_id: Option<String>,
generation: i32,
+ visual_state: RendererVisualStateToken,
}
fn page_screencast_interval(every_nth_frame: u32) -> Duration {
@@ -497,6 +500,7 @@ impl CdpScheduler {
registration,
interval,
next_due_at: now,
+ known_visual_state: None,
},
);
}
@@ -553,10 +557,16 @@ impl CdpScheduler {
.page_screencasts
.iter()
.filter(|(_, schedule)| schedule.next_due_at <= now)
- .map(|(session_id, schedule)| (session_id.clone(), schedule.registration.clone()))
+ .map(|(session_id, schedule)| {
+ (
+ session_id.clone(),
+ schedule.registration.clone(),
+ schedule.known_visual_state.clone(),
+ )
+ })
.collect::<Vec<_>>();
let mut pending = Vec::with_capacity(due.len());
- for (session_id, registration) in due {
+ for (session_id, registration, known_visual_state) in due {
match self.conn.page_screencast_subscription_status(&registration) {
PageScreencastSubscriptionStatus::Inactive => {
if self.page_screencast_schedule_matches(&session_id, registration.generation())
@@ -567,7 +577,10 @@ impl CdpScheduler {
PageScreencastSubscriptionStatus::CaptureInProgress
| PageScreencastSubscriptionStatus::AwaitingAck => {}
PageScreencastSubscriptionStatus::Ready => {
- match self.conn.start_page_screencast_frame_capture(&registration) {
+ match self
+ .conn
+ .start_page_screencast_frame_capture(&registration, known_visual_state)
+ {
PageScreencastCaptureStart::Pending(capture) => pending.push(capture),
PageScreencastCaptureStart::Retry => {
if let Some(schedule) = self.page_screencasts.get_mut(&session_id)
@@ -606,11 +619,23 @@ impl CdpScheduler {
return None;
}
match completion {
- PageScreencastCaptureCompletion::Frame(event) => Some(ScheduledPageScreencastFrame {
+ PageScreencastCaptureCompletion::Frame {
+ event,
+ visual_state,
+ } => Some(ScheduledPageScreencastFrame {
event,
session_id,
generation,
+ visual_state,
}),
+ PageScreencastCaptureCompletion::Unchanged => {
+ let schedule = self
+ .page_screencasts
+ .get_mut(&session_id)
+ .expect("matching screencast schedule must exist");
+ schedule.next_due_at = next_page_screencast_deadline(now, schedule.interval);
+ None
+ }
PageScreencastCaptureCompletion::Retry => {
let schedule = self
.page_screencasts
@@ -631,11 +656,13 @@ impl CdpScheduler {
&mut self,
session_id: &Option<String>,
generation: i32,
+ visual_state: RendererVisualStateToken,
now: TokioInstant,
) {
if let Some(schedule) = self.page_screencasts.get_mut(session_id)
&& schedule.registration.generation() == generation
{
+ schedule.known_visual_state = Some(visual_state);
schedule.next_due_at = next_page_screencast_deadline(now, schedule.interval);
}
}
diff --git a/moli-protocol-server/src/cdp_scheduler/actor.rs b/moli-protocol-server/src/cdp_scheduler/actor.rs
index 73f4bbc41..e99d34a2e 100644
--- a/moli-protocol-server/src/cdp_scheduler/actor.rs
+++ b/moli-protocol-server/src/cdp_scheduler/actor.rs
@@ -312,6 +312,7 @@ async fn run_cdp_scheduler_actor(
event,
session_id,
generation,
+ visual_state,
} = frame;
let output = route_top_level_background_event(
&mut adapter_scheduler,
@@ -331,6 +332,7 @@ async fn run_cdp_scheduler_actor(
scheduler.note_page_screencast_frame_emitted(
&session_id,
generation,
+ visual_state,
TokioInstant::now(),
);
}
diff --git a/moli-protocol/src/domains/page.rs b/moli-protocol/src/domains/page.rs
index b1c23a361..ac84a234d 100644
--- a/moli-protocol/src/domains/page.rs
+++ b/moli-protocol/src/domains/page.rs
@@ -26,7 +26,7 @@ use moli_core::page::{
RendererDocumentSourcedTopLevelLocationNavigation, RendererLayoutMetrics,
RendererPendingTopLevelHistoryTraversal, RendererPendingWindowOpenEvent,
RendererScreenshotClip, RendererScreenshotFormat, RendererScreenshotPurpose,
- RendererScreenshotRegion, RendererSetDocumentContentResult,
+ RendererScreenshotRegion, RendererSetDocumentContentResult, RendererVisualStateToken,
};
use moli_core::{RendererDocumentTitleChanged, RendererRuntimeCommandCausalIdentity};
use serde::Deserialize;
@@ -1769,7 +1769,11 @@ impl PendingPageScreencastCapture {
}
pub enum PageScreencastCaptureCompletion {
- Frame(BackgroundProtocolEvent),
+ Frame {
+ event: BackgroundProtocolEvent,
+ visual_state: RendererVisualStateToken,
+ },
+ Unchanged,
Retry,
Stale,
}
@@ -1878,6 +1882,7 @@ impl CdpConnection {
pub fn start_page_screencast_frame_capture(
&mut self,
registration: &PageScreencastRegistration,
+ known_visual_state: Option<RendererVisualStateToken>,
) -> PageScreencastCaptureStart {
let session_id = registration.session_id().map(str::to_owned);
let generation = registration.generation;
@@ -1909,6 +1914,7 @@ impl CdpConnection {
optimize_for_speed: true,
max_width: config.max_width(),
max_height: config.max_height(),
+ known_visual_state,
};
let pending = match conn.loaded_page_mut_for_protocol_access(session_id_ref) {
Ok(page) => match page.start_capture_screenshot_with_request(request) {
@@ -1974,6 +1980,17 @@ impl CdpConnection {
};
match page.finish_capture_screenshot(*completion) {
Ok(RendererCaptureScreenshotReply::Captured(image)) => image,
+ Ok(RendererCaptureScreenshotReply::ScreencastUnchanged) => {
+ if conn.complete_page_screencast_capture_for_session_owner(
+ session_id_ref,
+ generation,
+ false,
+ ) != Some(true)
+ {
+ return PageScreencastCaptureCompletion::Stale;
+ }
+ return PageScreencastCaptureCompletion::Unchanged;
+ }
Ok(
RendererCaptureScreenshotReply::LayoutDisabled
| RendererCaptureScreenshotReply::NoDocument,
@@ -1998,6 +2015,19 @@ impl CdpConnection {
}
};
+ let Some(visual_state) = image.visual_state else {
+ tracing::debug!(
+ generation,
+ ?session_id,
+ "screencast capture returned a frame without visual-state metadata"
+ );
+ let _ = conn.complete_page_screencast_capture_for_session_owner(
+ session_id_ref,
+ generation,
+ false,
+ );
+ return PageScreencastCaptureCompletion::Retry;
+ };
if conn.complete_page_screencast_capture_for_session_owner(session_id_ref, generation, true)
!= Some(true)
{
@@ -2015,12 +2045,15 @@ impl CdpConnection {
.unwrap_or_default()
.as_secs_f64(),
};
- PageScreencastCaptureCompletion::Frame(BackgroundProtocolEvent::page_screencast_frame(
- session_id_ref,
- BASE64_STANDARD.encode(&image.bytes),
- metadata,
- generation,
- ))
+ PageScreencastCaptureCompletion::Frame {
+ event: BackgroundProtocolEvent::page_screencast_frame(
+ session_id_ref,
+ BASE64_STANDARD.encode(&image.bytes),
+ metadata,
+ generation,
+ ),
+ visual_state,
+ }
}
}
@@ -6702,6 +6735,7 @@ fn start_devtools_capture_screenshot_command(
optimize_for_speed: command.optimize_for_speed,
max_width: None,
max_height: None,
+ known_visual_state: None,
};
match page.start_capture_screenshot_with_request(request) {
Ok(pending) => PageCommandTaskStep::Pending(PendingPageCommandDispatch {
@@ -6765,6 +6799,7 @@ fn start_devtools_print_to_pdf_command(
optimize_for_speed: false,
max_width: None,
max_height: None,
+ known_visual_state: None,
};
match page.start_capture_screenshot_with_request(request) {
Ok(pending) => PageCommandTaskStep::Pending(PendingPageCommandDispatch {
@@ -7788,6 +7823,12 @@ async fn complete_pending_page_command_inner(
Ok(RendererCaptureScreenshotReply::NoDocument) => {
CommandOutputPlan::error(-32000, "NoDocumentLoaded")
}
+ Ok(RendererCaptureScreenshotReply::ScreencastUnchanged) => {
+ CommandOutputPlan::error(
+ -32000,
+ "Screenshot capture returned an invalid screencast-only reply",
+ )
+ }
Err(error) => CommandOutputPlan::error(
-32000,
format!("Failed to capture page screenshot: {error}"),
@@ -7830,6 +7871,12 @@ async fn complete_pending_page_command_inner(
"NoDocumentLoaded",
));
}
+ Ok(RendererCaptureScreenshotReply::ScreencastUnchanged) => {
+ return PageCommandTaskStep::Complete(CommandOutputPlan::error(
+ -32000,
+ "PDF capture returned an invalid screencast-only reply",
+ ));
+ }
Err(error) => {
return PageCommandTaskStep::Complete(CommandOutputPlan::error(
-32000,
diff --git a/moli-protocol/src/domains/page/tests/lifecycle.rs b/moli-protocol/src/domains/page/tests/lifecycle.rs
index 7771a1e8b..390f8137d 100644
--- a/moli-protocol/src/domains/page/tests/lifecycle.rs
+++ b/moli-protocol/src/domains/page/tests/lifecycle.rs
@@ -3783,8 +3783,9 @@ async fn screencast_capture_materializes_jpeg_frame_and_ack_budget() {
ctx.conn.page_screencast_subscription_status(&registration),
PageScreencastSubscriptionStatus::Ready
);
- let PageScreencastCaptureStart::Pending(capture) =
- ctx.conn.start_page_screencast_frame_capture(&registration)
+ let PageScreencastCaptureStart::Pending(capture) = ctx
+ .conn
+ .start_page_screencast_frame_capture(&registration, None)
else {
panic!("loaded screencast should start an async renderer capture");
};
@@ -3793,7 +3794,10 @@ async fn screencast_capture_materializes_jpeg_frame_and_ack_budget() {
PageScreencastSubscriptionStatus::CaptureInProgress
);
- let PageScreencastCaptureCompletion::Frame(frame) = ctx
+ let PageScreencastCaptureCompletion::Frame {
+ event: frame,
+ visual_state,
+ } = ctx
.conn
.complete_page_screencast_frame_capture(capture.wait().await)
else {
@@ -3835,6 +3839,31 @@ async fn screencast_capture_materializes_jpeg_frame_and_ack_budget() {
ctx.conn.page_screencast_subscription_status(&registration),
PageScreencastSubscriptionStatus::Ready
);
+
+ let PageScreencastCaptureStart::Pending(clean_capture) = ctx
+ .conn
+ .start_page_screencast_frame_capture(&registration, Some(visual_state))
+ else {
+ panic!("an acknowledged subscription should poll its visual state");
+ };
+ assert!(matches!(
+ ctx.conn
+ .complete_page_screencast_frame_capture(clean_capture.wait().await),
+ PageScreencastCaptureCompletion::Unchanged
+ ));
+ assert_eq!(
+ ctx.conn.page_screencast_subscription_status(&registration),
+ PageScreencastSubscriptionStatus::Ready,
+ "an unchanged poll must neither emit a frame nor wait for an ACK",
+ );
+ assert_eq!(
+ ctx.conn
+ .acknowledge_page_screencast_frame_for_session_owner(
+ Some("SID-screencast-frame"),
+ registration.generation(),
+ ),
+ Some(false),
+ );
}
#[tokio::test(flavor = "multi_thread")]
diff --git a/moli-renderer-v8/src/lib.rs b/moli-renderer-v8/src/lib.rs
index 0de98edd2..f1c214939 100644
--- a/moli-renderer-v8/src/lib.rs
+++ b/moli-renderer-v8/src/lib.rs
@@ -302,8 +302,8 @@ pub use runtime::{
RendererSharedWorkerConsoleMessage, RendererSharedWorkerTargetEvent,
RendererSharedWorkerTargetInfo, RendererStyleSheetHeader, RendererStyleSheetInventoryUpdate,
RendererStyleSheetPayload, RendererSyntheticResponseBody, RendererTextSearchMatch,
- RendererTouchPoint, RendererWindowDocumentSource, RuntimeConsoleMessageSnapshot,
- renderer_output_transport_channel,
+ RendererTouchPoint, RendererVisualStateToken, RendererWindowDocumentSource,
+ RuntimeConsoleMessageSnapshot, renderer_output_transport_channel,
};
pub use service_worker_runtime::{
SharedServiceWorkerResourceStore, new_shared_json_service_worker_resource_store,
diff --git a/moli-renderer-v8/src/native_bridge/context_host/canvas_resources.rs b/moli-renderer-v8/src/native_bridge/context_host/canvas_resources.rs
index 59f39d56b..8688496db 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/canvas_resources.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/canvas_resources.rs
@@ -8,6 +8,7 @@ const MAX_RETAINED_CANVAS_PAINT_BYTES: usize = 256 * 1024 * 1024;
pub(super) struct CanvasResourceStore {
pixels_by_element: HashMap<DomHandle, Arc<moli_image::RgbaImage>>,
retained_bytes: usize,
+ paint_generation: u64,
}
impl CanvasResourceStore {
@@ -31,6 +32,7 @@ impl CanvasResourceStore {
}
self.pixels_by_element.insert(element, Arc::new(pixels));
self.retained_bytes = next_retained_bytes;
+ self.paint_generation = self.paint_generation.saturating_add(1);
true
}
@@ -39,6 +41,7 @@ impl CanvasResourceStore {
return false;
};
self.retained_bytes = self.retained_bytes.saturating_sub(pixels.byte_len());
+ self.paint_generation = self.paint_generation.saturating_add(1);
true
}
@@ -49,6 +52,10 @@ impl CanvasResourceStore {
fn elements(&self) -> impl Iterator<Item = DomHandle> + '_ {
self.pixels_by_element.keys().copied()
}
+
+ const fn paint_generation(&self) -> u64 {
+ self.paint_generation
+ }
}
impl super::JsContextHost {
@@ -79,6 +86,10 @@ impl super::JsContextHost {
self.canvas_resources.get(element)
}
+ pub(in crate::native_bridge::context_host) fn canvas_paint_generation(&self) -> u64 {
+ self.canvas_resources.paint_generation()
+ }
+
pub(in crate::native_bridge::context_host) fn retire_canvas_resources_for_document(
&mut self,
document: DomHandle,
diff --git a/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs
index 15576510e..bbe683b55 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs
@@ -1473,6 +1473,21 @@ impl JsContextHost {
.computed_cache_generation_for_document_for_test(document)
}
+ #[cfg(debug_assertions)]
+ pub(crate) fn computed_style_read_invariant_state(
+ &self,
+ document: DomHandle,
+ ) -> (u64, u64, u64) {
+ let (source_set_generation, retained_style_system_generation) = self
+ .style_engine
+ .computed_style_read_invariant_state(document);
+ (
+ self.dom_host().dom_version(),
+ source_set_generation,
+ retained_style_system_generation,
+ )
+ }
+
#[cfg(test)]
pub(crate) fn note_stylo_computed_style_input_build_for_test(&self) {
self.stylo_computed_style_input_builds.set(
diff --git a/moli-renderer-v8/src/native_bridge/context_host/image_resources/css.rs b/moli-renderer-v8/src/native_bridge/context_host/image_resources/css.rs
index d88743dba..7a86ad42c 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/image_resources/css.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/image_resources/css.rs
@@ -1,4 +1,10 @@
-use std::{collections::HashMap, sync::Arc};
+use std::{
+ collections::HashMap,
+ sync::{
+ Arc,
+ atomic::{AtomicU64, Ordering},
+ },
+};
use parking_lot::Mutex;
@@ -47,6 +53,7 @@ struct CssImageResourceKey {
pub(super) struct CssImageResourceStore {
inner: Arc<Mutex<CssImageResourceStoreInner>>,
ready_by_request: ReadyImageResourceIndex,
+ paint_generation: Arc<AtomicU64>,
#[cfg(test)]
completion_notify: Arc<tokio::sync::Notify>,
}
@@ -74,6 +81,7 @@ impl CssImageResourceStore {
Self {
inner: Arc::new(Mutex::new(CssImageResourceStoreInner::default())),
ready_by_request,
+ paint_generation: Arc::new(AtomicU64::new(0)),
#[cfg(test)]
completion_notify: Arc::new(tokio::sync::Notify::new()),
}
@@ -176,6 +184,7 @@ impl CssImageResourceStore {
self.ready_by_request
.insert(identity.request_key.clone(), &resource);
slot.state = CssImageResourceState::Ready(resource);
+ self.paint_generation.fetch_add(1, Ordering::AcqRel);
#[cfg(test)]
self.completion_notify.notify_waiters();
true
@@ -193,6 +202,7 @@ impl CssImageResourceStore {
return false;
}
slot.state = CssImageResourceState::Failed;
+ self.paint_generation.fetch_add(1, Ordering::AcqRel);
#[cfg(test)]
self.completion_notify.notify_waiters();
true
@@ -232,11 +242,18 @@ impl CssImageResourceStore {
.slots
.retain(|key, _| key.document_handle != document_handle);
let removed = before - inner.slots.len();
+ if removed != 0 {
+ self.paint_generation.fetch_add(1, Ordering::AcqRel);
+ }
drop(inner);
self.ready_by_request.prune_dead();
removed
}
+ pub(super) fn paint_generation(&self) -> u64 {
+ self.paint_generation.load(Ordering::Acquire)
+ }
+
#[cfg(test)]
pub(super) fn observability_for_test(&self) -> (usize, usize, usize, usize, Vec<String>) {
let inner = self.inner.lock();
diff --git a/moli-renderer-v8/src/native_bridge/context_host/image_resources/mod.rs b/moli-renderer-v8/src/native_bridge/context_host/image_resources/mod.rs
index 2c9e0cb41..e5e76b282 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/image_resources/mod.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/image_resources/mod.rs
@@ -97,6 +97,13 @@ impl super::PendingImageLoadEvent {
}
impl super::JsContextHost {
+ pub(in crate::native_bridge::context_host) fn image_paint_generations(&self) -> (u64, u64) {
+ (
+ self.image_resources.paint_generation(),
+ self.image_resources.css.paint_generation(),
+ )
+ }
+
pub(super) fn begin_pending_image_resource(
&mut self,
element: DomHandle,
diff --git a/moli-renderer-v8/src/native_bridge/context_host/image_resources/state.rs b/moli-renderer-v8/src/native_bridge/context_host/image_resources/state.rs
index 36285ad08..ea884ec1f 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/image_resources/state.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/image_resources/state.rs
@@ -29,6 +29,7 @@ pub(in crate::native_bridge::context_host) struct ImageResourceStore {
pub(super) css: CssImageResourceStore,
pub(super) scanned: ScannedImagePreloadStore,
pub(super) decode: ImageDecodeCoordinator,
+ paint_generation: u64,
}
struct ImageResourceSlot {
@@ -104,6 +105,7 @@ impl Default for ImageResourceStore {
scanned: ScannedImagePreloadStore::new(ready_by_request.clone(), decode.clone()),
ready_by_request,
decode,
+ paint_generation: 0,
}
}
}
@@ -119,6 +121,7 @@ impl ImageResourceStore {
scanned_preload: None,
},
);
+ self.paint_generation = self.paint_generation.saturating_add(1);
}
pub(super) fn identity(&self, element: DomHandle) -> Option<&ImageResourceRequestIdentity> {
@@ -210,6 +213,7 @@ impl ImageResourceStore {
ImageResourceState::Pending => {
slot.state = ImageResourceState::Ready(resource);
slot.scanned_preload = None;
+ self.paint_generation = self.paint_generation.saturating_add(1);
true
}
ImageResourceState::DecodeQueued(_) | ImageResourceState::Failed => false,
@@ -241,6 +245,7 @@ impl ImageResourceStore {
.insert(identity.request_key.clone(), &resource);
slot.state = ImageResourceState::Ready(resource);
slot.scanned_preload = None;
+ self.paint_generation = self.paint_generation.saturating_add(1);
true
}
@@ -253,6 +258,7 @@ impl ImageResourceStore {
}
slot.state = ImageResourceState::Failed;
slot.scanned_preload = None;
+ self.paint_generation = self.paint_generation.saturating_add(1);
true
}
@@ -290,6 +296,9 @@ impl ImageResourceStore {
pub(super) fn retire_element(&mut self, element: DomHandle) -> bool {
let removed = self.slots.remove(&element).is_some();
+ if removed {
+ self.paint_generation = self.paint_generation.saturating_add(1);
+ }
self.prune_dead_ready_requests();
removed
}
@@ -299,12 +308,20 @@ impl ImageResourceStore {
self.slots
.retain(|_, slot| slot.identity.document_handle != document);
self.prune_dead_ready_requests();
- before - self.slots.len()
+ let removed = before - self.slots.len();
+ if removed != 0 {
+ self.paint_generation = self.paint_generation.saturating_add(1);
+ }
+ removed
}
fn prune_dead_ready_requests(&mut self) {
self.ready_by_request.prune_dead();
}
+
+ pub(super) const fn paint_generation(&self) -> u64 {
+ self.paint_generation
+ }
}
pub(super) fn intrinsic_dimensions(resource: &ReadyImageResource) -> (f32, f32) {
diff --git a/moli-renderer-v8/src/native_bridge/context_host/layout.rs b/moli-renderer-v8/src/native_bridge/context_host/layout.rs
index cef5ad8aa..5e8929991 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/layout.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/layout.rs
@@ -56,6 +56,88 @@ impl JsContextHost {
self.layout_policy
}
+ fn css_image_discovery_stamp(&self) -> super::layout_state::CssImageDiscoveryStamp {
+ super::layout_state::CssImageDiscoveryStamp::new(
+ self.dom_host().dom_version(),
+ self.style_engine
+ .computed_style_observation_generations(self.active_layout_document_handles()),
+ self.style_viewport(),
+ )
+ }
+
+ pub(crate) fn active_layout_document_handles(&self) -> Vec<DomHandle> {
+ let mut documents = vec![self.document_handle()];
+ documents.extend(
+ self.child_browsing_context_handles_in_document_order()
+ .into_iter()
+ .filter(|frame| self.child_browsing_context_host_is_active(*frame))
+ .filter_map(|frame| self.child_browsing_context_document_handle(frame)),
+ );
+ documents.sort_by_key(|document| document.index());
+ documents.dedup();
+ documents
+ }
+
+ pub(crate) fn css_image_discovery_needed_for_paint(&self) -> bool {
+ let stamp = self.css_image_discovery_stamp();
+ !self
+ .document_layout_state
+ .borrow()
+ .css_image_discovery_is_current(stamp)
+ }
+
+ pub(crate) fn publish_css_image_discovery_for_paint(&mut self) {
+ let stamp = self.css_image_discovery_stamp();
+ self.document_layout_state
+ .get_mut()
+ .publish_css_image_discovery(stamp);
+ }
+
+ pub(crate) fn paint_resource_generations(
+ &self,
+ ) -> super::layout_state::PaintResourceGenerations {
+ let (html_images, css_images) = self.image_paint_generations();
+ super::layout_state::PaintResourceGenerations {
+ html_images,
+ css_images,
+ canvas: self.canvas_paint_generation(),
+ }
+ }
+
+ pub(crate) fn visual_state_generation(&self) -> u64 {
+ self.document_layout_state
+ .borrow()
+ .visual_state_generation()
+ }
+
+ pub(crate) fn visual_state_token(
+ &self,
+ document: crate::runtime::RendererDocumentLifecycleIdentity,
+ viewport: moli_layout::PaintViewport,
+ ) -> crate::runtime::RendererVisualStateToken {
+ let resources = self.paint_resource_generations();
+ crate::runtime::RendererVisualStateToken::new(
+ document,
+ self.dom_host().dom_version(),
+ self.style_engine
+ .computed_style_observation_generations(self.active_layout_document_handles()),
+ self.visual_state_generation(),
+ (
+ resources.html_images,
+ resources.css_images,
+ resources.canvas,
+ ),
+ viewport,
+ )
+ }
+
+ #[cfg(test)]
+ pub(crate) fn css_image_discovery_count_for_test(&self) -> u64 {
+ self.document_layout_state
+ .borrow()
+ .css_image_discovery_count()
+ }
+
pub(crate) fn layout_document_for_source(&self, source: DomHandle) -> Option<DomHandle> {
self.dom_host().owner_document_handle(source)
}
diff --git a/moli-renderer-v8/src/native_bridge/context_host/layout_state.rs b/moli-renderer-v8/src/native_bridge/context_host/layout_state.rs
index 43c4f4953..8a58e53b4 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/layout_state.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/layout_state.rs
@@ -7,8 +7,37 @@ use crate::{
css_resource_urls::{CompletedStylesheetWebFont, StylesheetLoadBlockingResource},
document_runtime::DomHandle,
script_vm::web_fonts::{DocumentWebFontCompletion, DocumentWebFontState},
+ style_engine::StyleViewport,
};
+#[derive(Clone, Debug, PartialEq)]
+pub(super) struct CssImageDiscoveryStamp {
+ dom_version: u64,
+ style_generations: Vec<(DomHandle, u64, u64, u64)>,
+ viewport: StyleViewport,
+}
+
+impl CssImageDiscoveryStamp {
+ pub(super) fn new(
+ dom_version: u64,
+ style_generations: Vec<(DomHandle, u64, u64, u64)>,
+ viewport: StyleViewport,
+ ) -> Self {
+ Self {
+ dom_version,
+ style_generations,
+ viewport,
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) struct PaintResourceGenerations {
+ pub(super) html_images: u64,
+ pub(super) css_images: u64,
+ pub(super) canvas: u64,
+}
+
/// Layout-facing state whose lifetime is bounded by exactly one main Document.
///
/// `ScriptVm` outlives `document.open()`, so the main-document owner
@@ -25,6 +54,10 @@ pub(super) struct DocumentLayoutState {
embedded_document_services: HashMap<DomHandle, DocumentLayoutServices>,
web_fonts: DocumentWebFontState,
web_font_sources_dirty: bool,
+ css_image_discovery_stamp: Option<CssImageDiscoveryStamp>,
+ #[cfg(test)]
+ css_image_discovery_count: u64,
+ visual_state_generation: u64,
latest_layout: LatestLayoutTreeCache,
/// Last used content viewport published by each live iframe owner's
/// parent layout. Blink keeps the equivalent size on LocalFrameView; it is
@@ -40,6 +73,10 @@ impl Default for DocumentLayoutState {
embedded_document_services: HashMap::new(),
web_fonts: DocumentWebFontState::default(),
web_font_sources_dirty: true,
+ css_image_discovery_stamp: None,
+ #[cfg(test)]
+ css_image_discovery_count: 0,
+ visual_state_generation: 0,
latest_layout: LatestLayoutTreeCache::default(),
frame_viewports: HashMap::new(),
}
@@ -55,6 +92,31 @@ impl DocumentLayoutState {
std::mem::take(&mut self.web_font_sources_dirty)
}
+ pub(super) fn css_image_discovery_is_current(&self, stamp: CssImageDiscoveryStamp) -> bool {
+ self.css_image_discovery_stamp == Some(stamp)
+ }
+
+ pub(super) fn publish_css_image_discovery(&mut self, stamp: CssImageDiscoveryStamp) {
+ self.css_image_discovery_stamp = Some(stamp);
+ #[cfg(test)]
+ {
+ self.css_image_discovery_count = self.css_image_discovery_count.saturating_add(1);
+ }
+ }
+
+ #[cfg(test)]
+ pub(super) const fn css_image_discovery_count(&self) -> u64 {
+ self.css_image_discovery_count
+ }
+
+ pub(super) const fn visual_state_generation(&self) -> u64 {
+ self.visual_state_generation
+ }
+
+ pub(super) fn mark_visual_state_dirty(&mut self) {
+ self.visual_state_generation = self.visual_state_generation.saturating_add(1);
+ }
+
pub(crate) fn with_services_for_document<T>(
&mut self,
document: DomHandle,
@@ -112,6 +174,7 @@ impl DocumentLayoutState {
pub(super) fn clear_latest_layout(&mut self) {
self.latest_layout.clear();
+ self.mark_visual_state_dirty();
}
pub(super) fn frame_viewport(&self, frame: DomHandle) -> Option<LayoutViewport> {
@@ -167,7 +230,11 @@ impl DocumentLayoutState {
&mut self,
terminal: CompletedStylesheetWebFont,
) -> DocumentWebFontCompletion {
- self.web_fonts.complete(terminal, &mut self.services)
+ let completion = self.web_fonts.complete(terminal, &mut self.services);
+ if !matches!(&completion, DocumentWebFontCompletion::Stale) {
+ self.mark_visual_state_dirty();
+ }
+ completion
}
#[cfg(test)]
diff --git a/moli-renderer-v8/src/native_bridge/element/styles/declaration/values.rs b/moli-renderer-v8/src/native_bridge/element/styles/declaration/values.rs
index 571e1df9e..145dece24 100644
--- a/moli-renderer-v8/src/native_bridge/element/styles/declaration/values.rs
+++ b/moli-renderer-v8/src/native_bridge/element/styles/declaration/values.rs
@@ -84,14 +84,22 @@ impl StyleComputationContext {
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
struct StyloComputedStyleInputKey {
source_document: Option<DomHandle>,
- required_shadow_roots: Vec<(DomHandle, bool)>,
+ tree_scope_roots: Vec<DomHandle>,
+}
+
+#[cfg(debug_assertions)]
+#[derive(Clone, Copy)]
+struct ComputedStyleReadInvariant {
+ dom_version: u64,
+ source_set_generation: u64,
+ retained_style_system_generation: u64,
}
/// Prepared style inputs shared by one synchronous rendered-state observation.
///
/// The scope never crosses a JavaScript callback, so DOM and stylesheet
-/// mutations cannot occur between reads. Distinct document and shadow-tree
-/// contexts still receive distinct immutable input snapshots.
+/// mutations cannot occur between reads. Each Document receives one immutable
+/// input snapshot containing its complete connected TreeScope universe.
pub(crate) struct ComputedStyleReadScope<'a> {
runtime: &'a JsContextHost,
context: StyleComputationContext,
@@ -105,6 +113,8 @@ pub(crate) struct ComputedStyleReadScope<'a> {
StyloComputedStyleInputKey,
Rc<StyloPreparedComputedStyleInputs>,
)>,
+ #[cfg(debug_assertions)]
+ invariants: Vec<(DomHandle, ComputedStyleReadInvariant)>,
}
impl<'a> ComputedStyleReadScope<'a> {
@@ -142,6 +152,8 @@ impl<'a> ComputedStyleReadScope<'a> {
additional_drained_documents: Vec::new(),
primary_input: None,
additional_inputs: Vec::new(),
+ #[cfg(debug_assertions)]
+ invariants: Vec::new(),
}
}
@@ -165,8 +177,8 @@ impl<'a> ComputedStyleReadScope<'a> {
);
}
- let input_key = stylo_computed_style_input_key(self.runtime, handle);
- let prepared_inputs = self.prepared_inputs(input_key);
+ let source_document = stylesheet_source_document_for_handle(self.runtime, handle);
+ let prepared_inputs = self.prepared_inputs(source_document);
let stylo_style = self
.runtime
.computed_style_snapshot_from_stylo_with_prepared_inputs(
@@ -174,6 +186,8 @@ impl<'a> ComputedStyleReadScope<'a> {
prepared_inputs.as_ref(),
read_document,
);
+ #[cfg(debug_assertions)]
+ self.verify_stable_style_world_after_read(source_document);
ComputedStyleRead {
runtime: self.runtime,
handle,
@@ -185,21 +199,22 @@ impl<'a> ComputedStyleReadScope<'a> {
fn prepared_inputs(
&mut self,
- input_key: StyloComputedStyleInputKey,
+ source_document: Option<DomHandle>,
) -> Rc<StyloPreparedComputedStyleInputs> {
if let Some((prepared_key, inputs)) = self.primary_input.as_ref()
- && prepared_key == &input_key
+ && prepared_key.source_document == source_document
{
return Rc::clone(inputs);
}
if let Some((_, inputs)) = self
.additional_inputs
.iter()
- .find(|(prepared_key, _)| prepared_key == &input_key)
+ .find(|(prepared_key, _)| prepared_key.source_document == source_document)
{
return Rc::clone(inputs);
}
+ let input_key = stylo_computed_style_input_key_for_document(self.runtime, source_document);
let inputs = stylo_prepared_computed_style_inputs_for_observation_scope(
self.runtime,
&input_key,
@@ -212,6 +227,38 @@ impl<'a> ComputedStyleReadScope<'a> {
}
inputs
}
+
+ #[cfg(debug_assertions)]
+ fn verify_stable_style_world_after_read(&mut self, source_document: Option<DomHandle>) {
+ let Some(document) = source_document else {
+ return;
+ };
+ let (dom_version, source_set_generation, retained_style_system_generation) =
+ self.runtime.computed_style_read_invariant_state(document);
+ let current = ComputedStyleReadInvariant {
+ dom_version,
+ source_set_generation,
+ retained_style_system_generation,
+ };
+ let Some((_, previous)) = self
+ .invariants
+ .iter_mut()
+ .find(|(candidate, _)| *candidate == document)
+ else {
+ self.invariants.push((document, current));
+ return;
+ };
+ if previous.dom_version == current.dom_version
+ && previous.source_set_generation == current.source_set_generation
+ {
+ debug_assert_eq!(
+ current.retained_style_system_generation, previous.retained_style_system_generation,
+ "one ComputedStyleReadScope rebuilt the retained style system without a DOM or style-source mutation",
+ );
+ } else {
+ *previous = current;
+ }
+ }
}
impl Drop for ComputedStyleReadScope<'_> {
@@ -1088,44 +1135,6 @@ fn document_scope_stylesheet_sources(
sources
}
-fn shadow_root_ancestors_for_part_exposure(
- runtime: &JsContextHost,
- handle: DomHandle,
-) -> Vec<DomHandle> {
- if runtime.dom_host().get_attribute(handle, "part").is_none() {
- return Vec::new();
- }
- let mut roots = Vec::new();
- let mut current = runtime.dom_host().containing_shadow_root(handle);
- while let Some(root) = current {
- roots.push(root);
- let Some(host) = runtime.dom_host().shadow_root_host(root) else {
- break;
- };
- current = runtime.dom_host().containing_shadow_root(host);
- }
- roots
-}
-
-fn shadow_roots_for_assigned_slot_chain(
- runtime: &JsContextHost,
- handle: DomHandle,
-) -> Vec<DomHandle> {
- let mut roots = Vec::new();
- let mut visited = HashSet::new();
- let mut current = runtime.dom_host().assigned_slot_for_node(handle);
- while let Some(slot) = current {
- if !visited.insert(slot) {
- break;
- }
- if let Some(root) = runtime.dom_host().containing_shadow_root(slot) {
- roots.push(root);
- }
- current = runtime.dom_host().assigned_slot_for_node(slot);
- }
- roots
-}
-
fn shadow_stylesheet_sources(
runtime: &JsContextHost,
root: DomHandle,
@@ -1149,60 +1158,6 @@ fn shadow_stylesheet_sources(
sources
}
-fn push_stylo_computed_style_shadow_root(
- roots: &mut Vec<(DomHandle, bool)>,
- root: DomHandle,
- include_empty: bool,
-) {
- if let Some((_, existing_include_empty)) =
- roots.iter_mut().find(|(existing, _)| *existing == root)
- {
- *existing_include_empty |= include_empty;
- } else {
- roots.push((root, include_empty));
- }
-}
-
-fn stylo_computed_style_required_shadow_roots(
- runtime: &JsContextHost,
- handle: DomHandle,
-) -> Vec<(DomHandle, bool)> {
- let mut roots = Vec::<(DomHandle, bool)>::new();
- if let Some(root) = runtime.dom_host().containing_shadow_root(handle) {
- push_stylo_computed_style_shadow_root(&mut roots, root, true);
- }
- for root in shadow_root_ancestors_for_part_exposure(runtime, handle) {
- push_stylo_computed_style_shadow_root(&mut roots, root, true);
- }
- if let Some(root) = runtime.dom_host().shadow_root_handle(handle) {
- push_stylo_computed_style_shadow_root(&mut roots, root, false);
- }
- for root in shadow_roots_for_assigned_slot_chain(runtime, handle) {
- push_stylo_computed_style_shadow_root(&mut roots, root, false);
- }
- roots
-}
-
-fn stylo_computed_style_input_shadow_roots(
- runtime: &JsContextHost,
- source_document: Option<DomHandle>,
- context: StyleComputationContext,
- required_roots: &[(DomHandle, bool)],
-) -> Vec<(DomHandle, bool)> {
- let mut roots = Vec::new();
- if context.read_document.is_none()
- && let Some(document) = source_document
- {
- for root in connected_shadow_roots_for_document(runtime.dom_host(), document) {
- push_stylo_computed_style_shadow_root(&mut roots, root, false);
- }
- }
- for (root, include_empty) in required_roots {
- push_stylo_computed_style_shadow_root(&mut roots, *root, *include_empty);
- }
- roots
-}
-
fn stylo_computed_style_inputs(
runtime: &JsContextHost,
handle: DomHandle,
@@ -1215,10 +1170,22 @@ fn stylo_computed_style_inputs(
fn stylo_computed_style_input_key(
runtime: &JsContextHost,
handle: DomHandle,
+) -> StyloComputedStyleInputKey {
+ stylo_computed_style_input_key_for_document(
+ runtime,
+ stylesheet_source_document_for_handle(runtime, handle),
+ )
+}
+
+fn stylo_computed_style_input_key_for_document(
+ runtime: &JsContextHost,
+ source_document: Option<DomHandle>,
) -> StyloComputedStyleInputKey {
StyloComputedStyleInputKey {
- source_document: stylesheet_source_document_for_handle(runtime, handle),
- required_shadow_roots: stylo_computed_style_required_shadow_roots(runtime, handle),
+ source_document,
+ tree_scope_roots: source_document
+ .map(|document| connected_shadow_roots_for_document(runtime.dom_host(), document))
+ .unwrap_or_default(),
}
}
@@ -1247,11 +1214,10 @@ fn stylo_prepared_computed_style_inputs_for_observation_scope(
let source_document = key.source_document;
let (script_custom_property_base_url, environment) =
stylo_computed_style_input_environment(runtime, source_document);
- if key.required_shadow_roots.is_empty()
- && let Some(document) = source_document
- {
+ if let Some(document) = source_document {
let cache_key = StyloDocumentComputedStyleInputCacheKey::new(
context.read_document,
+ &key.tree_scope_roots,
runtime.document_url(),
context.viewport,
environment,
@@ -1283,14 +1249,12 @@ fn cache_stylo_computed_style_inputs_after_observation(
context: StyleComputationContext,
inputs: &Rc<StyloPreparedComputedStyleInputs>,
) {
- if !key.required_shadow_roots.is_empty() {
- return;
- }
let Some(document) = key.source_document else {
return;
};
let cache_key = StyloDocumentComputedStyleInputCacheKey::new(
context.read_document,
+ &key.tree_scope_roots,
runtime.document_url(),
context.viewport,
inputs.inputs().environment,
@@ -1339,16 +1303,8 @@ fn stylo_computed_style_inputs_with_environment(
.map(|document| document.quirks_mode())
.unwrap_or(style::context::QuirksMode::NoQuirks),
};
- for (root, include_empty) in stylo_computed_style_input_shadow_roots(
- runtime,
- source_document,
- context,
- &key.required_shadow_roots,
- ) {
+ for root in key.tree_scope_roots.iter().copied() {
let sources = shadow_stylesheet_sources(runtime, root, context);
- if sources.is_empty() && !include_empty {
- continue;
- }
inputs.shadow_stylesheet_sources.push((root, sources));
}
Rc::new(inputs)
@@ -1364,43 +1320,6 @@ fn connected_shadow_roots_for_document(host: &DomHost, document: DomHandle) -> V
roots
}
-#[cfg(test)]
-fn computed_style_related_shadow_roots(host: &DomHost, handle: DomHandle) -> Vec<DomHandle> {
- let mut roots = Vec::new();
- if host.node(handle).is_none() {
- return roots;
- }
-
- if host.containing_shadow_root(handle).is_none() {
- for binding in
- host.snapshot_connected_shadow_root_bindings_related_to_light_tree_handle(handle)
- {
- push_unique_shadow_root(&mut roots, binding.root);
- }
- }
-
- let mut current = Some(handle);
- while let Some(candidate) = current {
- if let Some(root) = host.shadow_root_handle(candidate) {
- push_unique_shadow_root(&mut roots, root);
- }
- let Some(root) = host.containing_shadow_root(candidate) else {
- break;
- };
- push_unique_shadow_root(&mut roots, root);
- current = host.shadow_root_host(root);
- }
- roots.sort_by_key(|root| root.index());
- roots
-}
-
-#[cfg(test)]
-fn push_unique_shadow_root(roots: &mut Vec<DomHandle>, root: DomHandle) {
- if !roots.contains(&root) {
- roots.push(root);
- }
-}
-
fn stylo_computed_style_value(
runtime: &JsContextHost,
handle: DomHandle,
@@ -7778,9 +7697,8 @@ mod tests {
use super::{
KEYFRAME_NESTING_DEPTH_LIMIT, animation_shorthand_names, box_shorthand_component,
collect_custom_functions_from_css, compress_box_shorthand_value,
- computed_style_related_shadow_roots, connected_shadow_roots_for_document,
- custom_function_container_rule_texts, format_css_number,
- keyframe_has_supported_animation_values, keyframe_property_values,
+ connected_shadow_roots_for_document, custom_function_container_rule_texts,
+ format_css_number, keyframe_has_supported_animation_values, keyframe_property_values,
normalize_computed_color_functions, normalize_css_integer_token, normalize_style_value,
simple_var_function_parts,
};
@@ -7813,36 +7731,6 @@ mod tests {
assert_eq!(format_css_number(120.00005), "120.00005");
}
- #[test]
- fn computed_style_related_shadow_roots_excludes_sibling_roots_for_light_target() {
- let mut host = test_host();
- let document = host.document_handle();
- let target = host.create_element("main");
- let related_host = host.create_element("section");
- let sibling_host = host.create_element("aside");
-
- connect_for_test(&mut host, document, target);
- connect_for_test(&mut host, document, related_host);
- connect_for_test(&mut host, document, sibling_host);
-
- let related_root = host
- .attach_shadow_root(related_host, "open")
- .expect("related host should accept shadow root");
- let sibling_root = host
- .attach_shadow_root(sibling_host, "open")
- .expect("sibling host should accept shadow root");
-
- assert_eq!(computed_style_related_shadow_roots(&host, target), vec![]);
- assert_eq!(
- computed_style_related_shadow_roots(&host, related_host),
- vec![related_root]
- );
- assert_eq!(
- computed_style_related_shadow_roots(&host, document),
- vec![related_root, sibling_root]
- );
- }
-
#[test]
fn connected_shadow_roots_for_document_excludes_child_document_roots() {
let mut host = test_host();
@@ -7876,34 +7764,6 @@ mod tests {
);
}
- #[test]
- fn computed_style_related_shadow_roots_keeps_nested_shadow_chain() {
- let mut host = test_host();
- let document = host.document_handle();
- let outer_host = host.create_element("section");
- let inner_host = host.create_element("article");
- let target = host.create_element("span");
- let unrelated_host = host.create_element("aside");
-
- connect_for_test(&mut host, document, outer_host);
- connect_for_test(&mut host, document, unrelated_host);
- let outer_root = host
- .attach_shadow_root(outer_host, "open")
- .expect("outer host should accept shadow root");
- connect_for_test(&mut host, outer_root, inner_host);
- let inner_root = host
- .attach_shadow_root(inner_host, "open")
- .expect("inner host should accept shadow root");
- connect_for_test(&mut host, inner_root, target);
- let unrelated_root = host
- .attach_shadow_root(unrelated_host, "open")
- .expect("unrelated host should accept shadow root");
-
- let roots = computed_style_related_shadow_roots(&host, target);
- assert_eq!(roots, vec![outer_root, inner_root]);
- assert!(!roots.contains(&unrelated_root));
- }
-
#[test]
fn box_shorthand_component_keeps_function_whitespace_internal() {
assert_eq!(
diff --git a/moli-renderer-v8/src/runtime/mod.rs b/moli-renderer-v8/src/runtime/mod.rs
index c566bb898..ed6bae7e1 100644
--- a/moli-renderer-v8/src/runtime/mod.rs
+++ b/moli-renderer-v8/src/runtime/mod.rs
@@ -294,7 +294,7 @@ pub(crate) use self::page_context_cancel::{
};
pub use self::page_screenshot::{
RendererCaptureScreenshotRequest, RendererScreenshotClip, RendererScreenshotFormat,
- RendererScreenshotPurpose, RendererScreenshotRegion,
+ RendererScreenshotPurpose, RendererScreenshotRegion, RendererVisualStateToken,
};
pub(super) use self::page_state::RendererPageEntry;
pub use self::page_state::RendererPageRecord;
diff --git a/moli-renderer-v8/src/runtime/page_screenshot.rs b/moli-renderer-v8/src/runtime/page_screenshot.rs
index 7795de2dc..4a4c1a799 100644
--- a/moli-renderer-v8/src/runtime/page_screenshot.rs
+++ b/moli-renderer-v8/src/runtime/page_screenshot.rs
@@ -1,8 +1,68 @@
use moli_browser_profile::DEFAULT_WINDOW_SURFACE_PROFILE;
use moli_layout::{LayoutRect, PaintCaptureRequest, PaintViewport};
use moli_page_types::LayoutPolicy;
+use std::sync::Arc;
-use super::{PageVm, RendererCaptureScreenshotReply, RendererCapturedScreenshot};
+use super::{
+ PageVm, RendererCaptureScreenshotReply, RendererCapturedScreenshot,
+ RendererDocumentLifecycleIdentity,
+};
+
+/// Opaque identity for the renderer state that can affect one viewport frame.
+///
+/// The token retains generation metadata only. It never owns layout, paint,
+/// raster, or encoded-image data.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct RendererVisualStateToken(Arc<RendererVisualState>);
+
+#[derive(Debug, PartialEq, Eq)]
+struct RendererVisualState {
+ document: RendererDocumentLifecycleIdentity,
+ dom_generation: u64,
+ style_generations: Vec<(u32, u64, u64, u64)>,
+ interaction_generation: u64,
+ html_image_generation: u64,
+ css_image_generation: u64,
+ canvas_generation: u64,
+ viewport_width: u32,
+ viewport_height: u32,
+ device_pixel_ratio_bits: u32,
+}
+
+impl RendererVisualStateToken {
+ pub(crate) fn new(
+ document: RendererDocumentLifecycleIdentity,
+ dom_generation: u64,
+ style_generations: Vec<(crate::document_runtime::DomHandle, u64, u64, u64)>,
+ interaction_generation: u64,
+ resource_generations: (u64, u64, u64),
+ viewport: PaintViewport,
+ ) -> Self {
+ Self(Arc::new(RendererVisualState {
+ document,
+ dom_generation,
+ style_generations: style_generations
+ .into_iter()
+ .map(|(document, source, computed, context)| {
+ (document.index_u32(), source, computed, context)
+ })
+ .collect(),
+ interaction_generation,
+ html_image_generation: resource_generations.0,
+ css_image_generation: resource_generations.1,
+ canvas_generation: resource_generations.2,
+ viewport_width: viewport.css_width,
+ viewport_height: viewport.css_height,
+ device_pixel_ratio_bits: viewport.device_pixel_ratio.to_bits(),
+ }))
+ }
+
+ fn has_same_paint_resources(&self, other: &Self) -> bool {
+ self.0.html_image_generation == other.0.html_image_generation
+ && self.0.css_image_generation == other.0.css_image_generation
+ && self.0.canvas_generation == other.0.canvas_generation
+ }
+}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RendererScreenshotFormat {
@@ -48,6 +108,9 @@ pub struct RendererCaptureScreenshotRequest {
pub optimize_for_speed: bool,
pub max_width: Option<u32>,
pub max_height: Option<u32>,
+ /// Last frame state observed by this screencast subscription. Ordinary
+ /// screenshots leave this empty and always execute a fresh paint pass.
+ pub known_visual_state: Option<RendererVisualStateToken>,
}
impl RendererCaptureScreenshotRequest {
@@ -60,15 +123,17 @@ impl RendererCaptureScreenshotRequest {
optimize_for_speed: false,
max_width: None,
max_height: None,
+ known_visual_state: None,
}
}
}
impl PageVm {
/// Captures the current committed document at one renderer-owner command
- /// turn. The pass-local world, Stylo values, Taffy cache, and paint
- /// resources do not escape; the remaining owned geometry projection is
- /// published as the Document's latest observable layout snapshot.
+ /// turn. The pass-local world, Stylo values, and Taffy cache do not escape;
+ /// the owned geometry projection is published as the Document's latest
+ /// observable layout snapshot. Screencast polling can be suppressed by an
+ /// unchanged generation token, but every emitted frame is painted fresh.
pub(super) fn capture_screenshot(
&mut self,
request: RendererCaptureScreenshotRequest,
@@ -114,6 +179,16 @@ impl PageVm {
surface.device_pixel_ratio as f32,
);
let paint_capture = request.paint_capture_request()?;
+ let visual_state_before = matches!(request.purpose, RendererScreenshotPurpose::Screencast)
+ .then(|| {
+ self.vm()
+ .visual_state_token(self.document_lifecycle.identity(), viewport)
+ });
+ if visual_state_before.is_some()
+ && visual_state_before.as_ref() == request.known_visual_state.as_ref()
+ {
+ return Ok(RendererCaptureScreenshotReply::ScreencastUnchanged);
+ }
let layout_reason = match request.purpose {
RendererScreenshotPurpose::Screenshot | RendererScreenshotPurpose::Print { .. } => {
moli_layout::LayoutFlushReason::Screenshot
@@ -128,6 +203,22 @@ impl PageVm {
else {
return Ok(RendererCaptureScreenshotReply::NoDocument);
};
+ let visual_state = visual_state_before.map(|before| {
+ let after = self
+ .vm()
+ .visual_state_token(self.document_lifecycle.identity(), viewport);
+ // Resource decoders can publish from another task while layout is
+ // sampling immutable resources. Keep the older token in that
+ // race so the next poll cannot mistake a potentially stale frame
+ // for the newly completed resource state. Other generation
+ // changes here are renderer-internal world preparation and are
+ // represented by the completed fresh frame.
+ if before.has_same_paint_resources(&after) {
+ after
+ } else {
+ before
+ }
+ });
let raster = moli_paint::raster_snapshot(&snapshot)?;
let (mime_type, width, height, bytes) = match request.format {
@@ -151,6 +242,7 @@ impl PageVm {
width,
height,
bytes: bytes.into(),
+ visual_state,
},
))
}
diff --git a/moli-renderer-v8/src/runtime/page_surface.rs b/moli-renderer-v8/src/runtime/page_surface.rs
index eef06e752..015d663dc 100644
--- a/moli-renderer-v8/src/runtime/page_surface.rs
+++ b/moli-renderer-v8/src/runtime/page_surface.rs
@@ -5133,11 +5133,13 @@ pub struct RendererCapturedScreenshot {
pub width: u32,
pub height: u32,
pub bytes: Arc<[u8]>,
+ pub visual_state: Option<RendererVisualStateToken>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RendererCaptureScreenshotReply {
Captured(RendererCapturedScreenshot),
+ ScreencastUnchanged,
LayoutDisabled,
NoDocument,
}
diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update.rs b/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update.rs
index 73a6e3668..71301684d 100644
--- a/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update.rs
@@ -9,6 +9,21 @@ use crate::page_task_queue::{
};
use crate::script_vm::MainDocumentLifecycleBody;
+fn viewport_screencast_request(
+ known_visual_state: Option<crate::runtime::RendererVisualStateToken>,
+) -> crate::runtime::RendererCaptureScreenshotRequest {
+ crate::runtime::RendererCaptureScreenshotRequest {
+ purpose: crate::runtime::RendererScreenshotPurpose::Screencast,
+ format: crate::runtime::RendererScreenshotFormat::Png,
+ quality: 100,
+ region: crate::runtime::RendererScreenshotRegion::Viewport,
+ optimize_for_speed: true,
+ max_width: None,
+ max_height: None,
+ known_visual_state,
+ }
+}
+
async fn dispatch_main_document_domcontentloaded_for_rendering_test(
page_vm: &mut PageVm,
) -> anyhow::Result<crate::frame_owner_model::FrameDocumentTaskOwner> {
@@ -421,6 +436,183 @@ document.body.innerHTML = '<div id=target></div>';
.expect("screencast layout cache test should run");
}
+#[tokio::test(flavor = "current_thread")]
+async fn screencast_visual_token_tracks_child_document_styles_without_retaining_paint() {
+ run_page_vm_async_test(async move {
+ let loader =
+ crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");
+ let mut page_vm = test_page_vm_with_loader_and_document_url(
+ &loader,
+ Vec::new(),
+ Url::parse("https://example.com/child-screencast-style-generation.html")?,
+ );
+ page_vm.vm_mut().eval(
+ r#"
+document.documentElement.style.cssText = 'margin:0;background:white';
+document.body.style.cssText = 'margin:0';
+const frame = document.createElement('iframe');
+frame.style.cssText = 'display:block;width:40px;height:20px;border:0';
+document.body.appendChild(frame);
+const child = frame.contentDocument;
+child.documentElement.style.cssText = 'margin:0';
+child.body.style.cssText = 'margin:0;width:40px;height:20px';
+globalThis.__childScreencastSheet = new frame.contentWindow.CSSStyleSheet();
+globalThis.__childScreencastSheet.replaceSync('body { background: red; }');
+child.adoptedStyleSheets = [globalThis.__childScreencastSheet];
+'installed'
+"#,
+ )?;
+
+ let passes_before = page_vm.vm().layout_pass_observability_for_test().1;
+ let crate::runtime::RendererCaptureScreenshotReply::Captured(first) =
+ page_vm.capture_screenshot(viewport_screencast_request(None))?
+ else {
+ panic!("first child-style screencast demand must capture a frame");
+ };
+ let first_raster = moli_image::decode_png(&first.bytes)?;
+ assert_eq!(&first_raster.rgba[0..4], [255, 0, 0, 255]);
+ let first_visual_state = first
+ .visual_state
+ .expect("a screencast frame must publish visual-state metadata");
+ let passes_after_first = page_vm.vm().layout_pass_observability_for_test().1;
+ assert_eq!(passes_after_first, passes_before + 1);
+
+ assert_eq!(
+ page_vm.capture_screenshot(viewport_screencast_request(Some(
+ first_visual_state.clone(),
+ )))?,
+ crate::runtime::RendererCaptureScreenshotReply::ScreencastUnchanged,
+ );
+ assert_eq!(
+ page_vm.vm().layout_pass_observability_for_test().1,
+ passes_after_first,
+ "an unchanged token must avoid layout and paint entirely",
+ );
+
+ page_vm
+ .vm_mut()
+ .eval("globalThis.__childScreencastSheet.replaceSync('body { background: blue; }')")?;
+ let crate::runtime::RendererCaptureScreenshotReply::Captured(refreshed) = page_vm
+ .capture_screenshot(viewport_screencast_request(Some(
+ first_visual_state.clone(),
+ )))?
+ else {
+ panic!("a child stylesheet mutation must capture a fresh frame");
+ };
+ assert_eq!(
+ page_vm.vm().layout_pass_observability_for_test().1,
+ passes_after_first + 1,
+ "a child-only stylesheet generation must invalidate the session token",
+ );
+ assert_ne!(refreshed.visual_state.as_ref(), Some(&first_visual_state));
+ let refreshed_raster = moli_image::decode_png(&refreshed.bytes)?;
+ assert_eq!(&refreshed_raster.rgba[0..4], [0, 0, 255, 255]);
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("child screencast style-generation fixture should run");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn screencast_visual_token_tracks_canvas_and_scroll_while_screenshot_stays_fresh() {
+ run_page_vm_async_test(async move {
+ let loader =
+ crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");
+ let mut page_vm = test_page_vm_with_loader_and_document_url(
+ &loader,
+ Vec::new(),
+ Url::parse("https://example.com/screencast-visual-generations.html")?,
+ );
+ page_vm.set_viewport_surface(Some(crate::protocol_types::ViewportSurface {
+ inner_width: 40,
+ inner_height: 30,
+ outer_width: 40,
+ outer_height: 30,
+ device_pixel_ratio: 1.0,
+ screen_width: 40,
+ screen_height: 30,
+ screen_avail_width: 40,
+ screen_avail_height: 30,
+ }))?;
+ page_vm.vm_mut().eval(
+ r#"
+document.documentElement.style.cssText = 'margin:0;background:white';
+document.body.style.cssText = 'margin:0;height:100px';
+const canvas = document.createElement('canvas');
+canvas.id = 'surface';
+canvas.width = 40;
+canvas.height = 100;
+canvas.style.cssText = 'display:block;width:40px;height:100px';
+document.body.appendChild(canvas);
+const context = canvas.getContext('2d');
+context.fillStyle = 'red';
+context.fillRect(0, 0, 40, 100);
+'installed'
+"#,
+ )?;
+
+ let crate::runtime::RendererCaptureScreenshotReply::Captured(first) =
+ page_vm.capture_screenshot(viewport_screencast_request(None))?
+ else {
+ panic!("initial canvas screencast demand must capture a frame");
+ };
+ let first_state = first.visual_state.expect("initial visual-state token");
+ assert_eq!(&moli_image::decode_png(&first.bytes)?.rgba[0..4], [255, 0, 0, 255]);
+
+ assert_eq!(
+ page_vm.capture_screenshot(viewport_screencast_request(Some(first_state.clone())))?,
+ crate::runtime::RendererCaptureScreenshotReply::ScreencastUnchanged,
+ );
+
+ // Canvas pixel writes do not mutate the DOM or stylesheet worlds. The
+ // resource generation must independently invalidate the token.
+ page_vm.vm_mut().eval(
+ "const c=document.getElementById('surface').getContext('2d');c.fillStyle='#0000ff';c.fillRect(0,0,40,100);'painted'",
+ )?;
+ let crate::runtime::RendererCaptureScreenshotReply::Captured(canvas_frame) = page_vm
+ .capture_screenshot(viewport_screencast_request(Some(first_state.clone())))?
+ else {
+ panic!("canvas mutation must capture a fresh screencast frame");
+ };
+ let canvas_state = canvas_frame
+ .visual_state
+ .expect("canvas frame visual-state token");
+ assert_ne!(canvas_state, first_state);
+ assert_eq!(
+ &moli_image::decode_png(&canvas_frame.bytes)?.rgba[0..4],
+ [0, 0, 255, 255]
+ );
+
+ page_vm.vm_mut().eval("scrollTo(0, 30); scrollY")?;
+ let crate::runtime::RendererCaptureScreenshotReply::Captured(scrolled) = page_vm
+ .capture_screenshot(viewport_screencast_request(Some(canvas_state.clone())))?
+ else {
+ panic!("scroll mutation must capture a fresh screencast frame");
+ };
+ let scrolled_state = scrolled
+ .visual_state
+ .expect("scrolled frame visual-state token");
+ assert_ne!(scrolled_state, canvas_state);
+
+ let passes_before_screenshot = page_vm.vm().layout_pass_observability_for_test().1;
+ let mut screenshot = crate::runtime::RendererCaptureScreenshotRequest::viewport_png();
+ screenshot.known_visual_state = Some(scrolled_state);
+ let crate::runtime::RendererCaptureScreenshotReply::Captured(screenshot) =
+ page_vm.capture_screenshot(screenshot)?
+ else {
+ panic!("ordinary screenshots must ignore screencast token suppression");
+ };
+ assert!(screenshot.visual_state.is_none());
+ assert_eq!(
+ page_vm.vm().layout_pass_observability_for_test().1,
+ passes_before_screenshot + 1,
+ );
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("screencast visual generations fixture should run");
+}
+
#[tokio::test(flavor = "current_thread")]
async fn screenshot_composes_iframe_documents_into_exact_used_content_viewports() {
run_page_vm_async_test(async move {
@@ -1961,7 +2153,82 @@ document.body.innerHTML = '<div id=negative class=case></div><div id=overflow cl
}
#[tokio::test]
-async fn screenshot_paint_consumes_ready_webp_and_svg_css_url_layers() {
+async fn child_document_cssom_invalidates_generation_gated_image_discovery() {
+ run_page_vm_async_test(async move {
+ let image_url =
+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M/wHwAF/gL+3MxZ5wAAAABJRU5ErkJggg==";
+ let loader =
+ crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");
+ loader.set_optional_resource_fetch_mask(
+ crate::protocol_types::OptionalResourceFetchMask::IMAGE,
+ );
+ let mut page_vm = test_page_vm_with_loader_and_document_url(
+ &loader,
+ Vec::new(),
+ Url::parse("https://example.com/child-css-image-discovery.html")?,
+ );
+ page_vm
+ .vm_mut()
+ .set_layout_policy(crate::real_layout_test_policy());
+ page_vm.vm_mut().eval(
+ r#"
+const frame = document.createElement('iframe');
+document.body.appendChild(frame);
+const child = frame.contentDocument;
+child.body.innerHTML = '<div id=target style="width:20px;height:20px"></div>';
+globalThis.__childImageSheet = new frame.contentWindow.CSSStyleSheet();
+globalThis.__childImageSheet.replaceSync('#target { background: red; }');
+child.adoptedStyleSheets = [globalThis.__childImageSheet];
+'installed'
+"#,
+ )?;
+
+ let viewport = moli_layout::PaintViewport::new(80, 60, 1.0);
+ page_vm
+ .vm_mut()
+ .screenshot_layout_snapshot(viewport)?
+ .expect("initial child document paint");
+ let after_first = page_vm.vm().css_image_discovery_count_for_test();
+ page_vm
+ .vm_mut()
+ .screenshot_layout_snapshot(viewport)?
+ .expect("clean child document paint");
+ assert_eq!(
+ page_vm.vm().css_image_discovery_count_for_test(),
+ after_first,
+ "a clean child style world must reuse its discovery result",
+ );
+
+ page_vm.vm_mut().eval(&format!(
+ "globalThis.__childImageSheet.replaceSync('#target {{ background-image: url({}); }}')",
+ serde_json::to_string(image_url)?,
+ ))?;
+ page_vm
+ .vm_mut()
+ .screenshot_layout_snapshot(viewport)?
+ .expect("mutated child document paint");
+ assert_eq!(
+ page_vm.vm().css_image_discovery_count_for_test(),
+ after_first + 1,
+ "a child-only CSSOM generation must invalidate root paint discovery",
+ );
+ assert!(
+ page_vm
+ .vm()
+ .css_image_resource_observability_for_test()
+ .4
+ .iter()
+ .any(|url| url == image_url),
+ "computed discovery must walk the child Document root",
+ );
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("child CSS image discovery fixture should run");
+}
+
+#[tokio::test]
+async fn css_image_discovery_is_generation_gated_across_fresh_paint_passes() {
run_page_vm_async_test(async move {
// A lossless 2x2 red WebP. Keep the HTTP fixture encoded so this
// product path exercises metadata probing and bounded WebP decode.
@@ -2015,12 +2282,19 @@ html,body{{margin:0;padding:0;background:white}}
// The first paint demand discovers computed CSSOM URLs and queues
// the bounded decoders. CSS images have no DOM load-event task; a
// later screencast/screenshot samples immutable ready resources.
+ let discoveries_before = page_vm.vm().css_image_discovery_count_for_test();
+ let passes_before = page_vm.vm().layout_pass_observability_for_test().1;
page_vm
.vm_mut()
- .screenshot_layout_snapshot(moli_layout::PaintViewport::new(
- 80, 120, 1.0,
- ))?
+ .paint_layout_snapshot(
+ moli_layout::PaintViewport::new(80, 120, 1.0),
+ moli_layout::LayoutFlushReason::Screencast,
+ )?
.expect("CSS image fixture must retain a layout root");
+ let discoveries_after_first = page_vm.vm().css_image_discovery_count_for_test();
+ assert_eq!(discoveries_after_first, discoveries_before + 1);
+ let passes_after_first = page_vm.vm().layout_pass_observability_for_test().1;
+ assert_eq!(passes_after_first, passes_before + 1);
let urls = [&raster_url, &vector_url, &mask_url];
let completion_notify = page_vm.vm().css_image_completion_notify_for_test();
let all_ready = tokio::time::timeout(std::time::Duration::from_secs(3), async {
@@ -2048,10 +2322,22 @@ html,body{{margin:0;padding:0;background:white}}
let snapshot = page_vm
.vm_mut()
- .screenshot_layout_snapshot(moli_layout::PaintViewport::new(
- 80, 120, 1.0,
- ))?
+ .paint_layout_snapshot(
+ moli_layout::PaintViewport::new(80, 120, 1.0),
+ moli_layout::LayoutFlushReason::Screencast,
+ )?
.expect("ready CSS image fixture must retain a layout root");
+ let passes_after_ready = page_vm.vm().layout_pass_observability_for_test().1;
+ assert_eq!(
+ passes_after_ready,
+ passes_after_first + 1,
+ "each explicit paint demand must still execute a fresh layout",
+ );
+ assert_eq!(
+ page_vm.vm().css_image_discovery_count_for_test(),
+ discoveries_after_first,
+ "resource completion and an unchanged paint must reuse CSS image discovery",
+ );
assert_eq!(snapshot.images.len(), 1);
assert_eq!(snapshot.svg_images.len(), 3);
assert!(snapshot.fragments.iter().any(|fragment| {
@@ -2073,6 +2359,22 @@ html,body{{margin:0;padding:0;background:white}}
&image.rgba[index..index + 4]
};
assert_eq!(pixel(5, 5), [255, 0, 0, 255]);
+
+ page_vm
+ .vm_mut()
+ .eval("document.getElementById('raster').style.backgroundPosition = '1px 0px'")?;
+ page_vm
+ .vm_mut()
+ .paint_layout_snapshot(
+ moli_layout::PaintViewport::new(80, 120, 1.0),
+ moli_layout::LayoutFlushReason::Screencast,
+ )?
+ .expect("style-mutated CSS image fixture must retain a layout root");
+ assert_eq!(
+ page_vm.vm().css_image_discovery_count_for_test(),
+ discoveries_after_first + 1,
+ "a style mutation must invalidate CSS image discovery",
+ );
assert_eq!(pixel(35, 5), [255, 0, 0, 255]);
assert_eq!(pixel(5, 15), [255, 255, 255, 255]);
assert_eq!(pixel(5, 35), [0, 0, 255, 255]);
diff --git a/moli-renderer-v8/src/runtime/tests.rs b/moli-renderer-v8/src/runtime/tests.rs
index 45795e25a..9d21e8bb1 100644
--- a/moli-renderer-v8/src/runtime/tests.rs
+++ b/moli-renderer-v8/src/runtime/tests.rs
@@ -588,6 +588,7 @@ async fn screenshot_and_screencast_paint_downloaded_svg_vectors() {
optimize_for_speed: true,
max_width: None,
max_height: None,
+ known_visual_state: None,
},
)
.await;
@@ -694,6 +695,7 @@ async fn capture_screenshot_encodes_jpeg_and_limits_device_dimensions() {
optimize_for_speed: false,
max_width: Some(5),
max_height: Some(4),
+ known_visual_state: None,
};
let (reply, _) = page
.run_async_command(RendererPageCommand::CaptureScreenshot(request))
@@ -762,6 +764,7 @@ async fn print_capture_uses_print_media_controls_backgrounds_and_restores_screen
optimize_for_speed: false,
max_width: None,
max_height: None,
+ known_visual_state: None,
},
)
.await;
@@ -780,6 +783,7 @@ async fn print_capture_uses_print_media_controls_backgrounds_and_restores_screen
optimize_for_speed: false,
max_width: None,
max_height: None,
+ known_visual_state: None,
},
)
.await;
@@ -842,6 +846,7 @@ async fn capture_screenshot_clip_and_full_document_keep_the_live_layout_viewport
optimize_for_speed: false,
max_width: None,
max_height: None,
+ known_visual_state: None,
},
)
.await;
@@ -865,6 +870,7 @@ async fn capture_screenshot_clip_and_full_document_keep_the_live_layout_viewport
optimize_for_speed: true,
max_width: None,
max_height: None,
+ known_visual_state: None,
},
)
.await;
@@ -923,6 +929,7 @@ async fn bounded_viewport_clip_keeps_root_controls_while_page_clip_omits_them()
optimize_for_speed: false,
max_width: None,
max_height: None,
+ known_visual_state: None,
},
)
.await;
@@ -952,6 +959,7 @@ async fn bounded_viewport_clip_keeps_root_controls_while_page_clip_omits_them()
optimize_for_speed: false,
max_width: None,
max_height: None,
+ known_visual_state: None,
},
)
.await;
@@ -983,6 +991,7 @@ async fn capture_screenshot_rejects_full_document_at_the_128k_css_boundary() {
optimize_for_speed: false,
max_width: None,
max_height: None,
+ known_visual_state: None,
};
let error = match page
@@ -12727,6 +12736,7 @@ addEventListener("wheel", event => {
optimize_for_speed: true,
max_width: None,
max_height: None,
+ known_visual_state: None,
},
)
.await;
diff --git a/moli-renderer-v8/src/script_vm.rs b/moli-renderer-v8/src/script_vm.rs
index b22b5a9a3..2b227d7c3 100644
--- a/moli-renderer-v8/src/script_vm.rs
+++ b/moli-renderer-v8/src/script_vm.rs
@@ -2450,6 +2450,16 @@ impl ScriptVm {
.map_err(anyhow::Error::new)
}
+ pub(super) fn visual_state_token(
+ &self,
+ document: crate::runtime::RendererDocumentLifecycleIdentity,
+ viewport: moli_layout::PaintViewport,
+ ) -> crate::runtime::RendererVisualStateToken {
+ self._context_host
+ .borrow()
+ .visual_state_token(document, viewport)
+ }
+
fn with_fresh_layout_pass<T>(
&mut self,
request: moli_layout::LayoutPassRequest,
@@ -2461,9 +2471,8 @@ impl ScriptVm {
// the guard is entered, layout performs no JS, event-loop, observer,
// or resource completion work and owns no state beyond this call.
self.reconcile_document_web_fonts_for_layout();
- if request.requests_paint() {
- self.reconcile_document_css_images_for_paint();
- }
+ let discovered_css_images =
+ request.requests_paint() && self.reconcile_document_css_images_for_paint();
let (document, result) = {
let context_host = self._context_host.borrow();
let document = context_host.document_handle();
@@ -2487,6 +2496,11 @@ impl ScriptVm {
// sampled geometry.
tracing::warn!(?error, "failed to admit lazy images after layout refresh");
}
+ if discovered_css_images {
+ self._context_host
+ .borrow_mut()
+ .publish_css_image_discovery_for_paint();
+ }
result
}
@@ -2520,6 +2534,13 @@ impl ScriptVm {
.css_image_resource_observability_for_test()
}
+ #[cfg(test)]
+ pub(crate) fn css_image_discovery_count_for_test(&self) -> u64 {
+ self._context_host
+ .borrow()
+ .css_image_discovery_count_for_test()
+ }
+
#[cfg(test)]
pub(crate) fn css_image_completion_notify_for_test(
&self,
@@ -2599,7 +2620,7 @@ impl ScriptVm {
self.start_stylesheet_subresource_fetches(bound);
}
- fn reconcile_document_css_images_for_paint(&mut self) {
+ fn reconcile_document_css_images_for_paint(&mut self) -> bool {
let image_fetch_enabled = self
.document_runtime
.current_document_resource_loader()
@@ -2615,17 +2636,27 @@ impl ScriptVm {
.layout_policy()
.uses_real_layout()
{
- return;
+ return false;
}
let resources = {
let host = self._context_host.borrow();
- host.dom_host()
- .document_element_handle()
- .map(|root| crate::layout_renderer::current_native_css_image_resources(&host, root))
- .unwrap_or_default()
+ if !host.css_image_discovery_needed_for_paint() {
+ return false;
+ }
+ host.active_layout_document_handles()
+ .into_iter()
+ .filter_map(|document| {
+ host.dom_host()
+ .dom()
+ .document_element_handle_for_document(document)
+ })
+ .flat_map(|root| {
+ crate::layout_renderer::current_native_css_image_resources(&host, root)
+ })
+ .collect::<Vec<_>>()
};
if resources.is_empty() {
- return;
+ return true;
}
let bound = {
let mut host = self._context_host.borrow_mut();
@@ -2638,6 +2669,7 @@ impl ScriptVm {
.collect::<Vec<_>>()
};
self.start_stylesheet_subresource_fetches(bound);
+ true
}
pub(crate) fn observable_geometry_batch_for_current_document(
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style.rs
index a01304b01..7d6b140b2 100644
--- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style.rs
+++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style.rs
@@ -1790,6 +1790,151 @@ fn computed_style_reuses_retained_system_across_connected_shadow_roots() {
2
);
}
+
+#[test]
+fn child_layout_uses_complete_stable_tree_scope_universe() {
+ let mut vm = new_storage_test_vm("https://child-tree-scope-universe.test/");
+
+ vm.eval(
+ r#"
+(() => {
+ const body = document.body || document.documentElement || document;
+ const frame = document.createElement('iframe');
+ frame.id = 'tree-scope-universe-frame';
+ frame.style.cssText = 'width: 320px; height: 240px; border: 0';
+ body.appendChild(frame);
+
+ const childDocument = frame.contentDocument;
+ childDocument.open();
+ childDocument.write('<style>body { color: rgb(4, 5, 6); }</style><body><main>child</main></body>');
+ childDocument.close();
+ for (let index = 0; index < 32; index += 1) {
+ const host = childDocument.createElement('section');
+ childDocument.body.appendChild(host);
+ const shadow = host.attachShadow({mode: 'open'});
+ shadow.append(`empty-${index}`);
+ if (index % 8 === 0) {
+ const style = childDocument.createElement('style');
+ style.textContent = ':host { display: block; }';
+ shadow.prepend(style);
+ }
+ }
+})()
+"#,
+ )
+ .expect("child TreeScope universe fixture should initialize");
+
+ let child_document = child_document_handle_for_frame_id(&vm, "tree-scope-universe-frame");
+ let rebuilds_before =
+ vm.retained_style_system_rebuild_count_for_document_for_test(child_document);
+ let builds_before = vm
+ ._context_host
+ .borrow()
+ .stylo_computed_style_input_builds_for_test();
+ let key_builds_before = vm
+ ._context_host
+ .borrow()
+ .stylo_style_system_key_builds_for_test();
+
+ vm.screenshot_layout_snapshot(moli_layout::PaintViewport::new(800, 600, 1.0))
+ .expect("child TreeScope universe paint layout should succeed")
+ .expect("the fixture should have a layout root");
+
+ assert_eq!(
+ vm.retained_style_system_rebuild_count_for_document_for_test(child_document)
+ .saturating_sub(rebuilds_before),
+ 1,
+ "one child-document layout must build one retained style system",
+ );
+ assert_eq!(
+ vm._context_host
+ .borrow()
+ .stylo_computed_style_input_builds_for_test()
+ .saturating_sub(builds_before),
+ 2,
+ "the paint layout must prepare exactly one input for each document",
+ );
+ assert_eq!(
+ vm._context_host
+ .borrow()
+ .stylo_style_system_key_builds_for_test()
+ .saturating_sub(key_builds_before),
+ 2,
+ "the paint layout must hash exactly one style-system key for each document",
+ );
+}
+
+#[test]
+fn empty_shadow_root_universe_changes_rebuild_once_per_dom_mutation() {
+ let mut vm = new_storage_test_vm("https://empty-shadow-universe-mutation.test/");
+ let document = vm.document_handle_for_test();
+
+ let initial = vm
+ .eval(
+ r#"
+(() => {
+ const root = document.documentElement || document.appendChild(document.createElement('html'));
+ const body = document.body || root.appendChild(document.createElement('body'));
+ const light = document.createElement('main');
+ light.id = 'universe-light';
+ body.appendChild(light);
+ return getComputedStyle(light).display;
+})()
+"#,
+ )
+ .expect("initial light-tree style should evaluate");
+ assert_eq!(initial, "block");
+ let rebuilds_after_initial =
+ vm.retained_style_system_rebuild_count_for_document_for_test(document);
+
+ let attached = vm
+ .eval(
+ r#"
+(() => {
+ const host = document.createElement('section');
+ host.id = 'universe-host';
+ document.body.appendChild(host);
+ const shadow = host.attachShadow({mode: 'open'});
+ const target = document.createElement('span');
+ target.id = 'universe-shadow-target';
+ shadow.appendChild(target);
+ return [
+ getComputedStyle(document.getElementById('universe-light')).display,
+ getComputedStyle(target).display,
+ getComputedStyle(document.getElementById('universe-light')).display
+ ].join('|');
+})()
+"#,
+ )
+ .expect("styles after empty Shadow Root attachment should evaluate");
+ assert_eq!(attached, "block|inline|block");
+ let rebuilds_after_attach =
+ vm.retained_style_system_rebuild_count_for_document_for_test(document);
+ assert_eq!(
+ rebuilds_after_attach.saturating_sub(rebuilds_after_initial),
+ 1,
+ "attaching one empty Shadow Root must replace the document universe exactly once",
+ );
+
+ let removed = vm
+ .eval(
+ r#"
+(() => {
+ document.getElementById('universe-host').remove();
+ const light = document.getElementById('universe-light');
+ return [getComputedStyle(light).display, getComputedStyle(light).display].join('|');
+})()
+"#,
+ )
+ .expect("styles after empty Shadow Root removal should evaluate");
+ assert_eq!(removed, "block|block");
+ assert_eq!(
+ vm.retained_style_system_rebuild_count_for_document_for_test(document)
+ .saturating_sub(rebuilds_after_attach),
+ 1,
+ "disconnecting one empty Shadow Root must replace the document universe exactly once",
+ );
+}
#[test]
fn computed_style_is_empty_for_detached_and_non_flat_tree_elements() {
let mut vm = new_storage_test_vm("https://computed-style-non-flat-tree.test/");
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/dom.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/dom.rs
index 2874f96be..37aa0f7c6 100644
--- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/dom.rs
+++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/dom.rs
@@ -8196,7 +8196,7 @@ fn inner_text_document_input_cache_tracks_document_url_changes() {
}
#[test]
-fn inner_text_keeps_distinct_shadow_style_input_scopes() {
+fn inner_text_reuses_one_document_style_world_across_shadow_scopes() {
let mut vm = new_parsed_test_vm(
"https://inner-text-shadow-style-inputs.test/",
r#"<!doctype html><html><body>
@@ -8253,23 +8253,106 @@ host.attachShadow({mode: 'open'}).innerHTML =
assert_eq!(layout_after_second.1, layout_after_first.1);
assert_eq!(
builds_after_first.saturating_sub(builds_before),
- 5,
- "layout and rendered-text collection must preserve all shadow-aware style scopes"
+ 1,
+ "layout and rendered-text collection must share one document TreeScope universe"
);
assert_eq!(
builds_after_second.saturating_sub(builds_after_first),
- 2,
- "the rendered-text collector still resolves current shadow-aware styles on a geometry cache hit"
+ 0,
+ "an unchanged document TreeScope universe must reuse its prepared input"
);
assert_eq!(
key_builds_after_first.saturating_sub(key_builds_before),
- 5,
- "each layout and collector style input must own its exact retained-system key"
+ 1,
+ "one observation must build one retained-system key for the document"
);
assert_eq!(
key_builds_after_second.saturating_sub(key_builds_after_first),
- 2,
- "the rendered-text collector keeps exact owner-local Stylo keys without rebuilding layout"
+ 0,
+ "the rendered-text collector must reuse the unchanged document key"
+ );
+}
+
+#[test]
+fn paint_layout_reuses_one_style_world_across_many_empty_shadow_roots() {
+ let mut vm = new_parsed_test_vm(
+ "https://paint-empty-shadow-style-world.test/",
+ r#"<!doctype html><html><head><style>
+ body { color: rgb(1, 2, 3); }
+ </style></head><body><main id="light">light</main></body></html>"#,
+ );
+ vm.eval(
+ r#"
+const body = document.body;
+for (let index = 0; index < 64; index += 1) {
+ const host = document.createElement('section');
+ body.appendChild(host);
+ const shadow = host.attachShadow({mode: index % 2 === 0 ? 'open' : 'closed'});
+ const target = document.createElement('span');
+ target.textContent = `shadow-${index}`;
+ shadow.appendChild(target);
+ if (index % 8 === 0) {
+ const nestedHost = document.createElement('article');
+ shadow.appendChild(nestedHost);
+ nestedHost.attachShadow({mode: 'open'}).append(`nested-${index}`);
+ }
+}
+"#,
+ )
+ .expect("empty shadow-root paint fixture should initialize");
+
+ let document = vm.document_handle_for_test();
+ let rebuilds_before = vm.retained_style_system_rebuild_count_for_document_for_test(document);
+ let builds_before = vm
+ ._context_host
+ .borrow()
+ .stylo_computed_style_input_builds_for_test();
+ let key_builds_before = vm
+ ._context_host
+ .borrow()
+ .stylo_style_system_key_builds_for_test();
+
+ vm.screenshot_layout_snapshot(moli_layout::PaintViewport::new(800, 600, 1.0))
+ .expect("first empty shadow-root paint layout should succeed")
+ .expect("the fixture should have a layout root");
+ let rebuilds_after_first =
+ vm.retained_style_system_rebuild_count_for_document_for_test(document);
+ let builds_after_first = vm
+ ._context_host
+ .borrow()
+ .stylo_computed_style_input_builds_for_test();
+ let key_builds_after_first = vm
+ ._context_host
+ .borrow()
+ .stylo_style_system_key_builds_for_test();
+
+ vm.screenshot_layout_snapshot(moli_layout::PaintViewport::new(800, 600, 1.0))
+ .expect("second empty shadow-root paint layout should succeed")
+ .expect("the fixture should have a layout root");
+
+ assert_eq!(
+ rebuilds_after_first.saturating_sub(rebuilds_before),
+ 1,
+ "entering and leaving empty shadow roots must not replace the retained style system",
+ );
+ assert_eq!(
+ vm.retained_style_system_rebuild_count_for_document_for_test(document),
+ rebuilds_after_first,
+ "an unchanged fresh paint layout must retain the same document style system",
+ );
+ assert_eq!(builds_after_first.saturating_sub(builds_before), 1);
+ assert_eq!(key_builds_after_first.saturating_sub(key_builds_before), 1);
+ assert_eq!(
+ vm._context_host
+ .borrow()
+ .stylo_computed_style_input_builds_for_test(),
+ builds_after_first,
+ );
+ assert_eq!(
+ vm._context_host
+ .borrow()
+ .stylo_style_system_key_builds_for_test(),
+ key_builds_after_first,
);
}
diff --git a/moli-renderer-v8/src/style_engine/cache.rs b/moli-renderer-v8/src/style_engine/cache.rs
index 273f96b30..860afaf6f 100644
--- a/moli-renderer-v8/src/style_engine/cache.rs
+++ b/moli-renderer-v8/src/style_engine/cache.rs
@@ -233,6 +233,7 @@ mod tests {
fn key(path: &str) -> StyloDocumentComputedStyleInputCacheKey {
StyloDocumentComputedStyleInputCacheKey::new(
None,
+ &[],
&url::Url::parse(&format!("https://document.test/{path}"))
.expect("cache test document URL should parse"),
StyleViewport::default(),
diff --git a/moli-renderer-v8/src/style_engine/document_world.rs b/moli-renderer-v8/src/style_engine/document_world.rs
index 4be7d8ca7..c5fbfa723 100644
--- a/moli-renderer-v8/src/style_engine/document_world.rs
+++ b/moli-renderer-v8/src/style_engine/document_world.rs
@@ -101,4 +101,26 @@ impl DocumentStyleWorlds {
})
.collect()
}
+
+ pub(super) fn observation_generations(
+ &self,
+ documents: impl IntoIterator<Item = DomHandle>,
+ ) -> Vec<(DomHandle, u64, u64, u64)> {
+ let mut documents = documents.into_iter().collect::<Vec<_>>();
+ documents.sort_by_key(|document| document.index());
+ documents.dedup();
+ documents
+ .into_iter()
+ .map(|document| {
+ let world = self.for_document(document);
+ let generation = world.document_state.generation_snapshot();
+ (
+ document,
+ generation.source_set_generation,
+ generation.computed_cache_generation,
+ generation.target_context_epoch,
+ )
+ })
+ .collect()
+ }
}
diff --git a/moli-renderer-v8/src/style_engine/mod.rs b/moli-renderer-v8/src/style_engine/mod.rs
index 30583a2d4..34f42afd9 100644
--- a/moli-renderer-v8/src/style_engine/mod.rs
+++ b/moli-renderer-v8/src/style_engine/mod.rs
@@ -269,6 +269,7 @@ pub(crate) struct StyloStyleEnvironment {
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct StyloDocumentComputedStyleInputCacheKey {
read_document: Option<DomHandle>,
+ tree_scope_roots: Vec<DomHandle>,
document_url: url::Url,
viewport_width_bits: Option<u64>,
viewport_height_bits: Option<u64>,
@@ -281,6 +282,7 @@ pub(crate) struct StyloDocumentComputedStyleInputCacheKey {
impl StyloDocumentComputedStyleInputCacheKey {
pub(crate) fn new(
read_document: Option<DomHandle>,
+ tree_scope_roots: &[DomHandle],
document_url: &url::Url,
viewport: StyleViewport,
environment: StyloStyleEnvironment,
@@ -290,6 +292,7 @@ impl StyloDocumentComputedStyleInputCacheKey {
document_url.set_fragment(None);
Self {
read_document,
+ tree_scope_roots: tree_scope_roots.to_vec(),
document_url,
viewport_width_bits: viewport.width.map(f64::to_bits),
viewport_height_bits: viewport.height.map(f64::to_bits),
@@ -462,6 +465,23 @@ impl MoliStyleEngine {
.computed_cache_generation()
}
+ pub(crate) fn computed_style_observation_generations(
+ &self,
+ documents: impl IntoIterator<Item = DomHandle>,
+ ) -> Vec<(DomHandle, u64, u64, u64)> {
+ self.document_worlds.observation_generations(documents)
+ }
+
+ #[cfg(debug_assertions)]
+ pub(crate) fn computed_style_read_invariant_state(&self, document: DomHandle) -> (u64, u64) {
+ let world = self.world_for_document(document);
+ let generations = world.document_state.generation_snapshot();
+ (
+ generations.source_set_generation,
+ generations.retained_style_system_generation,
+ )
+ }
+
pub(crate) fn cached_document_prepared_style_inputs(
&self,
document: DomHandle,
diff --git a/moli-renderer-v8/src/style_engine/tests/subtree_cache.rs b/moli-renderer-v8/src/style_engine/tests/subtree_cache.rs
index a54f0cfb1..7d5a2c66d 100644
--- a/moli-renderer-v8/src/style_engine/tests/subtree_cache.rs
+++ b/moli-renderer-v8/src/style_engine/tests/subtree_cache.rs
@@ -4915,6 +4915,43 @@ fn style_subtree_invalidation_retains_style_system() {
assert!(engine.computed_style_cache_entry_count_for_document_for_test(document) == 0);
}
+#[test]
+fn retained_style_system_keeps_cascade_data_for_empty_shadow_scopes() {
+ let mut host = test_host();
+ let document = host.document_handle();
+ let open_host = host.create_element("section");
+ let closed_host = host.create_element("article");
+ assert!(host.append_child(document, open_host));
+ assert!(host.append_child(document, closed_host));
+ let open_root = host
+ .attach_shadow_root(open_host, "open")
+ .expect("open host should accept a shadow root");
+ let closed_root = host
+ .attach_shadow_root(closed_host, "closed")
+ .expect("closed host should accept a shadow root");
+
+ let engine = MoliStyleEngine::new();
+ let document_url = url::Url::parse("https://example.test/empty-scopes.html").unwrap();
+ let mut inputs = StyloComputedStyleInputs::default();
+ inputs
+ .shadow_stylesheet_sources
+ .push((open_root, Vec::new()));
+ inputs
+ .shadow_stylesheet_sources
+ .push((closed_root, Vec::new()));
+ let key = StyleSystemCacheKey::new(&document_url, &inputs, None);
+ engine.ensure_retained_style_system_for_document(&host, document, key, &inputs);
+
+ engine.with_retained_style_system_for_document_for_test(document, |retained| {
+ let roots = retained
+ .shadow_cascade_data
+ .iter()
+ .map(|(root, _)| *root)
+ .collect::<Vec<_>>();
+ assert_eq!(roots, vec![open_root, closed_root]);
+ });
+}
+
#[test]
fn style_subtree_invalidation_clears_only_affected_shadow_cascade_data() {
let mut host = test_host();
@@ -5297,6 +5334,7 @@ fn document_replacement_cleanup_preserves_unreplaced_document_world_and_shared_s
assert!(engine.dom_adapter.has_element_data(detached));
let input_cache_key = StyloDocumentComputedStyleInputCacheKey::new(
None,
+ &[],
&document_url,
StyleViewport::default(),
StyloStyleEnvironment::default(),
diff --git a/moli/src/fetch_dump.rs b/moli/src/fetch_dump.rs
index afd443bac..12f1c578b 100644
--- a/moli/src/fetch_dump.rs
+++ b/moli/src/fetch_dump.rs
@@ -178,6 +178,7 @@ async fn render_pdf_dump_async(page: &mut Page) -> Result<Vec<u8>> {
optimize_for_speed: false,
max_width: None,
max_height: None,
+ known_visual_state: None,
},
"pdf",
)
@@ -217,6 +218,9 @@ async fn capture_page_raster(
RendererCaptureScreenshotReply::NoDocument => {
bail!("--dump {dump_mode} requires a loaded HTML document")
}
+ RendererCaptureScreenshotReply::ScreencastUnchanged => {
+ bail!("--dump {dump_mode} returned an invalid screencast-only reply")
+ }
}
}