Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(cli): publish layout before fetch eval with --layout

ldm0011340a8a1e0
diff --git a/moli-core/src/page/renderer_command_support.rs b/moli-core/src/page/renderer_command_support.rs
index 70d9fed5e..24770e617 100644
--- a/moli-core/src/page/renderer_command_support.rs
+++ b/moli-core/src/page/renderer_command_support.rs
@@ -1452,6 +1452,16 @@ impl Page {
self.start_page_command(RendererPageCommand::SerializeHtml)
}
+ /// Publishes current layout for subsequent geometry reads without painting.
+ ///
+ /// This is an explicit refresh, used by CLI `fetch --layout --eval` after
+ /// readiness. Ordinary script evaluation and geometry reads do not call it.
+ /// When real layout is disabled, this is a no-op.
+ pub async fn publish_layout_async(&mut self) -> Result<()> {
+ self.dispatch_unit_page_command_async(RendererPageCommand::PublishLayout, "publish layout")
+ .await
+ }
+
pub fn start_layout_metrics(&self) -> Result<PendingPageCommand> {
self.start_page_command(RendererPageCommand::LayoutMetrics)
}
diff --git a/moli-layout/src/layout_tree/pass_result.rs b/moli-layout/src/layout_tree/pass_result.rs
index 44c8deced..72c12dbf4 100644
--- a/moli-layout/src/layout_tree/pass_result.rs
+++ b/moli-layout/src/layout_tree/pass_result.rs
@@ -25,6 +25,7 @@ pub enum LayoutFlushReason {
Screenshot,
Screencast,
Print,
+ Explicit,
SynchronousGeometry,
Test,
}
diff --git a/moli-renderer-v8/src/native_bridge/context_host/layout_snapshot.rs b/moli-renderer-v8/src/native_bridge/context_host/layout_snapshot.rs
index 7edab2c7a..a19b71a78 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/layout_snapshot.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/layout_snapshot.rs
@@ -12,8 +12,8 @@ struct LatestFrozenLayout {
/// This owns exactly one recursively frozen snapshot. It has no separately
/// keyed child tree, working layout world, source index, hit-test index, Taffy
/// cache, style borrow, pass diagnostics, paint snapshot, timer, or invalidation
-/// policy. Only screenshots and screencast frames replace this published layout;
-/// print projections are temporary and never enter this cache.
+/// policy. Screenshots, screencast frames and explicit layout refreshes replace
+/// this published layout; print projections never enter this cache.
#[derive(Default)]
pub(super) struct LatestLayoutTreeCache {
latest: Option<LatestFrozenLayout>,
diff --git a/moli-renderer-v8/src/runtime/page_commands.rs b/moli-renderer-v8/src/runtime/page_commands.rs
index 255205b4c..34986a81f 100644
--- a/moli-renderer-v8/src/runtime/page_commands.rs
+++ b/moli-renderer-v8/src/runtime/page_commands.rs
@@ -856,6 +856,10 @@ impl PageVm {
RendererPageCommand::LayoutMetrics => self
.layout_metrics()
.map(RendererPageReply::LayoutMetrics),
+ RendererPageCommand::PublishLayout => {
+ self.vm_mut().publish_layout()?;
+ Ok(RendererPageReply::Unit)
+ }
RendererPageCommand::CaptureScreenshot(request) => self
.capture_screenshot(request)
.map(RendererPageReply::CaptureScreenshot),
diff --git a/moli-renderer-v8/src/runtime/page_surface.rs b/moli-renderer-v8/src/runtime/page_surface.rs
index 3472300cd..e677729d6 100644
--- a/moli-renderer-v8/src/runtime/page_surface.rs
+++ b/moli-renderer-v8/src/runtime/page_surface.rs
@@ -5195,6 +5195,7 @@ pub enum RendererPageCommand {
},
SerializeHtml,
LayoutMetrics,
+ PublishLayout,
CaptureScreenshot(RendererCaptureScreenshotRequest),
CaptureScreencastFrame(RendererCaptureScreencastFrameRequest),
BlobBytesForUuid {
@@ -5794,6 +5795,7 @@ impl RendererPageCommand {
Self::RenderPageDump { .. } => Some("RenderPageDump"),
Self::SerializeHtml => Some("SerializeHtml"),
Self::LayoutMetrics => Some("LayoutMetrics"),
+ Self::PublishLayout => Some("PublishLayout"),
Self::CaptureScreenshot(_) => Some("CaptureScreenshot"),
Self::CaptureScreencastFrame(_) => Some("CaptureScreencastFrame"),
Self::ScrollBackendNodeIntoViewIfNeeded { .. } => {
diff --git a/moli-renderer-v8/src/script_vm.rs b/moli-renderer-v8/src/script_vm.rs
index 47563fd1e..3ab0f66fd 100644
--- a/moli-renderer-v8/src/script_vm.rs
+++ b/moli-renderer-v8/src/script_vm.rs
@@ -2434,6 +2434,21 @@ impl ScriptVm {
)
}
+ pub(super) fn publish_layout(&mut self) -> anyhow::Result<()> {
+ let viewport = {
+ let host = self._context_host.borrow();
+ if !host.layout_policy().uses_real_layout() {
+ return Ok(());
+ }
+ host.layout_viewport_for_document(host.document_handle())
+ };
+ self.with_fresh_layout_pass(
+ moli_layout::LayoutPassRequest::new(viewport, moli_layout::LayoutFlushReason::Explicit),
+ |_| Ok(()),
+ )?;
+ Ok(())
+ }
+
#[cfg(test)]
pub(super) fn screenshot_layout_snapshot(
&mut self,
@@ -2525,8 +2540,8 @@ impl ScriptVm {
// call.
self.reconcile_document_web_fonts_for_layout();
let requests_paint = request.requests_paint();
- // Printing consumes a temporary projection. Screenshots and screencast
- // frames publish geometry for input, observers and subsequent DOM reads.
+ // Printing consumes a temporary projection. Screenshots, screencast
+ // frames and explicit refreshes publish geometry for subsequent reads.
let publishes_layout = request.reason != moli_layout::LayoutFlushReason::Print;
let (document, result) = {
let context_host = self._context_host.borrow();
diff --git a/moli/src/app.rs b/moli/src/app.rs
index 6942d97fa..a50fa0419 100644
--- a/moli/src/app.rs
+++ b/moli/src/app.rs
@@ -135,6 +135,12 @@ pub async fn run_cli_with_config<W: Write>(
}
let rendered = if let Some(expression) = eval_expression.as_deref() {
+ if config.browser.layout_policy().uses_real_layout() {
+ page.publish_layout_async()
+ .await
+ .context("failed to publish layout before evaluating JavaScript")
+ .map_err(|error| with_fetch_context(error, &args.url))?;
+ }
eval_output::evaluate(&mut page, expression).await
} else {
fetch_dump::render_page_output_async(&mut page, &config.fetch).await
diff --git a/moli/src/cli.rs b/moli/src/cli.rs
index e8af1cfaa..6728874d4 100644
--- a/moli/src/cli.rs
+++ b/moli/src/cli.rs
@@ -581,6 +581,8 @@ pub struct CommonArgs {
pub disable_subframes: bool,
/// Enable the real on-demand layout renderer and screenshot surfaces.
+ /// With `fetch --eval` or `--eval-file`, refresh layout once before running
+ /// the script so geometry APIs can read it. Script mutations do not refresh it.
///
/// Without this flag Moli keeps deterministic compatibility
/// geometry and does not construct layout or paint output.
diff --git a/moli/tests/fetch_cli/eval.rs b/moli/tests/fetch_cli/eval.rs
index 4ed8d1e32..1926462a7 100644
--- a/moli/tests/fetch_cli/eval.rs
+++ b/moli/tests/fetch_cli/eval.rs
@@ -125,7 +125,56 @@ fn eval_can_use_realtime_audio_oscillator_and_analyser_shims() -> Result<()> {
}
#[test]
-fn eval_computed_sizes_only_use_existing_geometry_with_or_without_css() -> Result<()> {
+fn eval_with_layout_publishes_static_geometry() -> Result<()> {
+ let url = "data:text/html,<!doctype html><body style='margin:0'><div id=target style='position:absolute;left:20px;top:30px;width:120px;height:40px;overflow:hidden'>geometry<span style='display:block;height:200px'></span></div>";
+ let script = r#"(() => {
+ const target = document.getElementById('target');
+ const rect = target.getBoundingClientRect();
+ const range = document.createRange();
+ range.selectNodeContents(target.firstChild);
+ const rangeRect = range.getBoundingClientRect();
+ const selection = getSelection();
+ selection.removeAllRanges();
+ selection.addRange(range);
+ return {
+ rect: [rect.x, rect.y, rect.width, rect.height],
+ offset: [target.offsetWidth, target.offsetHeight],
+ client: [target.clientWidth, target.clientHeight],
+ scrolls: target.scrollHeight >= 200,
+ range: rangeRect.width > 0 && rangeRect.height > 0 && range.getClientRects().length > 0,
+ selection: selection.getRangeAt(0).getBoundingClientRect().width === rangeRect.width,
+ hit: document.elementFromPoint(25, 35)?.id,
+ computed: getComputedStyle(target).width
+ };
+ })()"#;
+ for args in [vec!["--layout"], vec!["--layout", "--disable-js"]] {
+ let output = run_eval(url, script, &args)?;
+ assert!(
+ output.status.success(),
+ "{args:?}: {}",
+ clean_output(&output.stderr)
+ );
+ let value: serde_json::Value = serde_json::from_slice(&output.stdout)?;
+ assert_eq!(
+ value,
+ serde_json::json!({
+ "rect": [20, 30, 120, 40],
+ "offset": [120, 40],
+ "client": [120, 40],
+ "scrolls": true,
+ "range": true,
+ "selection": true,
+ "hit": "target",
+ "computed": "120px"
+ }),
+ "{args:?}"
+ );
+ }
+ Ok(())
+}
+
+#[test]
+fn eval_computed_sizes_follow_layout_option_with_or_without_css() -> Result<()> {
let url = "data:text/html,<!doctype html><div id=target style=\"max-width:20px\"></div><canvas id=canvas style=\"max-width:40px\"></canvas>";
let script = r#"(() => {
const target = document.getElementById('target');
@@ -136,7 +185,7 @@ fn eval_computed_sizes_only_use_existing_geometry_with_or_without_css() -> Resul
const before = read();
const logicalBefore = readLogical();
const geometry = [target.offsetWidth, target.offsetHeight, canvas.offsetWidth, canvas.offsetHeight];
- return { before, logicalBefore, geometry, after: read(), logicalAfter: readLogical() };
+ return { before, logicalBefore, geometry, after: read(), logicalAfter: readLogical(), viewportWidth: innerWidth };
})()"#;
for args in [
vec![],
@@ -159,26 +208,89 @@ fn eval_computed_sizes_only_use_existing_geometry_with_or_without_css() -> Resul
value["logicalAfter"], value["after"],
"sampled axes: {args:?}"
);
- assert_eq!(
- value["before"],
- serde_json::json!(["auto", "auto", "auto", "auto"]),
- "width/height must not initiate layout: {args:?}: {value}"
- );
assert_eq!(
value["after"], value["before"],
"geometry reads cannot publish used sizes: {args:?}: {value}"
);
if args.contains(&"--layout") {
+ let sizes = if args.contains(&"--disable-css") {
+ [value["viewportWidth"].as_u64().unwrap() - 16, 0, 300, 150]
+ } else {
+ [20, 0, 40, 20]
+ };
assert_eq!(
value["geometry"],
- serde_json::json!([0, 0, 0, 0]),
- "real geometry is empty before an explicit output"
+ serde_json::json!(sizes),
+ "CLI must publish layout before eval: {args:?}"
+ );
+ assert_eq!(
+ value["before"],
+ serde_json::json!(sizes.map(|size| format!("{size}px"))),
+ "computed sizes must use the published layout: {args:?}"
+ );
+ } else {
+ assert_eq!(
+ value["before"],
+ serde_json::json!(["auto", "auto", "auto", "auto"]),
+ "eval without --layout must not publish used sizes: {args:?}"
);
}
}
Ok(())
}
+#[test]
+fn eval_with_layout_keeps_geometry_frozen_during_script() -> Result<()> {
+ let output = run_eval(
+ "data:text/html,<!doctype html><div id=target style='width:120px;height:40px'></div>",
+ r#"(() => {
+ const target = document.getElementById('target');
+ const before = target.offsetWidth;
+ target.style.width = '240px';
+ const added = document.createElement('div');
+ added.style.width = '50px';
+ document.body.appendChild(added);
+ return {
+ before,
+ after: target.getBoundingClientRect().width,
+ added: added.offsetWidth
+ };
+ })()"#,
+ &["--layout"],
+ )?;
+ assert!(output.status.success(), "{}", clean_output(&output.stderr));
+ let value: serde_json::Value = serde_json::from_slice(&output.stdout)?;
+ assert_eq!(
+ value,
+ serde_json::json!({ "before": 120, "after": 120, "added": 0 })
+ );
+ Ok(())
+}
+
+#[test]
+fn eval_file_with_layout_publishes_after_readiness() -> Result<()> {
+ let script_file = unique_temp_file_path("eval-file-layout", "geometry.js")?;
+ std::fs::write(
+ &script_file,
+ "document.getElementById('target').getBoundingClientRect().width",
+ )?;
+ let output = run_eval_file(
+ "data:text/html,<!doctype html><div id=target style='width:120px;height:40px'></div>",
+ &script_file,
+ &[
+ "--layout",
+ "--wait-script",
+ "() => { document.getElementById('target').style.width = '240px'; return true; }",
+ ],
+ )?;
+ if let Some(directory) = script_file.parent() {
+ let _ = std::fs::remove_dir_all(directory);
+ }
+ assert!(output.status.success(), "{}", clean_output(&output.stderr));
+ assert_eq!(clean_output(&output.stdout), "240\n");
+ Ok(())
+}
+
#[test]
fn eval_uses_standard_document_apis_and_writes_text() -> Result<()> {
let runtime = tokio::runtime::Runtime::new()?;