Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
ci(pdf): verify rendered pixels text and links with MuPDF
ldm0a9c763c8c436
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 014599d94..0c25a8fdd 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -449,6 +449,42 @@ jobs:if-no-files-found: warnretention-days: 7+ native-pdf:+ name: Native PDF rendering and links+ needs: [resolve-refs, build-release-head]+ runs-on: ubuntu-latest+ timeout-minutes: 15+ container: rust:1.96.1-bookworm+ steps:+ - uses: actions/checkout@v4+ with:+ persist-credentials: false+ ref: ${{ needs.resolve-refs.outputs.head_sha }}+ - name: Use HEAD release+ uses: ./.github/actions/use-ci-release+ with:+ side: head+ revision: ${{ needs.resolve-refs.outputs.head_sha }}+ - uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0+ with:+ version: 0.11.14+ python-version: "3.12"+ enable-cache: true+ cache-dependency-glob: scripts/check-native-pdf.py.lock+ - name: Check rendered pixels, text and link targets and regions+ run: >-+ uv run --locked --script scripts/check-native-pdf.py+ --moli target/ci-bin/moli-release-head/moli+ --output-dir target/native-pdf-ci+ - name: Upload PDFs and reader evidence+ if: ${{ always() }}+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: native-pdf-results+ path: target/native-pdf-ci+ if-no-files-found: warn+ retention-days: 7+webdriver-smoke:name: WebDriver smokeneeds: [resolve-refs, build-release-head]diff --git a/moli-paint/README.md b/moli-paint/README.mdindex d8e91486f..ee1f79856 100644--- a/moli-paint/README.md+++ b/moli-paint/README.md@@ -102,7 +102,7 @@ color glyphs. Regenerate it withReader-level regression and artifact generation:```sh-uv run scripts/check-native-pdf.py --moli target/debug/moli+uv run --locked --script scripts/check-native-pdf.py --moli target/debug/molicd moli-cdp-smokeuv run moli-cdp-smoke --group pdf```@@ -115,7 +115,18 @@ use lopdf for PDF objects and ordinary text; its extractor does not interpretActualText and Type3 text correctly, so it is not the complex-text oracle.The reader script also compares rendered solid and gradient button backgroundsagainst CLI screenshots; extracting a white label alone does not establish that-the label is visible in the PDF.+the label is visible in the PDF. It checks the white label's visible pixels as+well as its extracted text. A local fixture server supplies relative URLs, wrapped+links, rotated and clipped links, an iframe with an SVG icon, and internal ID/named+anchors. MuPDF checks both targets and hit regions, including PDF QuadPoints and+destination page numbers. The font fixtures and page resources are bundled;+these checks do not depend on public websites or system fonts.++CI runs this script against the exact HEAD release artifact in the+`Native PDF rendering and links` job. Its locked MuPDF dependency and Python 3.12+match the local command above. Failure blocks the job; PDF files, raster previews,+screenshots, extracted text and link JSON are uploaded even when a check fails.+The CI job does not substitute PDF parsing or nonempty text for visual checks.Validation on 2026-10-12 (Linux x86_64, Rust 1.96.1): `cargo fmt --all`,workspace Clippy with all targets/features and warnings denied, and the fulldiff --git a/scripts/check-native-pdf.py b/scripts/check-native-pdf.pyindex e8f02eabd..a67a4758c 100644--- a/scripts/check-native-pdf.py+++ b/scripts/check-native-pdf.py@@ -13,9 +13,12 @@ and plain-text regressions. Artifacts and observed process costs are retained.import argparseimport base64+from contextlib import contextmanager+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServerimport jsonfrom pathlib import Pathimport subprocess+import threadingimport timeimport pymupdf@@ -27,15 +30,15 @@ def data_url(data, media_type):return f"data:{media_type};base64," + base64.b64encode(data).decode()-def capture(binary, output, name, html):+def capture(binary, output, name, html, url=None):path = output / f"{name}.pdf"started = time.perf_counter()peak_kib = 0with path.open("wb") as target:process = subprocess.Popen(- [str(binary), "fetch", "--font", "--layout", "--wait-until", "load",+ [str(binary), "fetch", "--resource", "--layout", "--wait-until", "load","--log-level", "error", "--http-no-proxy", "*", "--dump", "pdf",- data_url(html.encode(), "text/html")],+ url or data_url(html.encode(), "text/html")],stdout=target, stderr=subprocess.PIPE,)while process.poll() is None:@@ -58,23 +61,35 @@ def capture(binary, output, name, html):text = " ".join(" ".join(page.get_text().split()) for page in document)(output / f"{name}.txt").write_text(text)document[0].get_pixmap(matrix=pymupdf.Matrix(1.5, 1.5)).save(output / f"{name}.png")+ links = [{"page": page.number, "kind": link["kind"],+ "rect": list(link["from"]), "uri": link.get("uri"),+ "destination_page": link.get("page"),+ "destination_point": list(link["to"]) if "to" in link else None}+ for page in document for link in page.get_links()]+ (output / f"{name}-links.json").write_text(json.dumps(links, indent=2) + "\n")info = {"pages": len(document), "pdf_bytes": path.stat().st_size,"seconds": round(seconds, 4), "peak_rss_kib_sampled": peak_kib,"fonts": sorted({font[3] for page in document for font in page.get_fonts()}),- "image_count": sum(len(page.get_images()) for page in document)}+ "image_count": sum(len(page.get_images()) for page in document),+ "link_count": len(links)}+ document.close()return text, info-def check_button_backgrounds(binary, output, html):- screenshot = output / "backgrounds-screenshot.png"+def screenshot(binary, output, name, html, url=None):+ path = output / f"{name}-screenshot.png"result = subprocess.run(- [str(binary), "fetch", "--font", "--layout", "--wait-until", "load",+ [str(binary), "fetch", "--resource", "--layout", "--wait-until", "load","--log-level", "error", "--http-no-proxy", "*", "--dump", "screenshot",- data_url(html.encode(), "text/html")],+ url or data_url(html.encode(), "text/html")],capture_output=True, check=True, timeout=120,)- screenshot.write_bytes(result.stdout)- reference = pymupdf.Pixmap(screenshot)+ path.write_bytes(result.stdout)+ return pymupdf.Pixmap(path)+++def check_button_backgrounds(binary, output, html):+ reference = screenshot(binary, output, "backgrounds", html)with pymupdf.open(output / "backgrounds.pdf") as document:page = document[0]# CLI PDF fits the viewport width inside the default 1 cm margins.@@ -92,6 +107,148 @@ def check_button_backgrounds(binary, output, html):assert max(abs(a - b) for a, b in zip(actual, expected)) <= 3, ("PDF button background differs from screenshot", x, y, actual, expected)+ # A correct background must also leave the white labels visible. Check+ # each label's interior separately from its extractable Unicode text.+ for x0, x1 in [(115, 265), (310, 470)]:+ white = 0+ for y in range(121, 140):+ for x in range(x0, x1):+ pixel = rendered.pixel(round(margin / scale + x - rendered.x),+ round(margin / scale + y - rendered.y))[:3]+ white += min(pixel) > 235+ assert white > 80, ("white button label is not visible", x0, white)+++@contextmanager+def fixture_server(resources):+ """Serve only fixed in-memory documents; no public web resources are fetched."""+ class Handler(BaseHTTPRequestHandler):+ def do_GET(self):+ body = resources.get(self.path)+ self.send_response(200 if body is not None else 404)+ self.send_header("Content-Type", "text/html; charset=utf-8")+ self.end_headers()+ self.wfile.write((body or "Missing fixture").encode())++ def log_message(self, *_):+ pass++ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ yield f"http://127.0.0.1:{server.server_port}"+ finally:+ server.shutdown()+ server.server_close()+ thread.join()+++def check_links(binary, output, style):+ # Explicit geometry avoids dependence on system fonts and viewport guesses.+ # Text uses bundled fonts; the child uses a vector icon without font lookup.+ html = style + """<base href="/fixtures/"><style>+body{margin:0;height:3600px} a{color:#174ac0}+.box{position:absolute;display:block;width:100px;height:30px;line-height:30px}+#relative{left:40px;top:40px;background:#c2d8ff}+#wrap{position:absolute;left:40px;top:100px;width:100px;line-height:30px}+#rotate{left:300px;top:100px;transform:rotate(30deg);transform-origin:0 0;background:#c2d8ff}+#clip{position:absolute;left:40px;top:230px;width:70px;height:30px;overflow:hidden}+#clip a{display:block;width:150px;height:30px;background:#c2d8ff}+#internal{left:40px;top:300px} #named{left:170px;top:300px}+#destination{position:absolute;left:40px;top:3200px;width:300px;height:30px;background:#5ac88c}+iframe{position:absolute;left:300px;top:230px;width:180px;height:90px;border:0}+#hidden{opacity:0;left:500px;top:40px}+#spanning{position:absolute;left:600px;top:1600px;width:80px;height:1600px;background:#d0e6f8}+</style>+<a class=box id=relative href="../target?q=1&x=2">Relative</a>+<div id=wrap><a href="https://links.example/wrapped">First Second</a></div>+<a class=box id=rotate href="https://links.example/rotated">Rotate</a>+<div id=clip><a href="https://links.example/clipped">Clipped text</a></div>+<a class=box id=internal href="/index.html#destination">Internal</a>+<a class=box id=named href="/index.html#old%20anchor">Named</a>+<a class=box id=hidden href="https://links.example/hidden">Hidden</a>+<a id=spanning href="https://links.example/paged"></a>+<iframe src="child.html"></iframe>+<div id=destination>Destination<a name="old anchor"></a></div>"""+ child = """<style>body{margin:0;font-size:0}a{position:absolute;left:10px;top:10px;+display:block;width:100px;height:30px;background:#c2d8ff}</style><a href="child-target">+<svg width="20" height="20" viewBox="0 0 20 20"><path d="M5 5H15V15H5Z" fill="#174ac0"/></svg></a>"""+ with fixture_server({"/index.html": html, "/fixtures/child.html": child}) as origin:+ text, info = capture(binary, output, "links", html, origin + "/index.html")+ reference = screenshot(binary, output, "links", html, origin + "/index.html")+ with pymupdf.open(output / "links.pdf") as document:+ page = document[0]+ margin = 72 / 2.54+ scale = (page.rect.width - margin * 2) / reference.width+ links = page.get_links()+ by_uri = {}+ for link in links:+ if link["kind"] == pymupdf.LINK_URI:+ by_uri.setdefault(link["uri"], []).append(link)+ assert set(by_uri) == {origin + "/target?q=1&x=2",+ "https://links.example/wrapped",+ "https://links.example/rotated",+ "https://links.example/clipped",+ "https://links.example/paged",+ origin + "/fixtures/child-target"}, by_uri++ def css_rect(link):+ rect = link["from"]+ return pymupdf.Rect(*[(value - margin) / scale for value in rect])++ def near(actual, expected, tolerance=1):+ assert max(abs(a - b) for a, b in zip(actual, expected)) <= tolerance, (actual, expected)++ near(css_rect(by_uri[origin + "/target?q=1&x=2"][0]), (40, 40, 140, 70))+ near(css_rect(by_uri["https://links.example/clipped"][0]), (40, 230, 110, 260))+ near(css_rect(by_uri[origin + "/fixtures/child-target"][0]), (310, 240, 410, 270))+ wrapped = by_uri["https://links.example/wrapped"]+ assert len(wrapped) == 2, wrapped+ assert all(css_rect(link).height < 31 for link in wrapped), wrapped+ near(css_rect(by_uri["https://links.example/rotated"][0]),+ (285, 100, 386.60, 175.98), tolerance=1.5)+ # MuPDF exposes annotation rectangles; inspect QuadPoints as well+ # so a rotated link cannot silently degrade to its bounding box.+ rotated = by_uri["https://links.example/rotated"][0]+ kind, values = document.xref_get_key(rotated["xref"], "QuadPoints")+ assert kind == "array" and len(values.strip("[]").split()) == 8, values+ points = [float(v) for v in values.strip("[]").split()]+ assert abs(points[1] - points[3]) > 10, points+ rendered = page.get_pixmap(matrix=pymupdf.Matrix(1 / scale, 1 / scale))+ rendered.save(output / "links-rendered.png")+ # Interior samples couple visible content to the independently+ # asserted annotation regions, including rotation, clip and iframe.+ for x, y in [(45, 45), (45, 250), (120, 250), (316, 245), (302, 150)]:+ actual = rendered.pixel(round(margin / scale + x), round(margin / scale + y))[:3]+ expected = reference.pixel(x, y)[:3]+ assert max(abs(a - b) for a, b in zip(actual, expected)) <= 3, (+ "linked content differs from screenshot", x, y, actual, expected)+ assert min(reference.pixel(45, 45)[:3]) < 220+ assert min(reference.pixel(120, 250)[:3]) > 250, "overflow clip must hide content"+ internal = [link for link in links if link["kind"] == pymupdf.LINK_GOTO]+ destination_page = int(3200 * scale / (page.rect.height - margin * 2))+ assert destination_page > 0+ assert len(internal) == 2 and all(link["page"] == destination_page for link in internal), internal+ target = next(link for link in internal if abs(link["to"].x - (margin + 40 * scale)) < 1)+ near(target["to"], (margin + 40 * scale,+ margin + 3200 * scale - destination_page * (page.rect.height - margin * 2)))+ assert all(margin <= link["to"].x <= margin + 340 * scale for link in internal), internal+ assert all("hidden" not in str(link) for page in document for link in page.get_links())+ assert len(document) == 2+ page_height = (page.rect.height - margin * 2) / scale+ near(css_rect(by_uri["https://links.example/paged"][0]), (600, 1600, 680, page_height))+ second = document[1].get_links()+ assert len(second) == 1 and second[0].get("uri") == "https://links.example/paged", second+ near(css_rect(second[0]), (600, 0, 680, 3200 - page_height))+ preview = document[1].get_pixmap()+ preview.save(output / "links-page-2.png")+ x, y = second[0]["from"].tl+ assert max(abs(a - b) for a, b in zip(preview.pixel(round(x + 3), round(y + 3))[:3],+ (208, 230, 248))) <= 1+ assert "Destination" in text and "Hidden" not in text, text+ assert all("MoliPDFTest" in font for font in info["fonts"]), info["fonts"]+ return infodef main():@@ -123,6 +280,8 @@ color:white;background:#325dff;border:0;border-radius:12px;font:20px PDFTest}assert text == "Search Gradient", textcheck_button_backgrounds(args.moli.resolve(), args.output_dir, html)+ results["links"] = check_links(args.moli.resolve(), args.output_dir, style)+expected = ["Font Text 123 中文", "office fi ffi á", "Second page a", "abc אבג xyz","Color ★", "Weight 650", "Italic"]html = style + """<p>Font Text 123 中文</p><p>office fi ffi á</p>@@ -150,6 +309,9 @@ color:white;background:#325dff;border:0;border-radius:12px;font:20px PDFTest}assert text == " ".join(f"Row {i:03}" for i in range(286)), textassert results["long_document"]["pages"] > 1assert results["long_document"]["image_count"] == 0+ for name, info in results.items():+ assert all(font.split("+")[-1] in {"MoliPDFTest", "DroidSansFallback"}+ for font in info["fonts"]), ("unexpected system font", name, info["fonts"])report = {"binary": str(args.moli.resolve()), "binary_bytes": args.moli.stat().st_size,"reader": pymupdf.version[0], "cases": results}(args.output_dir / "results.json").write_text(json.dumps(report, indent=2) + "\n")diff --git a/scripts/check-native-pdf.py.lock b/scripts/check-native-pdf.py.locknew file mode 100644index 000000000..ce2e52dea--- /dev/null+++ b/scripts/check-native-pdf.py.lock@@ -0,0 +1,24 @@+version = 1+revision = 3+requires-python = ">=3.11"++[manifest]+requirements = [{ name = "pymupdf", specifier = "==1.28.2" }]++[[package]]+name = "pymupdf"+version = "1.28.2"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/a3/fb/b6761fa2d5266f2cdb24c3b91f4023070ab7848381417678e7a289a1d52a/pymupdf-1.28.2.tar.gz", hash = "sha256:5e0be7908a715aa20333caddd73f1d6f01e4cd0c26e869fa2dd0b7f344da2249", size = 87903557, upload-time = "2026-08-06T21:43:23.321Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/b4/51/550c9a75c4ff3245cb4ecb7bb95cbe2ab7374230b8e2b7a1f7259444150b/pymupdf-1.28.2-cp310-abi3-macosx_10_15_x86_64.whl", hash = "sha256:5fc315b425ff1f7afdd1ea2f348205cb19b806767daae7ce4d64115799c2bae1", size = 24645079, upload-time = "2026-08-06T21:37:25.001Z" },+ { url = "https://files.pythonhosted.org/packages/fa/01/3591f781b417b382a8487a2356e927acfe858b1043bab0ec47f6805bb109/pymupdf-1.28.2-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:7113846b35dbf0a033f088e4f4fb543dabeb4b0b12c112966a1ca1ee2d5eacae", size = 23875605, upload-time = "2026-08-06T21:37:40.369Z" },+ { url = "https://files.pythonhosted.org/packages/d2/86/4a68f080b71b46802178346af46486e1697508e760855ff5f3b218a6dff7/pymupdf-1.28.2-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:3050a233dde1211efe89ada74e2add6238436434159f46097a1423aad2842545", size = 25095554, upload-time = "2026-08-06T21:37:58.485Z" },+ { url = "https://files.pythonhosted.org/packages/c7/06/dace3e27af26690cb20bead80dbac42941b0841eb689b8aabbd67dde16f0/pymupdf-1.28.2-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:397d6715c1f0df7548a92d0afd8ce370fc48fa47aeefac16be2bc04a16a8227f", size = 25762500, upload-time = "2026-08-06T21:38:17.438Z" },+ { url = "https://files.pythonhosted.org/packages/e5/61/4146dfa1d8172a1ce8d59f0eed94896ddefb8deb2274534d0522fbb8abf5/pymupdf-1.28.2-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:f89fb2d86d07d643a269f17a093105057e20c79c1d06c103b53600067b6d2b01", size = 25986309, upload-time = "2026-08-06T21:38:35.472Z" },+ { url = "https://files.pythonhosted.org/packages/52/60/1fb6e64676f7500ebe89054b9e5bbbe14d3101c92d5f1a40ac9a35227673/pymupdf-1.28.2-cp310-abi3-win32.whl", hash = "sha256:530ef543a3885b3b81cb72a854e7c5a625a9233201221132bb6c31698c6a2bdb", size = 18525353, upload-time = "2026-08-06T21:38:47.697Z" },+ { url = "https://files.pythonhosted.org/packages/4a/61/d563bbccba262f9dd6d2d35ccb72593648184d886188efb12d9ce8f34dd6/pymupdf-1.28.2-cp310-abi3-win_amd64.whl", hash = "sha256:ebd244918798502d7b4504c90410d1711a4d7675a32584ca30f1bab419ecbffe", size = 19826532, upload-time = "2026-08-06T21:39:00.213Z" },+ { url = "https://files.pythonhosted.org/packages/e2/93/08f404a1f0155fe24137cf2d3aabd3e2b4b08c62053ed89c60f2611be3e9/pymupdf-1.28.2-cp310-abi3-win_arm64.whl", hash = "sha256:ffe91a24edc75c80da2a4b62f50fc0f54632d34fc8fe4cbc48e5c7ff07cf8fb4", size = 19759252, upload-time = "2026-08-06T21:39:12.937Z" },+ { url = "https://files.pythonhosted.org/packages/58/8c/d897dcd32a25b58186c968b15ce4324ca029e9d96460de12325314e390be/pymupdf-1.28.2-cp313-abi3-pyemscripten_2025_0_wasm32.whl", hash = "sha256:2e1b574c0fd2cb238021033fd3c0f9c4388816638df064e4bfb56d9d81736dc8", size = 18399403, upload-time = "2026-08-06T21:39:25.008Z" },+ { url = "https://files.pythonhosted.org/packages/f6/f1/de34a1c53fe2bf8c6e71db84b0ced782d408970c9810d2b456a2ae96814c/pymupdf-1.28.2-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:fd481ed48bef56305c41fb7e05a055c03345c899c7b101dad086258b438f8168", size = 25802333, upload-time = "2026-08-06T21:39:41.426Z" },+]