The headless browser for AI agents and web scraping
Strengthen paired render verification
SGavrl38e53730c453
diff --git a/render-repros/check.py b/render-repros/check.pyindex 240f932d..3e6fe0c7 100755--- a/render-repros/check.py+++ b/render-repros/check.py@@ -5,6 +5,8 @@ Behavior assertions are based on solid-color component geometry, so fontanti-aliasing does not decide pass/fail. Pair metrics are diagnostics only:they use the full equal-sized canvas with no registration, cropping, blank-pageexclusion, or opaque aggregate "parity" verdict.+Structural diagnostics include both lossy row/column projections and a+bidirectional nearest-edge distance that preserves two-dimensional placement."""import json@@ -13,7 +15,14 @@ from pathlib import Pathimport numpy as npfrom PIL import Image-from scipy.ndimage import find_objects, gaussian_filter, gaussian_filter1d, label, sobel+from scipy.ndimage import (+ distance_transform_edt,+ find_objects,+ gaussian_filter,+ gaussian_filter1d,+ label,+ sobel,+)def rgb(value):@@ -60,6 +69,41 @@ def structural_edges(array):return magnitude > 48.0+def bidirectional_edge_distance(ours_edges, chromium_edges):+ """Return symmetric nearest-edge distances in native CSS-pixel space.++ Row and column projections intentionally discard the other coordinate, so+ two layouts can have identical projections while their boxes occupy+ different quadrants. A distance transform retains both coordinates. Each+ engine contributes equally instead of allowing the denser edge map to+ dominate the score.+ """+ ours_count = int(ours_edges.sum())+ chromium_count = int(chromium_edges.sum())+ if ours_count == 0 and chromium_count == 0:+ return {+ "edge_bidirectional_mean_distance_px": 0.0,+ "edge_bidirectional_p95_distance_px": 0.0,+ }+ if ours_count == 0 or chromium_count == 0:+ return {+ "edge_bidirectional_mean_distance_px": None,+ "edge_bidirectional_p95_distance_px": None,+ }++ distance_to_chromium = distance_transform_edt(~chromium_edges)[ours_edges]+ distance_to_ours = distance_transform_edt(~ours_edges)[chromium_edges]+ mean_distance = (distance_to_chromium.mean() + distance_to_ours.mean()) / 2.0+ p95_distance = (+ np.percentile(distance_to_chromium, 95)+ + np.percentile(distance_to_ours, 95)+ ) / 2.0+ return {+ "edge_bidirectional_mean_distance_px": round(float(mean_distance), 6),+ "edge_bidirectional_p95_distance_px": round(float(p95_distance), 6),+ }++def pair_metrics(ours, chromium):if ours.shape != chromium.shape:return {"size_mismatch": [list(ours.shape), list(chromium.shape)]}@@ -103,7 +147,8 @@ def pair_metrics(ours, chromium):)edge_row_projection = float(np.abs(ours_edge_rows - chromium_edge_rows).mean() / width)edge_col_projection = float(np.abs(ours_edge_cols - chromium_edge_cols).mean() / height)- return {+ edge_distance = bidirectional_edge_distance(ours_edges, chromium_edges)+ metrics = {"rgb_mae": round(float(delta.mean() / 255.0), 6),"pixels_gt_10": round(float((max_channel > 10).mean()), 6),"pixels_gt_50": round(float((max_channel > 50).mean()), 6),@@ -118,6 +163,8 @@ def pair_metrics(ours, chromium):"edge_row_projection_delta": round(edge_row_projection, 6),"edge_column_projection_delta": round(edge_col_projection, 6),}+ metrics.update(edge_distance)+ return metricsdef main():@@ -171,7 +218,8 @@ def main():f"p>50={metrics.get('pixels_gt_50', '-'):>8} "f"edge_bbox={metrics.get('edge_bbox_max_delta', '-'):>3} "f"edge_row={metrics.get('edge_row_projection_delta', '-'):>8} "- f"edge_col={metrics.get('edge_column_projection_delta', '-'):>8}"+ f"edge_col={metrics.get('edge_column_projection_delta', '-'):>8} "+ f"edge_2d={metrics.get('edge_bidirectional_mean_distance_px', '-'):>8}")report["failures"] = failuresdiff --git a/render-repros/checks.json b/render-repros/checks.jsonindex 9a899669..3b3e2bf5 100644--- a/render-repros/checks.json+++ b/render-repros/checks.json@@ -126,6 +126,12 @@{"name": "grid shorthand creates explicit columns", "color": "#087f5b", "width": 287, "height": 60, "count": 3},{"name": "custom property grid shorthand creates explicit columns", "color": "#1971c2", "width": 287, "height": 60, "count": 3}],+ "img-density-and-alt": [+ {"name": "raw intrinsic image keeps its 648 CSS pixel width", "color": "#ff0000", "width": 652},+ {"name": "2x density descriptor halves the intrinsic CSS width", "color": "#ff0000", "width": 328},+ {"name": "width descriptor and sizes establish a 300 pixel source size", "color": "#ff0000", "width": 304},+ {"name": "overflow viewport retains its fixed border geometry", "color": "#ff0000", "width": 304, "height": 104}+ ],"inline-block-flex-items": [{"name": "inline block title keeps its max content width", "color": "#087f5b", "x": 32, "y": 0, "width": 350, "height": 20},{"name": "inline block list shrink wraps and stacks children", "color": "#1971c2", "x": 525, "y": 0, "width": 90, "height": 60},@@ -203,6 +209,10 @@{"name": "opposing float shares the same band", "color": "#e8590c", "x": 600, "y": 60, "width": 300, "height": 40},{"name": "cleared navigation follows the float band", "color": "#087f5b", "x": 0, "y": 100, "width": 900, "height": 50}],+ "percentage-height-indefinite-parent": [+ {"name": "content sizes the indefinite percentage-height chain", "color": "#087f5b", "x": 0, "y": 0, "height": 24},+ {"name": "following flow starts after the content-sized chain", "color": "#e8590c", "x": 0, "y": 24, "width": 400, "height": 20}+ ],"relative-box-edges": [{"name": "vh margin resolves against viewport height", "color": "#087f5b", "x": 0, "y": 150, "width": 100, "height": 40},{"name": "vw margin resolves against viewport width", "color": "#1971c2", "x": 90, "y": 200, "width": 100, "height": 40},diff --git a/render-repros/img-density-and-alt.html b/render-repros/img-density-and-alt.htmlindex 8da51dee..50c6db1c 100644--- a/render-repros/img-density-and-alt.html+++ b/render-repros/img-density-and-alt.html@@ -1,18 +1,18 @@<!DOCTYPE html><html><head><title>img density + alt</title><style>body{margin:0;font-family:sans-serif}.box{border:2px solid red;margin:6px;display:inline-block}</style></head><body><p>Density: A raw 648px, B srcset 2x -> ~324 CSS px, C 648w + sizes:300px -> ~300px</p>-<div><span>A:</span><div class="box"><img src="https://web.dev/static/images/ai-feature.png"></div></div>-<div><span>B:</span><div class="box"><img srcset="https://web.dev/static/images/ai-feature.png 2x"></div></div>-<div><span>C:</span><div class="box"><img srcset="https://web.dev/static/images/ai-feature.png 648w" sizes="300px"></div></div>+<div><span>A:</span><div class="box"><img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2NDgiIGhlaWdodD0iMTIwIiB2aWV3Qm94PSIwIDAgNjQ4IDEyMCI+CiAgPHJlY3Qgd2lkdGg9IjY0OCIgaGVpZ2h0PSIxMjAiIGZpbGw9IiMyODZmOWUiLz4KICA8cmVjdCB4PSIyNCIgeT0iMjQiIHdpZHRoPSI2MDAiIGhlaWdodD0iNzIiIGZpbGw9IiM4ZWNhZTYiLz4KPC9zdmc+Cg=="></div></div>+<div><span>B:</span><div class="box"><img srcset="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2NDgiIGhlaWdodD0iMTIwIiB2aWV3Qm94PSIwIDAgNjQ4IDEyMCI+CiAgPHJlY3Qgd2lkdGg9IjY0OCIgaGVpZ2h0PSIxMjAiIGZpbGw9IiMyODZmOWUiLz4KICA8cmVjdCB4PSIyNCIgeT0iMjQiIHdpZHRoPSI2MDAiIGhlaWdodD0iNzIiIGZpbGw9IiM4ZWNhZTYiLz4KPC9zdmc+Cg== 2x"></div></div>+<div><span>C:</span><div class="box"><img srcset="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2NDgiIGhlaWdodD0iMTIwIiB2aWV3Qm94PSIwIDAgNjQ4IDEyMCI+CiAgPHJlY3Qgd2lkdGg9IjY0OCIgaGVpZ2h0PSIxMjAiIGZpbGw9IiMyODZmOWUiLz4KICA8cmVjdCB4PSIyNCIgeT0iMjQiIHdpZHRoPSI2MDAiIGhlaWdodD0iNzIiIGZpbGw9IiM4ZWNhZTYiLz4KPC9zdmc+Cg== 648w" sizes="300px"></div></div><p>Broken-image fallback: D alt text only, E alt="" nothing, F no alt -> grey box</p>-<div>D: <img src="https://web.dev/nope-404.png" alt="a description of the missing photo" style="width:200px;height:60px"></div>-<div>E: <img src="https://web.dev/nope-404.png" alt="" style="width:200px;height:60px"></div>-<div>F: <img src="https://web.dev/nope-404.png" style="width:200px;height:60px"></div>+<div>D: <img src="missing-image.png" alt="a description of the missing photo" style="width:200px;height:60px"></div>+<div>E: <img src="missing-image.png" alt="" style="width:200px;height:60px"></div>+<div>F: <img src="missing-image.png" style="width:200px;height:60px"></div><p>G: cover img half-outside an overflow:hidden viewport must not bleed past the red border:</p><div style="width:300px;height:100px;overflow:hidden;border:2px solid red;margin-left:120px"><div style="display:flex;transform:translate(-150px,0)">- <img src="https://web.dev/static/images/ai-feature.png" style="width:300px;height:100px;object-fit:cover;flex-shrink:0">- <img src="https://web.dev/static/images/ai-feature.png" style="width:300px;height:100px;object-fit:cover;flex-shrink:0">+ <img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2NDgiIGhlaWdodD0iMTIwIiB2aWV3Qm94PSIwIDAgNjQ4IDEyMCI+CiAgPHJlY3Qgd2lkdGg9IjY0OCIgaGVpZ2h0PSIxMjAiIGZpbGw9IiMyODZmOWUiLz4KICA8cmVjdCB4PSIyNCIgeT0iMjQiIHdpZHRoPSI2MDAiIGhlaWdodD0iNzIiIGZpbGw9IiM4ZWNhZTYiLz4KPC9zdmc+Cg==" style="width:300px;height:100px;object-fit:cover;flex-shrink:0">+ <img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2NDgiIGhlaWdodD0iMTIwIiB2aWV3Qm94PSIwIDAgNjQ4IDEyMCI+CiAgPHJlY3Qgd2lkdGg9IjY0OCIgaGVpZ2h0PSIxMjAiIGZpbGw9IiMyODZmOWUiLz4KICA8cmVjdCB4PSIyNCIgeT0iMjQiIHdpZHRoPSI2MDAiIGhlaWdodD0iNzIiIGZpbGw9IiM4ZWNhZTYiLz4KPC9zdmc+Cg==" style="width:300px;height:100px;object-fit:cover;flex-shrink:0"></div></div></body></html>diff --git a/render-repros/paired-corpus.py b/render-repros/paired-corpus.pyindex 8c33bb31..33e1ac6d 100755--- a/render-repros/paired-corpus.py+++ b/render-repros/paired-corpus.py@@ -4,19 +4,24 @@Every run uses a new output directory, checks process status and non-emptyscreenshots, records browser versions and timings, and reports raw full-canvaspixel diagnostics plus background-tolerant structural-edge diagnostics from-check.py. It deliberately emits no aggregate parity verdict. An optional-pre-change Obscura binary can be captured concurrently so regressions are-compared against the same live-page moment.+check.py. Browser identity is pinned and Chromium's DOM/text fingerprints,+viewport geometry, and resource-readiness state are recorded at capture time.+It deliberately emits no aggregate parity verdict. An optional pre-change+Obscura binary can be captured concurrently so regressions are compared+against the same live-page moment."""import argparseimport concurrent.futures+import hashlibimport jsonimport osimport reimport subprocessimport sys+import tempfileimport time+import urllib.parsefrom datetime import datetime, timezonefrom pathlib import Path@@ -27,6 +32,36 @@ from playwright.sync_api import sync_playwrightfrom check import pair_metrics+CANONICAL_USER_AGENT = (+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "+ "AppleWebKit/537.36 (KHTML, like Gecko) "+ "Chrome/143.0.0.0 Safari/537.36"+)+CANONICAL_PLATFORM = "Win32"+CANONICAL_UA_PLATFORM = "Windows"+CANONICAL_UA_PLATFORM_VERSION = "10.0.0"+CANONICAL_OBSCURA_PROFILE = 0+CANONICAL_COLOR_SCHEME = "light"+# Obscura currently models the default motion preference, not `reduce`.+CANONICAL_REDUCED_MOTION = "no-preference"+EXPECTED_MEDIA_MATCHES = {+ "prefers_color_scheme_light": True,+ "prefers_color_scheme_dark": False,+ "prefers_reduced_motion_no_preference": True,+ "prefers_reduced_motion_reduce": False,+}+GREASE_CHARS = [" ", "(", ":", "-", ".", "/", ")", ";", "=", "?", "_"]+GREASE_VERSIONS = ["8", "99", "24"]+BRAND_PERMUTATIONS = [+ [0, 1, 2],+ [0, 2, 1],+ [1, 0, 2],+ [1, 2, 0],+ [2, 0, 1],+ [2, 1, 0],+]++def slug(url):value = re.sub(r"[^a-z0-9]+", "-", url.lower()).strip("-")return value[:80] or "page"@@ -48,7 +83,83 @@ def diagnostic_text(value):return value-def capture_obscura(binary, url, screenshot, log, width, height, settle_ms):+def media_matches_configured(media):+ return all(media.get(key) is expected for key, expected in EXPECTED_MEDIA_MATCHES.items())+++def parse_scroll_y(value):+ if value == "bottom":+ return value+ try:+ return int(value)+ except ValueError as error:+ raise argparse.ArgumentTypeError(+ "--scroll-y must be an integer CSS-pixel offset or 'bottom'"+ ) from error+++def scroll_eval_expression(scroll):+ if scroll is None:+ return None+ scroll_x, scroll_y = scroll+ requested_y = (+ "document.documentElement.scrollHeight"+ if scroll_y == "bottom"+ else str(scroll_y)+ )+ return (+ "(()=>{"+ f"const requestedX={scroll_x},requestedY={requested_y};"+ "window.scrollTo(requestedX,requestedY);"+ "return JSON.stringify({"+ "requested:{x:requestedX,y:requestedY},"+ "actual:{x:window.scrollX,y:window.scrollY},"+ "viewport:{width:innerWidth,height:innerHeight},"+ "content:{width:document.documentElement.scrollWidth,"+ "height:document.documentElement.scrollHeight}"+ "})"+ "})()"+ )+++def parse_obscura_scroll_report(stdout):+ for line in reversed(stdout.splitlines()):+ try:+ report = json.loads(line)+ except json.JSONDecodeError:+ continue+ if not isinstance(report, dict) or not isinstance(+ report.get("captureState"), dict+ ):+ continue+ evaluated = report.get("evaluation")+ if isinstance(evaluated, str):+ try:+ evaluated = json.loads(evaluated)+ except json.JSONDecodeError:+ evaluated = None+ capture = report["captureState"]+ requested = evaluated.get("requested") if isinstance(evaluated, dict) else None+ return {+ "requested": requested,+ "actual": {+ "x": capture.get("scrollX"),+ "y": capture.get("scrollY"),+ },+ "viewport": {+ "width": capture.get("innerWidth"),+ "height": capture.get("innerHeight"),+ },+ "content": {+ "width": capture.get("scrollWidth"),+ "height": capture.get("scrollHeight"),+ },+ "sampled_phase": "immediately-before-screenshot",+ }+ return None+++def obscura_environment(width, height):env = dict(os.environ,OBSCURA_SHOT_W=str(width),@@ -61,11 +172,135 @@ def capture_obscura(binary, url, screenshot, log, width, height, settle_ms):# Match Playwright's 50-second goto allowance. This is the browser# engine's millisecond ceiling, distinct from the CLI's seconds unit.OBSCURA_NAV_TIMEOUT_MS="50000",+ # Pin the navigator platform/profile as well as the explicit UA. A+ # randomized platform changes responsive content and font selection,+ # making a renderer comparison answer the wrong question.+ OBSCURA_PROFILE=str(CANONICAL_OBSCURA_PROFILE),+ )+ return env+++def probe_obscura_identity(binary):+ expression = (+ "JSON.stringify({userAgent:navigator.userAgent,"+ "platform:navigator.platform,"+ "uaPlatform:navigator.userAgentData&&navigator.userAgentData.platform,"+ "uaBrands:navigator.userAgentData&&navigator.userAgentData.brands,"+ "media:{"+ "prefers_color_scheme_light:matchMedia('(prefers-color-scheme: light)').matches,"+ "prefers_color_scheme_dark:matchMedia('(prefers-color-scheme: dark)').matches,"+ "prefers_reduced_motion_no_preference:matchMedia('(prefers-reduced-motion: no-preference)').matches,"+ "prefers_reduced_motion_reduce:matchMedia('(prefers-reduced-motion: reduce)').matches"+ "}})")+ command = [+ binary,+ "fetch",+ "data:text/html,<title>identity-probe</title>",+ "--user-agent",+ CANONICAL_USER_AGENT,+ "--eval",+ expression,+ "--timeout",+ "5",+ "--wait",+ "0",+ "--quiet",+ ]+ env = obscura_environment(1, 1)+ try:+ result = subprocess.run(+ command, capture_output=True, text=True, timeout=15, env=env+ )+ raw = result.stdout.strip()+ effective = json.loads(raw) if result.returncode == 0 else None+ return {+ "ok": result.returncode == 0,+ "status": result.returncode,+ "effective": effective,+ "media_matches_configured": (+ media_matches_configured(effective.get("media", {}))+ if effective+ else False+ ),+ "diagnostic": result.stderr.strip() or None,+ }+ except (subprocess.TimeoutExpired, json.JSONDecodeError) as error:+ return {"ok": False, "status": "probe-error", "diagnostic": str(error)}+++def probe_obscura_css_media(binary):+ """Verify the renderer's CSS media evaluator, not only JS matchMedia."""+ html = """<!doctype html><style>+ html,body{margin:0}+ #scheme,#motion{position:fixed;top:0;width:4px;height:4px;background:#ff00ff}+ #scheme{left:0} #motion{left:4px}+ @media (prefers-color-scheme:light){#scheme{background:#00ff00}}+ @media (prefers-color-scheme:dark){#scheme{background:#ff0000}}+ @media (prefers-reduced-motion:no-preference){#motion{background:#0000ff}}+ @media (prefers-reduced-motion:reduce){#motion{background:#ffff00}}+ </style><div id=scheme></div><div id=motion></div>"""+ url = "data:text/html," + urllib.parse.quote(html, safe="")+ with tempfile.TemporaryDirectory(prefix="obscura-media-probe-") as directory:+ screenshot = Path(directory) / "probe.png"+ command = [+ binary,+ "fetch",+ url,+ "--user-agent",+ CANONICAL_USER_AGENT,+ "--screenshot",+ str(screenshot),+ "--timeout",+ "5",+ "--wait",+ "0",+ "--quiet",+ ]+ try:+ result = subprocess.run(+ command,+ capture_output=True,+ text=True,+ timeout=15,+ env=obscura_environment(8, 4),+ )+ if result.returncode != 0 or not screenshot.is_file():+ return {+ "ok": False,+ "status": result.returncode,+ "diagnostic": result.stderr.strip() or "missing probe screenshot",+ }+ image = Image.open(screenshot).convert("RGB")+ scheme = list(image.getpixel((1, 1)))+ motion = list(image.getpixel((5, 1)))+ expected = {"color_scheme": [0, 255, 0], "reduced_motion": [0, 0, 255]}+ actual = {"color_scheme": scheme, "reduced_motion": motion}+ return {+ "ok": actual == expected,+ "status": result.returncode,+ "configured": {+ "color_scheme": CANONICAL_COLOR_SCHEME,+ "reduced_motion": CANONICAL_REDUCED_MOTION,+ },+ "expected_rgb": expected,+ "actual_rgb": actual,+ "diagnostic": None if actual == expected else "CSS media probe colors differ",+ }+ except (subprocess.TimeoutExpired, OSError) as error:+ return {"ok": False, "status": "probe-error", "diagnostic": str(error)}+++def capture_obscura(+ binary, url, screenshot, log, width, height, settle_ms, scroll=None+):+ env = obscura_environment(width, height)command = [binary,"fetch",url,+ "--user-agent",+ CANONICAL_USER_AGENT,"--screenshot",str(screenshot),"--timeout",@@ -73,17 +308,29 @@ def capture_obscura(binary, url, screenshot, log, width, height, settle_ms):"--wait",f"{settle_ms / 1000:g}",]+ scroll_expression = scroll_eval_expression(scroll)+ if scroll_expression is not None:+ command.extend(["--eval", scroll_expression])started = time.time()try:result = subprocess.run(command, capture_output=True, text=True, timeout=75, env=env)log.write_text(result.stdout + result.stderr)- ok = result.returncode == 0 and screenshot.is_file() and screenshot.stat().st_size > 0+ scroll_state = None+ if scroll_expression is not None and result.returncode == 0:+ scroll_state = parse_obscura_scroll_report(result.stdout)+ ok = (+ result.returncode == 0+ and screenshot.is_file()+ and screenshot.stat().st_size > 0+ and (scroll_expression is None or scroll_state is not None)+ )return {"ok": ok,"status": result.returncode,"elapsed_s": round(time.time() - started, 3),+ "scroll_state": scroll_state,}except subprocess.TimeoutExpired as error:log.write_text(@@ -92,6 +339,184 @@ def capture_obscura(binary, url, screenshot, log, width, height, settle_ms):return {"ok": False, "status": "timeout", "elapsed_s": round(time.time() - started, 3)}+def chromium_identity_override(session):+ """Keep request headers and navigator identity aligned with Obscura."""+ match = re.search(r"Chrome/(\d+)", CANONICAL_USER_AGENT)+ major = int(match.group(1)) if match else 143+ grease = {+ "brand": (+ "Not"+ + GREASE_CHARS[major % len(GREASE_CHARS)]+ + "A"+ + GREASE_CHARS[(major + 1) % len(GREASE_CHARS)]+ + "Brand"+ ),+ "version": GREASE_VERSIONS[major % len(GREASE_VERSIONS)],+ }+ unordered = [+ grease,+ {"brand": "Chromium", "version": str(major)},+ {"brand": "Google Chrome", "version": str(major)},+ ]+ permutation = BRAND_PERMUTATIONS[major % len(BRAND_PERMUTATIONS)]+ brands = [unordered[index] for index in permutation]+ session.send(+ "Emulation.setUserAgentOverride",+ {+ "userAgent": CANONICAL_USER_AGENT,+ "acceptLanguage": "en-US,en",+ "platform": CANONICAL_PLATFORM,+ "userAgentMetadata": {+ "brands": brands,+ "fullVersionList": [+ {+ "brand": brand["brand"],+ "version": brand["version"] + ".0.0.0",+ }+ for brand in brands+ ],+ "platform": CANONICAL_UA_PLATFORM,+ "platformVersion": CANONICAL_UA_PLATFORM_VERSION,+ "architecture": "x86",+ "model": "",+ "mobile": False,+ "bitness": "64",+ "wow64": False,+ },+ },+ )+++def capture_chromium_state(page):+ """Sample page provenance immediately before the screenshot."""+ state = page.evaluate(+ """async () => {+ async function sha256(value) {+ if (!globalThis.crypto || !crypto.subtle) return null;+ const bytes = new TextEncoder().encode(value);+ const digest = await crypto.subtle.digest("SHA-256", bytes);+ return Array.from(new Uint8Array(digest), byte =>+ byte.toString(16).padStart(2, "0")).join("");+ }++ const root = document.documentElement;+ const body = document.body;+ const dom = root ? root.outerHTML : "";+ const visibleText = body ? body.innerText : "";+ const normalizedText = visibleText.replace(/\\s+/g, " ").trim();+ const images = Array.from(document.images || []);+ const fonts = document.fonts;+ const media = {+ prefers_color_scheme_light:+ matchMedia("(prefers-color-scheme: light)").matches,+ prefers_color_scheme_dark:+ matchMedia("(prefers-color-scheme: dark)").matches,+ prefers_reduced_motion_no_preference:+ matchMedia("(prefers-reduced-motion: no-preference)").matches,+ prefers_reduced_motion_reduce:+ matchMedia("(prefers-reduced-motion: reduce)").matches+ };+ return {+ sampled_phase: "immediately-before-screenshot",+ url: location.href,+ identity: {+ user_agent: navigator.userAgent,+ platform: navigator.platform,+ ua_platform: navigator.userAgentData+ ? navigator.userAgentData.platform+ : null,+ ua_brands: navigator.userAgentData+ ? Array.from(navigator.userAgentData.brands)+ : null,+ language: navigator.language,+ languages: Array.from(navigator.languages || []),+ },+ document: {+ ready_state: document.readyState,+ element_count: document.getElementsByTagName("*").length,+ outer_html_bytes: new TextEncoder().encode(dom).length,+ outer_html_sha256: await sha256(dom),+ visible_text_bytes: new TextEncoder().encode(normalizedText).length,+ visible_text_sha256: await sha256(normalizedText),+ },+ geometry: {+ inner_width: innerWidth,+ inner_height: innerHeight,+ scroll_x: scrollX,+ scroll_y: scrollY,+ device_pixel_ratio: devicePixelRatio,+ document_client_width: root ? root.clientWidth : null,+ document_client_height: root ? root.clientHeight : null,+ document_scroll_width: root ? root.scrollWidth : null,+ document_scroll_height: root ? root.scrollHeight : null,+ body_client_width: body ? body.clientWidth : null,+ body_client_height: body ? body.clientHeight : null,+ body_scroll_width: body ? body.scrollWidth : null,+ body_scroll_height: body ? body.scrollHeight : null,+ visual_viewport: visualViewport ? {+ width: visualViewport.width,+ height: visualViewport.height,+ scale: visualViewport.scale,+ offset_left: visualViewport.offsetLeft,+ offset_top: visualViewport.offsetTop+ } : null+ },+ fonts: {+ supported: !!fonts,+ status: fonts ? fonts.status : null,+ face_count: fonts ? Array.from(fonts).length : null,+ ready_at_sample: fonts ? fonts.status === "loaded" : null+ },+ images: {+ total: images.length,+ complete: images.filter(image => image.complete).length,+ complete_with_pixels: images.filter(image =>+ image.complete && image.naturalWidth > 0).length,+ complete_without_pixels: images.filter(image =>+ image.complete && image.naturalWidth === 0).length,+ pending: images.filter(image => !image.complete).length,+ lazy: images.filter(image => image.loading === "lazy").length+ },+ media: {+ ...media,+ root_computed_color_scheme: root+ ? getComputedStyle(root).colorScheme+ : null,+ root_class: root ? root.className : null,+ root_data_theme: root ? root.getAttribute("data-theme") : null,+ body_class: body ? body.className : null,+ body_data_theme: body ? body.getAttribute("data-theme") : null+ }+ };+ }"""+ )+ document_state = state["document"]+ if (+ document_state["outer_html_sha256"] is None+ or document_state["visible_text_sha256"] is None+ ):+ # crypto.subtle is unavailable on some non-secure/file origins. Only+ # transfer the potentially large strings on that fallback path.+ fallback = page.evaluate(+ """() => {+ const dom = document.documentElement+ ? document.documentElement.outerHTML+ : "";+ const text = document.body+ ? document.body.innerText.replace(/\\s+/g, " ").trim()+ : "";+ return {dom, text};+ }"""+ )+ document_state["outer_html_sha256"] = hashlib.sha256(+ fallback["dom"].encode()+ ).hexdigest()+ document_state["visible_text_sha256"] = hashlib.sha256(+ fallback["text"].encode()+ ).hexdigest()+ return state++def load_rgb(path):return np.asarray(Image.open(path).convert("RGB"))@@ -113,10 +538,31 @@ def main():parser.add_argument("--width", type=int, default=1280)parser.add_argument("--height", type=int, default=1400)parser.add_argument("--settle-ms", type=int, default=3000)+ parser.add_argument(+ "--scroll-x",+ type=int,+ help="scroll both engines to this CSS-pixel x offset before capture",+ )+ parser.add_argument(+ "--scroll-y",+ type=parse_scroll_y,+ help="scroll both engines to this CSS-pixel y offset or 'bottom' before capture",+ )args = parser.parse_args()+ if args.settle_ms % 1000:+ parser.error(+ "--settle-ms must be a whole number of seconds because Obscura's "+ "fetch --wait interface accepts integer seconds"+ )out = Path(args.out)out.mkdir(parents=True, exist_ok=False)+ controlled_scroll = None+ if args.scroll_x is not None or args.scroll_y is not None:+ controlled_scroll = (+ args.scroll_x if args.scroll_x is not None else 0,+ args.scroll_y if args.scroll_y is not None else 0,+ )urls = [line.strip()for line in Path(args.urls).read_text().splitlines()@@ -126,14 +572,85 @@ def main():"started_utc": datetime.now(timezone.utc).isoformat(),"viewport": {"width": args.width, "height": args.height, "dpr": 1},"settle_ms_after_load": args.settle_ms,- "settle_semantics": "full wall-clock interval while pumping each engine",+ "settle_ms_after_controlled_scroll": (+ args.settle_ms if controlled_scroll is not None else 0+ ),+ "settle_semantics": (+ "full wall-clock interval while pumping each engine; when a "+ "controlled scroll is requested, the same interval runs once "+ "after load and once after scrolling"+ ),+ "controlled_scroll": (+ {"x": controlled_scroll[0], "y": controlled_scroll[1]}+ if controlled_scroll is not None+ else None+ ),"navigation_timeout_ms": 50000,"obscura": binary_version(args.obscura_bin),"baseline": binary_version(args.baseline_bin) if args.baseline_bin else None,+ "capture_identity": {+ "normalized": True,+ "configured_user_agent": CANONICAL_USER_AGENT,+ "configured_platform": CANONICAL_PLATFORM,+ "configured_ua_platform": CANONICAL_UA_PLATFORM,+ "configured_ua_platform_version": CANONICAL_UA_PLATFORM_VERSION,+ "obscura_profile": CANONICAL_OBSCURA_PROFILE,+ },+ "capture_media": {+ "normalized": True,+ "color_scheme": CANONICAL_COLOR_SCHEME,+ "reduced_motion": CANONICAL_REDUCED_MOTION,+ "expected_match_media": EXPECTED_MEDIA_MATCHES,+ "reduced_motion_reason": (+ "Obscura currently models the browser default "+ "(no-preference), so Chromium is pinned to the same state"+ ),+ },+ "state_observability": {+ "chromium": "same page, sampled immediately before screenshot",+ "obscura": (+ "identity and JS media probed on a data URL; CSS media behavior "+ "verified by a separate pixel probe; controlled-scroll captures "+ "record the same live page's requested/clamped offset, viewport, "+ "and content size immediately before paint"+ ),+ },"pages": [],}+ manifest["obscura_identity_probe"] = probe_obscura_identity(args.obscura_bin)+ manifest["obscura_css_media_probe"] = probe_obscura_css_media(args.obscura_bin)+ if args.baseline_bin:+ manifest["baseline_identity_probe"] = probe_obscura_identity(args.baseline_bin)+ manifest["baseline_css_media_probe"] = probe_obscura_css_media(+ args.baseline_bin+ )results_path = out / "results.json"write_results(results_path, manifest)+ probes = [+ ("obscura JS media", manifest["obscura_identity_probe"].get("media_matches_configured")),+ ("obscura CSS media", manifest["obscura_css_media_probe"].get("ok")),+ ]+ if args.baseline_bin:+ probes.extend(+ [+ (+ "baseline JS media",+ manifest["baseline_identity_probe"].get("media_matches_configured"),+ ),+ (+ "baseline CSS media",+ manifest["baseline_css_media_probe"].get("ok"),+ ),+ ]+ )+ failed_probes = [name for name, passed in probes if not passed]+ if failed_probes:+ print(+ "capture environment mismatch: " + ", ".join(failed_probes),+ file=sys.stderr,+ )+ print(f"probe evidence: {results_path}", file=sys.stderr)+ raise SystemExit(2)with sync_playwright() as playwright:chromium_executable = args.chromium_bin or playwright.chromium.executable_path@@ -159,12 +676,20 @@ def main():context = browser.new_context(viewport={"width": args.width, "height": args.height},device_scale_factor=1,- color_scheme="light",- reduced_motion="no-preference",+ user_agent=CANONICAL_USER_AGENT,+ color_scheme=CANONICAL_COLOR_SCHEME,+ reduced_motion=CANONICAL_REDUCED_MOTION,locale="en-US",timezone_id="UTC",)page = context.new_page()+ # Repeat the context-level settings at page scope so a future+ # context refactor cannot silently fall back to host media.+ page.emulate_media(+ color_scheme=CANONICAL_COLOR_SCHEME,+ reduced_motion=CANONICAL_REDUCED_MOTION,+ )+ chromium_identity_override(context.new_cdp_session(page))chrome_messages = []page.on("console", lambda message: chrome_messages.append(f"console {message.type}: {message.text}"))page.on("pageerror", lambda error: chrome_messages.append(f"pageerror: {error}"))@@ -178,6 +703,7 @@ def main():args.width,args.height,args.settle_ms,+ controlled_scroll,)baseline_future = Noneif args.baseline_bin:@@ -190,17 +716,48 @@ def main():args.width,args.height,args.settle_ms,+ controlled_scroll,)chrome_started = time.time()try:page.goto(url, wait_until="load", timeout=50000)page.wait_for_timeout(args.settle_ms)+ if controlled_scroll is not None:+ scroll_x, scroll_y = controlled_scroll+ page.evaluate(+ """([x, y]) => {+ const requestedY = y === "bottom"+ ? document.documentElement.scrollHeight+ : y;+ window.scrollTo(x, requestedY);+ }""",+ [scroll_x, scroll_y],+ )+ page.wait_for_timeout(args.settle_ms)+ chromium_state_ok = False+ try:+ chromium_state = capture_chromium_state(page)+ chromium_state["media"]["matches_configured"] = (+ media_matches_configured(chromium_state["media"])+ )+ if not chromium_state["media"]["matches_configured"]:+ raise RuntimeError(+ "Chromium matchMedia differs from configured capture media"+ )+ chromium_state_ok = True+ except Exception as error:+ chromium_state = None+ chrome_messages.append(f"state capture error: {error}")page.screenshot(path=str(chrome_path), full_page=False, timeout=50000)- chrome_ok = chrome_path.is_file() and chrome_path.stat().st_size > 0- chrome_status = 0+ chrome_ok = (+ chromium_state_ok+ and chrome_path.is_file()+ and chrome_path.stat().st_size > 0+ )+ chrome_status = 0 if chrome_ok else "state-error"except Exception as error:chrome_messages.append(f"capture error: {error}")chrome_ok = False@@ -211,12 +768,70 @@ def main():"status": chrome_status,"elapsed_s": round(time.time() - chrome_started, 3),"title": page.title() if chrome_ok else None,+ "state": chromium_state if chrome_ok else None,}context.close()page_result["obscura"] = ours_future.result()if baseline_future:page_result["baseline"] = baseline_future.result()+ if (+ controlled_scroll is not None+ and chrome_ok+ and page_result["obscura"]["ok"]+ ):+ ours_scroll = page_result["obscura"].get("scroll_state") or {}+ ours_actual = ours_scroll.get("actual") or {}+ ours_content = ours_scroll.get("content") or {}+ chrome_geometry = chromium_state.get("geometry") or {}+ comparable = all(+ isinstance(value, (int, float))+ for value in (+ ours_actual.get("x"),+ ours_actual.get("y"),+ chrome_geometry.get("scroll_x"),+ chrome_geometry.get("scroll_y"),+ )+ )+ page_result["controlled_scroll_comparison"] = {+ "comparable": comparable,+ "obscura_actual": ours_actual,+ "chromium_actual": {+ "x": chrome_geometry.get("scroll_x"),+ "y": chrome_geometry.get("scroll_y"),+ },+ "actual_delta": (+ {+ "x": ours_actual["x"] - chrome_geometry["scroll_x"],+ "y": ours_actual["y"] - chrome_geometry["scroll_y"],+ }+ if comparable+ else None+ ),+ "content_size_delta": {+ "width": (+ ours_content.get("width")+ - chrome_geometry.get("document_scroll_width")+ if isinstance(ours_content.get("width"), (int, float))+ and isinstance(+ chrome_geometry.get("document_scroll_width"),+ (int, float),+ )+ else None+ ),+ "height": (+ ours_content.get("height")+ - chrome_geometry.get("document_scroll_height")+ if isinstance(ours_content.get("height"), (int, float))+ and isinstance(+ chrome_geometry.get("document_scroll_height"),+ (int, float),+ )+ else None+ ),+ },+ }+if chrome_ok and page_result["obscura"]["ok"]:chrome_rgb = load_rgb(chrome_path)current_metrics = pair_metrics(load_rgb(ours_path), chrome_rgb)@@ -231,6 +846,8 @@ def main():"edge_bbox_max_delta","edge_row_projection_delta","edge_column_projection_delta",+ "edge_bidirectional_mean_distance_px",+ "edge_bidirectional_p95_distance_px",):if key in current_metrics and key in baseline_metrics:if current_metrics[key] is None or baseline_metrics[key] is None:@@ -247,13 +864,21 @@ def main():edge_delta = page_result.get("delta_vs_baseline", {}).get("edge_column_projection_delta")+ edge_2d = page_result.get("metrics", {}).get(+ "edge_bidirectional_mean_distance_px"+ )+ edge_2d_delta = page_result.get("delta_vs_baseline", {}).get(+ "edge_bidirectional_mean_distance_px"+ )print(f"{name:84} "f"p>50={metric if metric is not None else 'capture-fail'} "f"edge_bbox={edge_bbox if edge_bbox is not None else '-'} "f"edge_row={edge_row if edge_row is not None else '-'} "f"edge_col={edge_col if edge_col is not None else '-'} "- f"edge_col_delta={edge_delta if edge_delta is not None else '-'}",+ f"edge_2d={edge_2d if edge_2d is not None else '-'} "+ f"edge_col_delta={edge_delta if edge_delta is not None else '-'} "+ f"edge_2d_delta={edge_2d_delta if edge_2d_delta is not None else '-'}",flush=True,)browser.close()diff --git a/render-repros/percentage-height-indefinite-parent.html b/render-repros/percentage-height-indefinite-parent.htmlindex a9c9ab97..22d03352 100644--- a/render-repros/percentage-height-indefinite-parent.html+++ b/render-repros/percentage-height-indefinite-parent.html@@ -1,19 +1,22 @@<!doctype html><meta charset="utf-8"><style>+ body { margin: 0; }#outer { width: 400px; }#wrapper, #pre { height: 100%; }#stack { display: flex; flex-direction: column; width: 100%; position: relative; }#editor { flex: 1 1; position: relative; overflow: auto; }- #pre { display: flex; }- #code { display: block; line-height: 24px; }+ #pre { display: flex; margin: 0; }+ #code { display: block; line-height: 24px; background: #087f5b; }+ #after { width: 400px; height: 20px; background: #e8590c; }</style><div id="outer"><div id="wrapper"><div id="stack"><div id="editor">- <pre id="pre"><code id="code">content must give an indefinite percentage-height chain its height</code></pre>+ <pre id="pre"><code id="code">content gives the chain height</code></pre></div></div></div></div>+<div id="after"></div>diff --git a/render-repros/test_check.py b/render-repros/test_check.pynew file mode 100644index 00000000..f6f92676--- /dev/null+++ b/render-repros/test_check.py@@ -0,0 +1,36 @@+#!/usr/bin/env python3++import unittest++import numpy as np++from check import pair_metrics+++class PairMetricsTests(unittest.TestCase):+ def test_bidirectional_distance_catches_projection_preserving_rearrangement(self):+ diagonal = np.full((160, 160, 3), 255, dtype=np.uint8)+ anti_diagonal = diagonal.copy()+ diagonal[20:50, 20:50] = 0+ diagonal[100:130, 100:130] = 0+ anti_diagonal[20:50, 100:130] = 0+ anti_diagonal[100:130, 20:50] = 0++ metrics = pair_metrics(diagonal, anti_diagonal)++ self.assertAlmostEqual(metrics["edge_row_projection_delta"], 0.0)+ self.assertAlmostEqual(metrics["edge_column_projection_delta"], 0.0)+ self.assertGreater(metrics["edge_bidirectional_mean_distance_px"], 20.0)++ def test_identical_images_have_zero_bidirectional_distance(self):+ image = np.full((80, 80, 3), 255, dtype=np.uint8)+ image[20:60, 25:55] = 0++ metrics = pair_metrics(image, image)++ self.assertEqual(metrics["edge_bidirectional_mean_distance_px"], 0.0)+ self.assertEqual(metrics["edge_bidirectional_p95_distance_px"], 0.0)+++if __name__ == "__main__":+ unittest.main()diff --git a/render-repros/test_paired_corpus.py b/render-repros/test_paired_corpus.pynew file mode 100644index 00000000..d015bf3c--- /dev/null+++ b/render-repros/test_paired_corpus.py@@ -0,0 +1,63 @@+#!/usr/bin/env python3++import importlib.util+import unittest+from pathlib import Path+++SCRIPT = Path(__file__).with_name("paired-corpus.py")+SPEC = importlib.util.spec_from_file_location("paired_corpus", SCRIPT)+paired_corpus = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(paired_corpus)+++class MediaEnvironmentTests(unittest.TestCase):+ def test_canonical_light_default_motion_environment_matches(self):+ self.assertTrue(+ paired_corpus.media_matches_configured(+ dict(paired_corpus.EXPECTED_MEDIA_MATCHES)+ )+ )++ def test_dark_or_reduced_environment_is_rejected(self):+ dark = dict(paired_corpus.EXPECTED_MEDIA_MATCHES)+ dark["prefers_color_scheme_light"] = False+ dark["prefers_color_scheme_dark"] = True+ self.assertFalse(paired_corpus.media_matches_configured(dark))++ reduced = dict(paired_corpus.EXPECTED_MEDIA_MATCHES)+ reduced["prefers_reduced_motion_no_preference"] = False+ reduced["prefers_reduced_motion_reduce"] = True+ self.assertFalse(paired_corpus.media_matches_configured(reduced))+++class ControlledScrollTests(unittest.TestCase):+ def test_bottom_expression_resolves_live_document_height(self):+ expression = paired_corpus.scroll_eval_expression((12, "bottom"))+ self.assertIn("const requestedX=12", expression)+ self.assertIn(+ "requestedY=document.documentElement.scrollHeight", expression+ )+ self.assertIn("window.scrollTo(requestedX,requestedY)", expression)++ def test_capture_report_uses_post_settle_state(self):+ stdout = (+ "diagnostic\n"+ '{"evaluation":"{\\"requested\\":{\\"x\\":0,\\"y\\":2702}}",'+ '"captureState":{"scrollX":0,"scrollY":1802,'+ '"innerWidth":1280,"innerHeight":900,'+ '"scrollWidth":1291,"scrollHeight":2702}}\n'+ )+ state = paired_corpus.parse_obscura_scroll_report(stdout)+ self.assertEqual(state["requested"], {"x": 0, "y": 2702})+ self.assertEqual(state["actual"], {"x": 0, "y": 1802})+ self.assertEqual(state["content"]["height"], 2702)+ self.assertEqual(state["sampled_phase"], "immediately-before-screenshot")++ def test_scroll_y_parser_accepts_bottom_and_integer(self):+ self.assertEqual(paired_corpus.parse_scroll_y("bottom"), "bottom")+ self.assertEqual(paired_corpus.parse_scroll_y("-20"), -20)+++if __name__ == "__main__":+ unittest.main()