Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(screenshot): keep viewport fallback in page metrics
ldm05357eb622902
diff --git a/moli-cdp-smoke/README.md b/moli-cdp-smoke/README.mdindex 1bc566d4e..00689a8e9 100644--- a/moli-cdp-smoke/README.md+++ b/moli-cdp-smoke/README.md@@ -249,15 +249,21 @@ Covered well:asynchronous request cancellation, and suppression of asynchronous events andtimers 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). 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 `playwright-compat` group takes viewport, clipped, and full-page+- The default `playwright-compat` group takes viewport and clippedscreenshots through `page.screenshot()` on fresh pages, without a raw CDP capture first.This covers Playwright's `Page.getLayoutMetrics` preflight before layout hasbeen published. DPR/resize and concurrent-page screenshot cases likewise usePlaywright directly, so a fixture cannot hide a broken first screenshot.- In Moli, before the first layout publication, the document's client dimensions default- to the configured viewport, so a first `fullPage: true` capture covers one- viewport. The next full-page capture uses the published content dimensions;- the smoke test checks both captures on a page taller than the viewport.+ In Moli, before the first layout publication, DOM dimensions remain zero,+ while `Page.getLayoutMetrics.cssContentSize` falls back to the configured+ viewport. Clients can use those page metrics to submit a positive screenshot+ clip. Empty clips are rejected regardless of layout publication state.+ Playwright computes its own full-page clip from DOM dimensions, so a cold+ `fullPage: true` request fails. The smoke test checks that rejection leaves+ geometry unpublished, then verifies viewport output and subsequent full-page+ and full-page clip output on a tall page. CLI `moli fetch --layout --dump+ screenshot_full` directly requests full-document output and works on the+ first capture without a DOM-size preflight.- The default raw `action-window` group holds Moli's on-demand input policy atthe public CDP boundary. Three acknowledged `Input.dispatchMouseEvent`wheel commands remain delayed until one fixed one-second deadline, preservediff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/playwright_compat.py b/moli-cdp-smoke/moli_cdp_smoke/groups/playwright_compat.pyindex cdc9ec7c4..2e1e12190 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/playwright_compat.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/playwright_compat.py@@ -35,12 +35,6 @@ async def _verify_playwright_first_screenshot(state: SmokeState) -> None:for name, options, size in [("viewport", {}, (320, 240)),("clip", {"clip": {"x": 10, "y": 15, "width": 60, "height": 50}}, (60, 50)),- ("full-page", {"full_page": True}, (320, 240)),- (- "full-page-clip",- {"full_page": True, "clip": {"x": 10, "y": 15, "width": 60, "height": 50}},- (60, 50),- ),]:page = await state.context.new_page()try:@@ -51,12 +45,40 @@ async def _verify_playwright_first_screenshot(state: SmokeState) -> None:wait_until="load",timeout=10_000,)+ assert_equal(+ await page.evaluate("""() => [+ document.documentElement.clientWidth,+ document.documentElement.clientHeight,+ document.querySelector('div').getBoundingClientRect().width+ ]"""),+ [0, 0, 0],+ f"unpublished geometry before first Playwright {name} screenshot",+ )+ if name == "viewport":+ # Playwright derives fullPage clips from DOM dimensions, which+ # are zero before publication. CDP must reject that empty clip.+ try:+ await page.screenshot(full_page=True, timeout=10_000)+ except Exception as error:+ if "positive finite width, height, and scale" not in str(error):+ raise SmokeError(f"unexpected cold full-page error: {error}") from error+ else:+ raise SmokeError("cold Playwright full-page screenshot should reject its empty clip")+ assert_equal(+ await page.evaluate("""() => [+ document.documentElement.clientWidth,+ document.documentElement.clientHeight,+ document.querySelector('div').getBoundingClientRect().width+ ]"""),+ [0, 0, 0],+ "rejected full-page screenshot must not publish layout",+ )image = decode_png(await page.screenshot(timeout=10_000, **options))assert_equal((image.width, image.height), size, f"first Playwright {name} screenshot size")assert_equal(image.pixel(5, 5), (20, 30, 40, 255), f"first Playwright {name} screenshot pixel")- if name == "full-page":- # The first capture publishes layout. The next full-page- # request must use the real content extent, not the fallback.+ if name == "viewport":+ # A successful viewport capture publishes the DOM dimensions+ # used by subsequent Playwright full-page requests.full_image = decode_png(await page.screenshot(full_page=True, timeout=10_000))assert_equal(full_image.height, 900, "published Playwright full-page screenshot height")assert_equal(@@ -64,11 +86,24 @@ async def _verify_playwright_first_screenshot(state: SmokeState) -> None:(20, 30, 40, 255),"published Playwright full-page bottom pixel",)+ # Playwright clips against DOM dimensions before sending CDP.+ # A full-page clip therefore needs a previously published frame.+ clipped = decode_png(await page.screenshot(+ full_page=True,+ clip={"x": 10, "y": 15, "width": 60, "height": 50},+ timeout=10_000,+ ))+ assert_equal((clipped.width, clipped.height), (60, 50), "published full-page clip size")+ assert_equal(clipped.pixel(5, 5), (20, 30, 40, 255), "published full-page clip pixel")finally:await page.close()state.record("playwright_first_screenshot_without_published_layout",- {"modes": ["viewport", "clip", "full-page", "full-page-clip"]},+ {+ "modes": ["viewport", "clip"],+ "rejected_unpublished_modes": ["full-page"],+ "published_modes": ["full-page", "full-page-clip"],+ },)diff --git a/moli-protocol/src/domains/page/tests/capture.rs b/moli-protocol/src/domains/page/tests/capture.rsindex bbe8e6245..e906b8371 100644--- a/moli-protocol/src/domains/page/tests/capture.rs+++ b/moli-protocol/src/domains/page/tests/capture.rs@@ -378,6 +378,26 @@ async fn capture_screenshot_rejects_invalid_quality_and_clip() {json!({"clip": {"x": 0, "y": 0, "width": 0, "height": 1, "scale": 1}}),"Page.captureScreenshot clip must have a finite origin and positive finite width, height, and scale.",),+ (+ 20,+ json!({"clip": {"x": 1, "y": 0, "width": 0, "height": 0, "scale": 1}}),+ "Page.captureScreenshot clip must have a finite origin and positive finite width, height, and scale.",+ ),+ (+ 21,+ json!({"clip": {"x": 0, "y": 0, "width": -1, "height": -1, "scale": 1}}),+ "Page.captureScreenshot clip must have a finite origin and positive finite width, height, and scale.",+ ),+ (+ 22,+ json!({"clip": {"x": 0, "y": 0, "width": 0, "height": 0, "scale": 0}}),+ "Page.captureScreenshot clip must have a finite origin and positive finite width, height, and scale.",+ ),+ (+ 23,+ json!({"clip": {"x": 0, "y": 0, "width": 0, "height": 0, "scale": 1}}),+ "Page.captureScreenshot clip must have a finite origin and positive finite width, height, and scale.",+ ),] {ctx.process_async(json!({"id": id,@@ -1113,6 +1133,105 @@ async fn get_layout_metrics_before_first_screenshot_does_not_publish_layout() {assert_eq!(live["result"]["contentSize"]["height"], 900.0);}+#[tokio::test(flavor = "multi_thread")]+async fn full_page_clip_from_layout_metrics_preserves_geometry_until_capture() {+ for (dpr, scale, beyond, width, height) in [+ (1.0, 1.0, false, 320, 240),+ (2.0, 1.0, false, 640, 480),+ (2.0, 0.5, true, 320, 240),+ ] {+ let mut ctx = TestContext::new();+ let session = "SID-COLD-FULL-SCREENSHOT";+ install_active_screenshot_page(+ &mut ctx,+ "BID-COLD-FULL-SCREENSHOT",+ "TID-COLD-FULL-SCREENSHOT",+ session,+ &screenshot_data_url("<!doctype html><style>html,body{margin:0}main{width:80px;height:900px;background:rgb(20,30,40)}</style><main></main>"),+ ).await;+ set_screenshot_viewport(&mut ctx, session, 320, 240, dpr, 120).await;++ let geometry = json!({+ "id":121,"method":"Runtime.evaluate","sessionId":session,+ "params":{+ "expression":"[document.documentElement.clientWidth,document.documentElement.clientHeight,document.querySelector('main').getBoundingClientRect().width]",+ "returnByValue":true+ }+ });+ ctx.process_async(geometry.clone()).await;+ assert_eq!(+ take_response_by_id(&mut ctx, 121)["result"]["result"]["value"],+ json!([0, 0, 0])+ );++ // Empty clips are invalid both before and after layout publication.+ let empty_capture = json!({+ "id":122,"method":"Page.captureScreenshot","sessionId":session,+ "params":{"format":"png","captureBeyondViewport":beyond,+ "clip":{"x":0,"y":0,"width":0,"height":0,"scale":scale}}+ });+ ctx.process_async(empty_capture.clone()).await;+ let cold_error = take_response_by_id(&mut ctx, 122);+ assert_eq!(cold_error["error"]["code"], -32602, "{cold_error}");++ ctx.process_async(json!({+ "id":123,"method":"Page.getLayoutMetrics","sessionId":session+ }))+ .await;+ let unpublished = take_response_by_id(&mut ctx, 123);+ let mut clip = unpublished["result"]["cssContentSize"].clone();+ assert_eq!(clip, json!({"x":0,"y":0,"width":320.0,"height":240.0}));+ clip["scale"] = json!(scale);++ // The page-size fallback and rejected capture must leave DOM geometry+ // unpublished. The caller supplies a positive clip to the screenshot.+ ctx.process_async(geometry.clone()).await;+ assert_eq!(+ take_response_by_id(&mut ctx, 121)["result"]["result"]["value"],+ json!([0, 0, 0])+ );+ ctx.process_async(json!({+ "id":122,"method":"Page.captureScreenshot","sessionId":session,+ "params":{"format":"png","captureBeyondViewport":beyond,"clip":clip}+ }))+ .await;+ let png = screenshot_bytes(&take_response_by_id(&mut ctx, 122));+ assert_png_dimensions(&png, width, height);+ assert_eq!(decode_png_pixel(&png, 10, 10), [20, 30, 40, 255]);++ ctx.process_async(geometry).await;+ assert_eq!(+ take_response_by_id(&mut ctx, 121)["result"]["result"]["value"][2],+ 80+ );+ ctx.process_async(json!({+ "id":123,"method":"Page.getLayoutMetrics","sessionId":session+ }))+ .await;+ let published = take_response_by_id(&mut ctx, 123);+ assert_eq!(published["result"]["contentSize"]["height"], 900.0);++ ctx.process_async(empty_capture).await;+ let rejected = take_response_by_id(&mut ctx, 122);+ assert_eq!(rejected["error"], cold_error["error"]);++ let mut full_clip = published["result"]["cssContentSize"].clone();+ full_clip["scale"] = json!(scale);+ ctx.process_async(json!({+ "id":124,"method":"Page.captureScreenshot","sessionId":session,+ "params":{"captureBeyondViewport":true,"clip":full_clip}+ }))+ .await;+ let full = screenshot_bytes(&take_response_by_id(&mut ctx, 124));+ let full_height = (900.0 * dpr * scale) as u32;+ assert_png_dimensions(&full, width, full_height);+ assert_eq!(+ decode_png_pixel(&full, 10, full_height - 10),+ [20, 30, 40, 255]+ );+ }+}+/// cdp.page: getLayoutMetrics – falls back to viewport metrics without a live page#[tokio::test(flavor = "multi_thread")]async fn get_layout_metrics() {diff --git a/moli-renderer-v8/src/native_bridge/element/geometry/metrics.rs b/moli-renderer-v8/src/native_bridge/element/geometry/metrics.rsindex 5e09f7d36..82143c2ba 100644--- a/moli-renderer-v8/src/native_bridge/element/geometry/metrics.rs+++ b/moli-renderer-v8/src/native_bridge/element/geometry/metrics.rs@@ -256,14 +256,11 @@ fn node_box_metric_from_object<'s>(metric: &str,) -> Result<i32, moli_layout::LayoutError> {if let Ok((runtime_ptr, handle)) = node_runtime_and_handle_from_object(scope, object) {- let runtime = unsafe { &*runtime_ptr };- let metrics = read_element_metrics(runtime, handle)?;+ let metrics = read_element_metrics(unsafe { &*runtime_ptr }, handle)?;return Ok(metrics.as_ref().map(|metrics| layout_box_metric(metrics, metric))- .unwrap_or_else(|| {- unpublished_document_client_metric(runtime, handle, metric).unwrap_or(0)- }));+ .unwrap_or(0));}let Ok((runtime_ptr, handle)) = node_runtime_and_handle_from_object_or_detached(scope, object)else {@@ -283,44 +280,6 @@ fn node_box_metric_from_object<'s>(}}-fn unpublished_document_client_metric(- runtime: &JsContextHost,- handle: DomHandle,- metric: &str,-) -> Option<i32> {- if !matches!(metric, "clientWidth" | "clientHeight")- || !runtime.layout_policy().uses_real_layout()- || !runtime.dom_host().is_connected(handle)- {- return None;- }- let document = runtime.layout_document_for_source(handle)?;- if runtime- .dom_host()- .dom()- .document_element_handle_for_document(document)- != Some(handle)- || (document != runtime.document_handle()- && runtime- .child_browsing_context_host_for_document_handle(document)- .is_none())- || runtime- .with_latest_layout_tree_for_document(document, |_| ())- .is_some()- {- return None;- }- // Before the first visual publication, use the configured viewport as the- // document's client size. Content bounds and element boxes still need a- // snapshot; a published zero-sized box must not acquire this fallback.- let viewport = runtime.layout_viewport_for_document(document);- Some(rounded_layout_value(if metric == "clientWidth" {- viewport.css_width as f32- } else {- viewport.css_height as f32- }))-}-fn layout_box_metric(metrics: &moli_layout::LayoutElementMetrics<DomHandle>, metric: &str) -> i32 {rounded_layout_value(match metric {"clientWidth" => metrics.client_size.width,diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface.rsindex e7d3376eb..35c0fc985 100644--- a/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface.rs+++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface.rs@@ -1383,7 +1383,7 @@ fn painted_overlay_wins_over_scrollbar_and_corner_consumes_input() {}#[test]-fn document_client_size_defaults_to_viewport_without_publishing_layout() {+fn document_client_size_requires_published_layout() {let mut vm = new_parsed_test_vm("https://document-client-viewport.test/","<!doctype html><style>html,body{margin:0}main{width:80px;height:900px}</style><main></main>",@@ -1403,10 +1403,7 @@ fn document_client_size_defaults_to_viewport_without_publishing_layout() {..Default::default()})).unwrap();- assert_eq!(- vm.eval(query).unwrap(),- format!("[{width},{height},0,0,0,0,0]")- );+ assert_eq!(vm.eval(query).unwrap(), "[0,0,0,0,0,0,0]");assert_eq!(vm.layout_pass_observability_for_test().1, initial_passes);}diff --git a/moli/src/fetch_dump/tests.rs b/moli/src/fetch_dump/tests.rsindex a1599c989..73240abaf 100644--- a/moli/src/fetch_dump/tests.rs+++ b/moli/src/fetch_dump/tests.rs@@ -67,18 +67,19 @@ async fn render_full_page_screenshot_extends_beyond_viewport() -> Result<()> {).await?;- let viewport = render_page_output_async(+ // Full-document output must work before any other capture publishes layout.+ let full_page = render_page_output_async(&mut page,&FetchCommandConfig {- dump_mode: Some(DumpFormat::Screenshot),+ dump_mode: Some(DumpFormat::ScreenshotFull),..FetchCommandConfig::default()},).await?;- let full_page = render_page_output_async(+ let viewport = render_page_output_async(&mut page,&FetchCommandConfig {- dump_mode: Some(DumpFormat::ScreenshotFull),+ dump_mode: Some(DumpFormat::Screenshot),..FetchCommandConfig::default()},)@@ -86,6 +87,7 @@ async fn render_full_page_screenshot_extends_beyond_viewport() -> Result<()> {let viewport_dimensions = png_dimensions(&viewport);let full_page_dimensions = png_dimensions(&full_page);+ assert_eq!(full_page_dimensions.1, 1300);assert_eq!(full_page_dimensions.0, viewport_dimensions.0);assert!(full_page_dimensions.1 > viewport_dimensions.1);diff --git a/moli/tests/fetch_cli.rs b/moli/tests/fetch_cli.rsindex a6519b3b8..50f1b0401 100644--- a/moli/tests/fetch_cli.rs+++ b/moli/tests/fetch_cli.rs@@ -1099,8 +1099,10 @@ fn cli_fetch_implicit_html_dump_is_quiet_by_default() -> Result<()> {}#[test]-fn cli_dump_full_screenshot_writes_png_bytes() -> Result<()> {- let output = run_fetch_cli_with_dump_and_args("about:blank", "screenshot_full", &["--layout"])?;+fn cli_dump_full_screenshot_captures_tall_page_without_prior_layout() -> Result<()> {+ let html = "<!doctype html><style>html,body{margin:0}main{height:1600px;background:blue}</style><main></main>";+ let url = format!("data:text/html;base64,{}", BASE64_STANDARD.encode(html));+ let output = run_fetch_cli_with_dump_and_args(&url, "screenshot_full", &["--layout"])?;assert!(output.status.success(),"moli fetch failed: stdout_bytes={}\nstderr={}",@@ -1109,6 +1111,11 @@ fn cli_dump_full_screenshot_writes_png_bytes() -> Result<()> {);assert!(output.stdout.starts_with(b"\x89PNG\r\n\x1a\n"));assert!(output.stdout.ends_with(b"IEND\xaeB`\x82"));+ assert_eq!(+ u32::from_be_bytes(output.stdout[20..24].try_into().unwrap()),+ 1600,+ "full screenshot must include content below the default viewport"+ );Ok(())}