"""Live browser-engine probes: can this machine actually run each engine? Config-free (pure Playwright) so both the doctor CLI and standalone scripts can import it without pulling in application settings. Each probe launches the engine exactly the way ``browser.manager`` does, renders a data: URL page, evaluates JS, and takes a screenshot — a real end-to-end engine check. """ from __future__ import annotations import asyncio import os import time import uuid from pathlib import Path from typing import Any REPO = Path(__file__).resolve().parents[3] # backend/ (same depth as errors.py) RUNTIME = REPO / ".browser-runtime" BROWSERS = RUNTIME / "playwright-browsers" TMP = RUNTIME / "tmp" PROFILES = RUNTIME / "probe-profiles" # The compatibility flags manager.py already scopes to Firefox. MOZ_ENV = { "MOZ_DISABLE_CONTENT_SANDBOX": "1", "MOZ_DISABLE_GFX_SANDBOX": "1", "MOZ_DISABLE_RDD_SANDBOX": "1", "MOZ_DISABLE_SOCKET_PROCESS_SANDBOX": "1", } PROBE_HTML = ( "data:text/html,probe

engine-probe-ok

" ) def prepare_runtime_env() -> None: """Mirror manager._prepare_runtime: redirect caches and temp into the app runtime root so probes exercise the same paths the server uses.""" for directory in (BROWSERS, TMP, PROFILES): directory.mkdir(parents=True, exist_ok=True) os.environ["PLAYWRIGHT_BROWSERS_PATH"] = str(BROWSERS) for key in ("TEMP", "TMP", "TMPDIR"): os.environ[key] = str(TMP) async def _exercise(page: Any, label: str) -> dict[str, Any]: """Prove the page really renders: JS eval + title + screenshot.""" await page.goto(PROBE_HTML, wait_until="domcontentloaded", timeout=20000) heading = await page.inner_text("#h") title = await page.title() shot_path = RUNTIME / "screenshots" / f"probe_{label}_{int(time.time())}.png" shot_path.parent.mkdir(parents=True, exist_ok=True) await page.screenshot(path=str(shot_path), type="png") if heading.strip() != "engine-probe-ok": raise AssertionError(f"{label}: JS eval mismatch: {heading!r}") if title != "probe": raise AssertionError(f"{label}: title mismatch: {title!r}") return { "heading": heading, "title": title, "screenshot": str(shot_path), "screenshot_bytes": shot_path.stat().st_size, } async def probe_engine(engine: str, headless: bool = True) -> dict[str, Any]: """Launch one engine (chromium | chrome | msedge | firefox) and exercise it. The verdict requires outliving the 4-second liveness window: this environment has shown Firefox aborting ~2.6s after launch (denied child-process spawn -> 0xC0000005), so a fast data-URL-only check would report a false PASS. """ from playwright.async_api import async_playwright prepare_runtime_env() engine = engine.lower() label = { "chromium": "chromium (Playwright bundled)", "chrome": "chrome (installed Google Chrome)", "msedge": "msedge (installed Microsoft Edge)", "firefox": "firefox (Playwright bundled Mozilla engine)", }.get(engine, engine) pw = await async_playwright().start() profile = PROFILES / f"{engine}_{uuid.uuid4().hex[:8]}" started = time.monotonic() browser = None try: try: if engine == "firefox": browser = await pw.firefox.launch( headless=headless, env={**os.environ, **MOZ_ENV} ) context = await browser.new_context(viewport={"width": 1280, "height": 720}) page = await context.new_page() else: options: dict[str, Any] = { "user_data_dir": str(profile), "headless": headless, "viewport": {"width": 1280, "height": 720}, } # Mirror manager._browser_engine exactly: the bundled engine # also goes through channel="chromium" (plain headless would # want the chromium_headless_shell build instead). options["channel"] = "chromium" if engine == "chromium" else engine context = await pw.chromium.launch_persistent_context(**options) browser = context.browser page = context.pages[0] if context.pages else await context.new_page() facts = await _exercise(page, engine) # Liveness window: the Firefox abort fires ~2.6s after launch. await asyncio.sleep(4) connected = getattr(browser, "is_connected", None) if callable(connected) and not connected(): raise RuntimeError( "browser process exited shortly after launch (child-process " "spawn denied in this environment)" ) version = browser.version if browser is not None else "unknown" return { "engine": label, "key": engine, "ok": True, "headless": headless, "version": version, "seconds": round(time.monotonic() - started, 1), **facts, } finally: if browser is not None: await browser.close() except Exception as exc: # noqa: BLE001 — the probe reports, never raises return { "engine": label, "key": engine, "ok": False, "headless": headless, "seconds": round(time.monotonic() - started, 1), "error": f"{type(exc).__name__}: {exc}"[:1500], } finally: await pw.stop()