Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
test(cdp): gate every smoke group on real Chromium
ldm0926785f45af1
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 84d4456d3..259b217bd 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -402,7 +402,8 @@ jobs:cdp-smoke:name: CDP smoke- needs: [resolve-refs, build-release-head]+ needs: [resolve-refs, build-release-head, cdp-smoke-chromium]+ if: ${{ !cancelled() && needs.resolve-refs.result == 'success' && needs.build-release-head.result == 'success' }}runs-on: ubuntu-latesttimeout-minutes: 60container: rust:1.96.1-bookworm@@ -435,7 +436,12 @@ jobs:run: |export MOLI_BIN="$PWD/target/ci-bin/moli-release-head/moli"uv run --project moli-cdp-smoke --no-sync moli-cdp-smoke \- --jobs 4 --output-dir target/smoke/cdp-ci+ --browser moli --jobs 4 --output-dir target/smoke/cdp-ci+ - name: Require full Chromium smoke+ if: ${{ always() }}+ env:+ CHROMIUM_SMOKE_RESULT: ${{ needs.cdp-smoke-chromium.result }}+ run: test "$CHROMIUM_SMOKE_RESULT" = success- name: Upload diagnosticsif: ${{ always() }}continue-on-error: true@@ -446,6 +452,47 @@ jobs:if-no-files-found: warnretention-days: 7+ cdp-smoke-chromium:+ name: CDP smoke (Chromium)+ needs: [resolve-refs]+ runs-on: ubuntu-latest+ timeout-minutes: 30+ container: rust:1.96.1-bookworm+ steps:+ - uses: actions/checkout@v4+ with:+ persist-credentials: false+ ref: ${{ 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: moli-cdp-smoke/uv.lock+ - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0+ with:+ node-version: 24.15.0+ cache: npm+ cache-dependency-path: moli-cdp-smoke/package-lock.json+ - name: Install dependencies and locked Chromium+ run: |+ uv sync --project moli-cdp-smoke --locked+ npm ci --prefix moli-cdp-smoke+ uv run --project moli-cdp-smoke --no-sync playwright install --with-deps chromium+ - name: Run full CDP smoke on Chromium+ run: |+ uv run --project moli-cdp-smoke --no-sync moli-cdp-smoke \+ --browser chromium --jobs 4 --output-dir target/smoke/cdp-chromium-ci+ - name: Upload Chromium diagnostics+ if: ${{ always() }}+ continue-on-error: true+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: cdp-smoke-chromium-diagnostics+ path: target/smoke/cdp-chromium-ci+ if-no-files-found: warn+ retention-days: 7+native-pdf:name: Native PDF rendering and linksneeds: [resolve-refs, build-release-head]diff --git a/moli-cdp-smoke/README.md b/moli-cdp-smoke/README.mdindex 8aceea40d..f7516cd9c 100644--- a/moli-cdp-smoke/README.md+++ b/moli-cdp-smoke/README.md@@ -6,6 +6,52 @@ The suite covers real CDP-client workflows: `connect_over_cdp`, concurrent brows## Chromium Behavior Evidence+CI runs the entire default group list twice: `CDP smoke` uses the HEAD Moli+release and `CDP smoke (Chromium)` uses the Chromium revision bundled with the+Playwright version in `uv.lock`. Both jobs select all default groups, including+newly registered groups, without maintaining separate allowlists. The+`chromium-cdp` group is a collection of protocol scenarios; its name alone does+not identify the browser under test.+The existing `CDP smoke` check also requires the Chromium job to succeed, so it+cannot remain green when the Chromium suite fails.++Each worker records the actual discovery version, engine, executable command,+and PID for its managed browser and any nested browser launches. Chromium+workers reject Moli server and CLI launches. Empty scenario lists, failed+scenarios, and `not_applicable`/`applicable: false` results fail the supervisor.+Use managed `--browser chromium` runs for the full oracle, including process+resource sampling; sharing an external `--endpoint` does not provide the same+process isolation or owned PID.++Lifecycle artifacts retain total FDs for both engines. Chromium also records+FDs for regular files inside its owned profile: delayed database initialization+opens these independently of target churn. Its fixed FD budget covers the+remaining descriptors; eventpoll, eventfd, and thread budgets remain separate.+Moli's original all-FD budget is unchanged.++The full-suite calibration on 2026-10-19 used Playwright 1.58.0's Chrome for+Testing 145.0.7632.6, Node 24.15.0, fresh headless profiles, and local fixtures.+The browser command disables the back/forward cache because the history+scenarios explicitly test document requests and their response lifecycle.+Authentication scenarios use fresh browser contexts to prevent cached Basic+credentials from bypassing a later challenge. Worker Network events are+collected from Worker sessions in Chromium and from the owning Page in Moli.++Some existing scenarios test Moli policies or extensions. These keep explicit+expectations for each engine; running all groups does not assert feature parity+or identical scenario counts:++| Boundary | Moli | Pinned Chromium |+| --- | --- | --- |+| Screen layout / wheel scheduling | Frozen layout and fixed action window | Live layout, per-event microtasks and observer updates |+| Scrollbar startup / emulation | CLI/environment matrix; current document updates immediately | Default visible, `--hide-scrollbars`; emulation applies on navigation |+| Locale/timezone across contexts | Shared process defaults and exclusive claims | Independent renderer defaults and claims |+| Fetch body streams | Buffered seeking and explicit rejection of continuation after body take | Sequential reads; EOF may require a separate empty read |+| WebSocket events and URL blocking | Extra generic request events, payload lengths, and WebSocket URL blocking | Dedicated WebSocket events and payload data; URL blocking excludes WebSockets |+| Hosted file URLs | Capability error before navigation/interception | File navigation and interception; missing file returns `ERR_FILE_NOT_FOUND` |+| Other capability boundaries | Stack timing privacy, unsupported drag/CPU throttling, PI rename extension | Observed stack timing, successful drag/throttling, rejected PI rename |+| Response/manifest/idle details | Plaintext TextTrack bodies, document-relative data manifest URLs, same-site idle persistence | Base64 TextTrack bodies, data manifest URL fallbacks, cross-document idle reset |+Any smoke assertion described as Chromium-compatible must be verified against areal Chromium binary. Do not infer observable behavior solely from thespecification, Chromium source code, an existing Moli test, or intuition.@@ -607,7 +653,7 @@ Near-term expansion order:## Running-Build moli from the repository root first:+For Moli runs, build the binary from the repository root first:```bashcargo build -p moli@@ -627,15 +673,17 @@ uv run moli-cdp-smokeWith no `--group`, the supervisor executes every raw, Playwright page, browser,and repository-managed external-client group, including `inspector-routing`and the pinned Puppeteer client. Every group runs in a separate worker process-with its own Moli process, fixture server, HTTP cache, Playwright context, and+with its own selected browser process, fixture server, cache/profile, Playwright context, andtemporary directories. One failed or wedged group therefore cannot retainstate or child processes for the next group.The default concurrency is one worker. Use bounded parallelism explicitly;-CI runs the same unfiltered suite with four workers:+CI runs the same unfiltered suite with four workers on both engines:```bash-uv run moli-cdp-smoke --jobs 4+MOLI_BIN=../target/release/moli uv run moli-cdp-smoke --browser moli --jobs 4+uv run playwright install --with-deps chromium+uv run moli-cdp-smoke --browser chromium --jobs 4```Each run writes `summary.json` plus one log and one result JSON per worker under@@ -643,7 +691,7 @@ Each run writes `summary.json` plus one log and one result JSON per worker under`--timeout` to change the per-worker wall-clock limit. The worker also retainsits own protocol-operation timeouts, so the wall limit is a final process-levelsafety boundary rather than the primary synchronization mechanism. Supervised-worker logs include the live `moli serve` stdout/stderr stream, so the last+worker logs include the live browser stdout/stderr stream, so the lastrenderer messages survive even when the supervisor terminates a wedged worker.For failed workers, the supervisor prints the saved error/traceback before thelog tail, so CI output includes the cause even when the worker log only reports@@ -782,13 +830,15 @@ MOLI_BIN=../target/release/moli uv run moli-cdp-smokeUseful environment variables:- `MOLI_BIN`: path to the `moli` binary under test.+- `CHROMIUM_BIN` / `--chromium-bin`: optional executable override for+ `--browser chromium`; otherwise use the locked Playwright browser.- `MOLI_CDP_PORT`: fixed CDP server port for single-worker debugging. Bydefault every worker uses `--port 0` and reads the OS-selected endpoint fromMoli's bound-listener log. A fixed port is rejected with parallel workers.- `MOLI_SMOKE_GROUPS`: comma-separated smoke group list. CLI `--group` takes precedence.- `MOLI_INSPECTOR_ROUTING_SCENARIOS`: comma-separated scenario names within the `inspector-routing` group.- `MOLI_SMOKE_TRACE=1`: print extra runner-side trace logs.-- `MOLI_SMOKE_TRACE_BG=1`: print background `moli serve` logs when invoking a+- `MOLI_SMOKE_TRACE_BG=1`: print background browser logs when invoking aworker directly. The supervisor enables this automatically because itpersists each worker's combined output as a diagnostic artifact.- `NODE`: Node executable used by optional Node client groups. Defaults to `node`.@@ -800,7 +850,8 @@ Useful environment variables:- `STAGEHAND_VERSION`: exact Stagehand version gate. Defaults to `3.7.0`.- `AGENT_BROWSER_BIN`: agent-browser CLI used by the optional external group. Defaults to `agent-browser` on `PATH`.-This smoke connects to moli over CDP, so it does not need Playwright-managed browser binaries.+Moli runs do not need Playwright-managed browser binaries. Chromium runs require+the browser installed by the locked Playwright version, or an explicit override.The runner starts `moli serve` with `--layout --resource` so screenshotcoverage uses the real renderer and the Chromium-derived Network matrix canobserve every optional resource family, including images, audio, video, anddiff --git a/moli-cdp-smoke/moli_cdp_smoke/config.py b/moli-cdp-smoke/moli_cdp_smoke/config.pyindex 69140613d..35360b86f 100644--- a/moli-cdp-smoke/moli_cdp_smoke/config.py+++ b/moli-cdp-smoke/moli_cdp_smoke/config.py@@ -18,6 +18,11 @@ TRACE_BACKGROUND_PROCESS_ENV = "MOLI_SMOKE_TRACE_BG"REPO_ROOT = Path(__file__).resolve().parents[2]+def is_moli_browser() -> bool:+ # The worker sets this only after checking the actual discovery endpoint.+ return os.environ.get("MOLI_SMOKE_BROWSER", "moli") == "moli"++def clear_proxy_env(env: dict[str, str]) -> dict[str, str]:next_env = dict(env)for key in PROXY_ENV_KEYS:@@ -41,6 +46,8 @@ def reserve_port() -> int:def moli_binary() -> Path:+ if not is_moli_browser():+ raise RuntimeError("a Chromium smoke worker must not invoke the Moli CLI")override = os.environ.get("MOLI_BIN")if override:return Path(override).expanduser().resolve()diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/action_window.py b/moli-cdp-smoke/moli_cdp_smoke/groups/action_window.pyindex 3feee4285..21c4f68ed 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/action_window.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/action_window.py@@ -6,7 +6,7 @@ import jsonimport urllib.requestfrom typing import Any-from ..assertions import SmokeError, assert_equal, record, record_contract+from ..assertions import SmokeError, assert_equal, record, record_contract, wait_untilfrom ..png_image import DecodedPng, decode_pngfrom ..raw_cdp import RawCdpClient, connect_raw_cdp, discover_websocket_url@@ -525,18 +525,15 @@ async def run_action_window_group(results: list[dict[str, Any]],) -> None:websocket_url = await discover_websocket_url(endpoint)- if not websocket_url.endswith("/devtools/browser/moli-browser"):- record(- results,- "raw_cdp_action_window_moli_policy_not_applicable",- {"engine": "chromium", "applicable": False},- )- return+ is_moli = websocket_url.endswith("/devtools/browser/moli-browser")client = await connect_raw_cdp(endpoint)context_id: str | None = Nonetry:context_id, session_id = await _open_target(client)+ if not is_moli:+ await _run_chromium_action_window(client, session_id, fixture, results)+ returnawait _run_deadline_contract(client, session_id, fixture, results)await _run_overflow_container_contract(client, session_id, fixture, results)await _run_capture_barrier_contract(client, session_id, fixture, results)@@ -552,3 +549,60 @@ async def run_action_window_group(except Exception:passawait client.websocket.close()+++async def _run_chromium_action_window(+ client: RawCdpClient, session: str, fixture: str, results: list[dict[str, Any]],+) -> None:+ async def value(expression: str) -> Any:+ return await _evaluate_json(client, session, "JSON.stringify(" + expression + ")")++ async def equals(expression: str, expected: Any) -> None:+ async def ready() -> bool:+ return await value(expression) == expected+ await wait_until(ready, f"Chromium {expression} == {expected!r}")++ await _reset_witness(fixture)+ await _navigate(client, session, f"{fixture}/action-window-deadline")+ await _capture_png(client, session)+ await _wait_for_intersections(client, session, [False])+ intersections = [False]+ for delta, position, visible in [(100, 100, True), (-100, 0, False), (100, 100, True)]:+ await _dispatch_wheel(client, session, delta)+ await equals("scrollY", position)+ intersections.append(visible)+ await _wait_for_intersections(client, session, intersections)+ log = [f"{phase}:{delta}" for delta in [100, -100, 100] for phase in ["event", "microtask"]]+ await equals("__actionWindowWheelLog", log)+ record(results, "raw_cdp_action_window_chromium_live_events", {"wheelLog": log, "ioLog": intersections})++ await _navigate(client, session, f"{fixture}/action-window-overflow")+ await _capture_png(client, session)+ await _dispatch_wheel(client, session, 60, x=50, y=50)+ await equals("[scroller.scrollLeft,scroller.scrollTop]", [0, 60])+ await _dispatch_wheel(client, session, 0, delta_x=45, x=50, y=50)+ await equals("[scroller.scrollLeft,scroller.scrollTop]", [45, 60])+ assert_equal(await value("[scrollX,scrollY,__actionWindowOverflowDeltas]"),+ [0, 0, [[0, 60], [45, 0]]], "Chromium overflow wheel axes")+ record(results, "raw_cdp_action_window_chromium_overflow_axes")++ await _reset_witness(fixture)+ await _navigate(client, session, f"{fixture}/action-window-capture")+ assert_equal((await _capture_png(client, session)).pixel(10, 10), (255, 255, 255, 255), "Chromium initial capture")+ for index, (delta, color) in enumerate([(10, (255, 0, 0, 255)), (20, (0, 255, 0, 255))], 1):+ await _dispatch_wheel(client, session, delta)+ await _wait_for_witness(fixture, index)+ assert_equal((await _capture_png(client, session)).pixel(10, 10), color, "Chromium capture after wheel")+ await equals("scrollY", 30)+ assert_equal(await value("__actionWindowCaptureDeltas"), [10, 20], "Chromium capture deltas")+ record(results, "raw_cdp_action_window_chromium_capture")++ await _navigate(client, session, f"{fixture}/action-window-replacement")+ await _capture_png(client, session)+ await _dispatch_wheel(client, session, 10)+ await equals("__actionWindowRetiredDeltas", [10])+ for delta in [20, 30]:+ await _dispatch_wheel(client, session, delta)+ await equals("__actionWindowReplacementDeltas", [20, 30])+ assert_equal(await value("__actionWindowRetiredDeltas"), [10], "retired Document gets no later wheel")+ record(results, "raw_cdp_action_window_chromium_document_replacement")diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/browser_semantics.py b/moli-cdp-smoke/moli_cdp_smoke/groups/browser_semantics.pyindex ca6035bd4..bd5d61345 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/browser_semantics.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/browser_semantics.py@@ -5,6 +5,7 @@ from contextlib import asynccontextmanagerfrom typing import Any, AsyncIterator, Awaitable, Callablefrom ..assertions import SmokeError, assert_equal, record_contract, wait_until+from ..config import is_moli_browserfrom ..helpers import attach_cdp_event_collectorfrom ..progress import await_with_progressfrom ..state import SmokeState@@ -978,30 +979,42 @@ async def _dom_mutation_events_and_edit_commands(state: SmokeState) -> dict[str,cdp.send("DOM.requestNode", {"objectId": pi_object}),))["nodeId"]- pi_rename_result, pi_rename_order = await send_and_require_events(- "DOM.setNodeName-processing-instruction",- "DOM.setNodeName",- {"nodeId": pi_node_id, "name": "xml"},- ["DOM.childNodeRemoved", "DOM.childNodeInserted"],- )- pi_rename_insert = next(- item- for item in pi_rename_order- if item.get("method") == "DOM.childNodeInserted"- )- assert_equal(- pi_rename_result["nodeId"],- pi_rename_insert["params"]["node"]["nodeId"],- "DOM.setNodeName processing-instruction node id",- )- assert_equal(- await step(- "Runtime.evaluate-processing-instruction-target",- page.evaluate("document.firstChild.target"),- ),- "xml",- "DOM.setNodeName processing-instruction xml target",- )+ pi_rename_order = []+ if is_moli_browser():+ pi_rename_result, pi_rename_order = await send_and_require_events(+ "DOM.setNodeName-processing-instruction",+ "DOM.setNodeName",+ {"nodeId": pi_node_id, "name": "xml"},+ ["DOM.childNodeRemoved", "DOM.childNodeInserted"],+ )+ pi_rename_insert = next(+ item+ for item in pi_rename_order+ if item.get("method") == "DOM.childNodeInserted"+ )+ assert_equal(+ pi_rename_result["nodeId"],+ pi_rename_insert["params"]["node"]["nodeId"],+ "DOM.setNodeName processing-instruction node id",+ )+ assert_equal(+ await step(+ "Runtime.evaluate-processing-instruction-target",+ page.evaluate("document.firstChild.target"),+ ),+ "xml",+ "DOM.setNodeName processing-instruction xml target",+ )+ else:+ try:+ await cdp.send("DOM.setNodeName", {"nodeId": pi_node_id, "name": "xml"})+ except Exception as error:+ if "Node is not an Element" not in str(error):+ raise+ else:+ raise SmokeError("Chromium unexpectedly renamed a processing instruction")+ assert_equal(await page.evaluate("document.firstChild.target"), "old-target",+ "rejected PI rename leaves the document unchanged")return {"runtimeOrder": [item["method"] for item in shallow_runtime_order],diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/chromium_cdp_network.py b/moli-cdp-smoke/moli_cdp_smoke/groups/chromium_cdp_network.pyindex 2e55c1c73..1d057ef82 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/chromium_cdp_network.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/chromium_cdp_network.py@@ -6,6 +6,7 @@ from typing import Anyfrom urllib.parse import urlsplitfrom . import SmokeStatefrom ..assertions import SmokeError, assert_equal, wait_until+from ..config import is_moli_browserfrom ..fixture import FixtureServerfrom ..helpers import attach_cdp_event_collector, run_worker_command@@ -1511,7 +1512,7 @@ async def _verify_failed_main_document_request_extra_info_on_session()assert_equal(state.fixture_server.request_count(route),- 1,+ 1 if is_moli_browser() else 2,"failed Document fixture request count",)loading_failed = next(diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/chromium_cdp_page.py b/moli-cdp-smoke/moli_cdp_smoke/groups/chromium_cdp_page.pyindex f000eb49d..6671fe289 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/chromium_cdp_page.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/chromium_cdp_page.py@@ -2,6 +2,7 @@ from __future__ import annotationsfrom typing import Anyfrom urllib.parse import urlsplitfrom . import SmokeState+from ..config import is_moli_browserfrom ..assertions import SmokeError, assert_equal, wait_untilfrom ..fixture import FixtureServerfrom ..helpers import capture_layout@@ -177,7 +178,7 @@ async def _verify_chromium_idle_override_sample(state: SmokeState) -> None:"(async()=>{const d=new IdleDetector();await d.start();return [d.userState,d.screenState]})()",await_promise=True,),- ["idle", "locked"],+ ["idle", "locked"] if is_moli_browser() else ["active", "unlocked"],"same-origin cross-document navigation should preserve idle override",)@@ -191,7 +192,7 @@ async def _verify_chromium_idle_override_sample(state: SmokeState) -> None:"(async()=>{const d=new IdleDetector();await d.start();return [d.userState,d.screenState]})()",await_promise=True,),- ["idle", "locked"],+ ["idle", "locked"] if is_moli_browser() else ["active", "unlocked"],"same-site cross-origin navigation should preserve idle override",)@@ -514,7 +515,7 @@ async def _verify_chromium_page_get_app_manifest_sample(state: SmokeState) -> Noassert_equal(embedded.get("url"), data_manifest_url, "data manifest URL")assert_equal(embedded_manifest.get("startUrl"),- expected_embedded_base + "relative-start",+ expected_embedded_base + "relative-start" if is_moli_browser() else dynamic_url,"data manifest document-relative start URL",)assert_equal(@@ -524,7 +525,7 @@ async def _verify_chromium_page_get_app_manifest_sample(state: SmokeState) -> No)assert_equal((embedded_manifest.get("icons") or [{}])[0].get("url"),- expected_embedded_base + "icon.png",+ expected_embedded_base + "icon.png" if is_moli_browser() else None,"data manifest document-relative icon URL",)state.record("chromium_page_get_app_manifest_sample")diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/chromium_cdp_performance.py b/moli-cdp-smoke/moli_cdp_smoke/groups/chromium_cdp_performance.pyindex 3c34cc9da..960a0c488 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/chromium_cdp_performance.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/chromium_cdp_performance.py@@ -1,6 +1,7 @@from __future__ import annotationsfrom typing import Anyfrom . import SmokeState+from ..config import is_moli_browserfrom ..assertions import SmokeError, assert_equal, wait_untilfrom ..helpers import attach_cdp_event_collector@@ -144,8 +145,10 @@ async def _verify_cpu_throttling_capability_multiple_pages_sample(state: SmokeSterror = await _send_cdp_expect_optional_error(cdp, "Emulation.setCPUThrottlingRate", {"rate": rate})- if not error or "CPU throttling is not supported" not in str(error):+ if is_moli_browser() and (not error or "CPU throttling is not supported" not in str(error)):raise SmokeError(f"CPU rate {rate} should report unsupported: {error}")+ if not is_moli_browser():+ assert_equal(error, None, "Chromium accepts CPU throttling")for neutral_rate in [1.0, 0.5, 0.0, -1.0]:result = await cdp.send("Emulation.setCPUThrottlingRate", {"rate": neutral_rate})assert_equal(result, {}, f"CPU rate {neutral_rate} disables throttling")@@ -207,8 +210,10 @@ async def _verify_profiler_after_rejected_cpu_throttling_sample(state: SmokeStaterror = await _send_cdp_expect_optional_error(state.cdp, "Emulation.setCPUThrottlingRate", {"rate": 4.0})- if not error or "CPU throttling is not supported" not in str(error):+ if is_moli_browser() and (not error or "CPU throttling is not supported" not in str(error)):raise SmokeError(f"CPU throttling while profiling should report unsupported: {error}")+ if not is_moli_browser():+ assert_equal(error, None, "Chromium accepts CPU throttling while profiling")burn = await state.cdp.send("Runtime.evaluate",{@@ -236,6 +241,7 @@ async def _verify_profiler_after_rejected_cpu_throttling_sample(state: SmokeStatprofile_result = await state.cdp.send("Profiler.stop")finally:await state.cdp.send("Profiler.disable")+ await state.cdp.send("Emulation.setCPUThrottlingRate", {"rate": 1})profile = profile_result.get("profile") or {}nodes = profile.get("nodes") or []diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/core.py b/moli-cdp-smoke/moli_cdp_smoke/groups/core.pyindex 86ca26f7c..1b4ec428e 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/core.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/core.py@@ -6,6 +6,7 @@ from playwright.async_api import TimeoutError as PlaywrightTimeoutErrorfrom . import SmokeStatefrom ..assertions import SmokeError, assert_equal, wait_until+from ..config import is_moli_browserfrom ..helpers import capture_layout, attach_cdp_event_collector@@ -174,7 +175,7 @@ async def run_core_group(state: SmokeState) -> None:for suffix in ("/backend-api/f/conversation/prepare","/backend-api/f/conversation",- "/ws-chatgpt-live?conversation_id=smoke-live",+ *(("/ws-chatgpt-live?conversation_id=smoke-live",) if is_moli_browser() else ()),):request = next((@@ -192,6 +193,17 @@ async def run_core_group(state: SmokeState) -> None:live_loader_id,f"ChatGPT-like live channel subresource loaderId for {suffix}",)+ if not is_moli_browser():+ socket_url = fixture.replace("http:", "ws:", 1) + "/ws-chatgpt-live?conversation_id=smoke-live"+ created = next((e for e in state.websocket_events if e["method"] == "Network.webSocketCreated"+ and e["params"].get("url") == socket_url), None)+ if created is None:+ raise SmokeError("missing live channel Network.webSocketCreated")+ socket_id = created["params"]["requestId"]+ await wait_until(lambda: any(e["method"] == "Network.webSocketHandshakeResponseReceived"+ and e["params"].get("requestId") == socket_id+ and e["params"].get("response", {}).get("status") == 101+ for e in state.websocket_events), "live channel WebSocket handshake")state.record("chatgpt_like_live_channel_dom")await page.goto(f"{fixture}/chatgpt-client-id-map-page", wait_until="load", timeout=10_000)diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/dom_input.py b/moli-cdp-smoke/moli_cdp_smoke/groups/dom_input.pyindex 45ae22afa..713bd7c92 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/dom_input.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/dom_input.py@@ -9,6 +9,7 @@ from playwright.async_api import Error as PlaywrightError, expectfrom . import SmokeStatefrom ..helpers import capture_layout+from ..config import is_moli_browserfrom ..assertions import SmokeError, assert_equal, wait_untilfrom ..progress import await_with_progress@@ -395,11 +396,13 @@ async def run_locator_input_workflows(state: SmokeState) -> None:)assert_equal(form_state, {"checked": True, "radio": "b", "select": "two"}, "checkbox/radio/select state")- await _expect_drag_interception_boundary(- page.locator("#drag").drag_to(page.locator("#drop"), timeout=1_000),- "Playwright locator.drag_to drag interception boundary",- )- assert_equal(await page.text_content("#drop"), "drop", "unsupported drag/drop does not dispatch")+ drag = page.locator("#drag").drag_to(page.locator("#drop"), timeout=1_000)+ if is_moli_browser():+ await _expect_drag_interception_boundary(drag, "Moli drag interception boundary")+ assert_equal(await page.text_content("#drop"), "drop", "unsupported drag/drop does not dispatch")+ else:+ await drag+ assert_equal(await page.text_content("#drop"), "dragged-value", "Chromium drag/drop dispatches")state.record("locator_input_workflows")@@ -2038,9 +2041,32 @@ async def run_touch_input_workflows(state: SmokeState) -> None:cdp = state.cdpasync def expect_invalid_params(method: str, params: dict[str, object]) -> None:+ if not is_moli_browser() and (+ params.get("modifiers") == 256 or params.get("button") == "middle"+ ):+ assert_equal(await cdp.send(method, params), {}, "Chromium accepts this input range")+ returnerror = await _expect_playwright_error(cdp.send(method, params))- if "InvalidParams" not in error:- raise SmokeError(f"{method}: expected InvalidParams, got: {error}")+ expected = "InvalidParams"+ if not is_moli_browser():+ expected = "Invalid parameters"+ event_type = str(params.get("type", ""))+ if event_type[:1].isupper():+ expected = f"Unexpected event type '{event_type}'"+ elif params.get("gestureSourceType") == "Touch":+ expected = "Unknown gestureSourceType"+ elif event_type == "mouseWheel":+ expected = "'deltaX' and 'deltaY' are expected for mouseWheel event"+ elif params.get("force") == 2:+ expected = "'force' should be in the range of [0,1]"+ elif method == "Input.dispatchTouchEvent":+ expected = {+ "touchStart": "TouchStart and TouchMove must have at least one touch point." if not params.get("touchPoints") else "All or none of the provided TouchPoints must supply ids.",+ "touchCancel": "TouchCancel must not have any touch points.",+ "touchEnd": "Must send a TouchStart first to start a new touch.",+ }.get(event_type, expected)+ if expected not in error:+ raise SmokeError(f"{method}: expected {expected!r}, got: {error}")await page.evaluate("""html => {diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/layout_policy.py b/moli-cdp-smoke/moli_cdp_smoke/groups/layout_policy.pyindex d88b60ad1..10b77d199 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/layout_policy.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/layout_policy.py@@ -11,9 +11,10 @@ from typing import Any, AsyncIterator, Awaitable, Callablefrom urllib.parse import quotefrom ..assertions import SmokeError, assert_equal, record+from ..config import is_moli_browserfrom ..pdf_document import assert_pdf_envelopefrom ..png_image import decode_png-from ..raw_cdp import RawCdpClient, connect_raw_cdp, discover_websocket_url+from ..raw_cdp import RawCdpClient, connect_raw_cdpfrom .layout_screenshot import _capture, _open_target, _response_for_id, _success, _wait_for_load@@ -25,7 +26,8 @@ body { margin: 0; height: 1200px }</style><div id="probe" tabindex="0"></div><script>window.inputEvents = [];-for (const name of ['mousemove','wheel','touchstart','dragenter','click']) {+document.addEventListener('dragover', event => event.preventDefault());+for (const name of ['mousemove','wheel','touchstart','dragenter','dragover','click']) {document.addEventListener(name, event => {inputEvents.push(name);if (name === 'wheel' || name === 'dragenter') event.preventDefault();@@ -68,6 +70,12 @@ async def _fresh_probe(client: RawCdpClient) -> AsyncIterator[Probe]:# query, screenshot, or screencast may warm a case before its first command.target, session = await _open_target(client, DATA_URL)try:+ if not is_moli_browser():+ # Chromium hit testing uses the compositor surface. Wait for the+ # initial rendered document before probing its live layout policy.+ await _success(client, "Page.bringToFront", session_id=session)+ await _capture(client, session)+ await _success(client, "DOM.enable", session_id=session)remote, _, _ = await _success(client, "Runtime.evaluate", {"expression": "document.getElementById('probe')",}, session_id=session)@@ -89,11 +97,12 @@ async def _initializes_once(probe: Probe, operation: Operation) -> dict[str, Anyawait probe.set_width(120)# Read only after the mutation: returning 80 proves the tested command# published the first layout, rather than this assertion creating it.- assert_equal(await probe.width(), 80, "first demand published the 80px box")+ assert_equal(await probe.width(), 80 if is_moli_browser() else 120, "geometry after mutation")warm = await operation(probe, 1)- assert_equal(warm, initial, "warm command returned the original geometry")- assert_equal(await probe.width(), 80, "warm demand retained the 80px box")- return {"firstPublishedWidth": 80, "warmWidthAfterMutation": 80}+ if is_moli_browser():+ assert_equal(warm, initial, "warm command returned the original geometry")+ assert_equal(await probe.width(), 80 if is_moli_browser() else 120, "warm geometry")+ return {"firstPublishedWidth": 80, "warmWidthAfterMutation": await probe.width()}async def _does_not_publish(probe: Probe, operation: Operation) -> dict[str, Any]:@@ -102,8 +111,9 @@ async def _does_not_publish(probe: Probe, operation: Operation) -> dict[str, Anyassert_equal(await probe.width(), 120, "non-layout command left the page cold")await probe.set_width(160)await operation(probe, 1)- assert_equal(await probe.width(), 120, "non-layout command did not refresh a warm page")- return {"firstGeometryWidth": 120, "warmWidthAfterMutation": 120}+ expected = 120 if is_moli_browser() else (100 if operation is _attribute_width else 160)+ assert_equal(await probe.width(), expected, "geometry after second mutation")+ return {"firstGeometryWidth": 120, "warmWidthAfterMutation": await probe.width()}def _command(method: str, params: Callable[[Probe, int], dict[str, Any]] | None = None) -> Operation:@@ -118,17 +128,34 @@ def _script(expression: str) -> Operation:return run+async def _attribute_width(probe: Probe, phase: int) -> None:+ await probe.call("DOM.setAttributeValue", {"nodeId": probe.node_id, "name": "style", "value": "width:100px"})+++async def _idle_touch_end(probe: Probe, phase: int) -> None:+ if is_moli_browser():+ await probe.call("Input.dispatchTouchEvent", {"type": "touchEnd", "touchPoints": []})+ else:+ identifier = await probe.client.send("Input.dispatchTouchEvent", {"type": "touchEnd", "touchPoints": []}, session_id=probe.session)+ response, _ = await _response_for_id(probe.client, identifier)+ assert_equal(response.get("error"), {"code": -32602, "message": "Must send a TouchStart first to start a new touch."}, "idle touch end validation")++def _input(method: str, params: dict[str, Any], event: str) -> Operation:async def run(probe: Probe, phase: int) -> None:await probe.evaluate("inputEvents.length = 0")actual = dict(params)+ expected_event = event+ if method == "Input.dispatchDragEvent" and phase == 1:+ actual["type"] = "dragOver"+ expected_event = "dragover"if "x" in actual:actual["x"] += phaseawait probe.call(method, actual)deadline = asyncio.get_running_loop().time() + 4- while event not in await probe.evaluate("inputEvents"):+ while expected_event not in await probe.evaluate("inputEvents"):if asyncio.get_running_loop().time() >= deadline:- raise SmokeError(f"{method} did not dispatch {event}")+ raise SmokeError(f"{method} did not dispatch {event} in phase {phase}: " + str(await probe.evaluate("({events:inputEvents,focus:document.hasFocus(),rect:document.getElementById('probe').getBoundingClientRect().toJSON()})")))await asyncio.sleep(0.02)if method == "Input.dispatchTouchEvent":await probe.call(method, {"type": "touchEnd", "touchPoints": []})@@ -157,16 +184,18 @@ async def _style_sheet(probe: Probe, phase: int) -> None:sheet = next((message["params"]["header"] for message in seenif message.get("sessionId") == probe.sessionand message.get("method") == "CSS.styleSheetAdded"- and message["params"]["header"]["isInline"]), None)+ and (message["params"]["header"]["isInline"] if is_moli_browser()+ else message["params"]["header"]["origin"] == "regular")), None)if sheet is not None:breakseen = [await probe.client.recv()]params = {"styleSheetId": sheet["styleSheetId"]}- original = await probe.call("CSS.getStyleSheet", params)- text = original["styleSheet"]["text"] + "\nbody { color: rgb(1,2,3) }"+ method = "CSS.getStyleSheet" if is_moli_browser() else "CSS.getStyleSheetText"+ original = await probe.call(method, params)+ text = (original["styleSheet"]["text"] if is_moli_browser() else original["text"]) + "\nbody { color: rgb(1,2,3) }"await probe.call("CSS.setStyleSheetText", {**params, "text": text})- updated = await probe.call("CSS.getStyleSheet", params)- assert_equal(updated["styleSheet"]["text"], text, "stylesheet mutation applied")+ updated = await probe.call(method, params)+ assert_equal(updated["styleSheet"]["text"] if is_moli_browser() else updated["text"], text, "stylesheet mutation applied")async def _viewport(probe: Probe, phase: int) -> None:@@ -186,11 +215,11 @@ async def _screenshot(probe: Probe) -> dict[str, Any]:first, _ = await _capture(probe.client, probe.session)assert_equal(decode_png(first).pixel(120, 30), (255, 255, 255, 255), "cold screenshot narrow box")await probe.set_width(120)- assert_equal(await probe.width(), 80, "cold screenshot published screen layout")+ assert_equal(await probe.width(), 80 if is_moli_browser() else 120, "geometry after screenshot and mutation")second, _ = await _capture(probe.client, probe.session)assert_equal(decode_png(second).pixel(120, 30), (0, 255, 0, 255), "warm screenshot updated pixels")await probe.set_width(160)- assert_equal(await probe.width(), 120, "warm screenshot published refreshed layout")+ assert_equal(await probe.width(), 120 if is_moli_browser() else 160, "geometry after warm screenshot and mutation")return {"coldPublishedWidth": 80, "refreshedWidth": 120, "pixelsVerified": True}@@ -215,13 +244,13 @@ async def _screencast(probe: Probe) -> dict[str, Any]:_, _, seen = await _success(probe.client, "Page.startScreencast", {"format": "jpeg", "maxWidth": 400, "maxHeight": 300,}, session_id=probe.session)- event = await _frame(probe, seen, previous)+ event = await _frame(probe, seen, previous if is_moli_browser() else None)previous = event["params"]["sessionId"]if not base64.b64decode(event["params"]["data"], validate=True).startswith(b"\xff\xd8"):raise SmokeError("screencast frame did not contain JPEG data")await probe.call("Page.stopScreencast")await probe.set_width(mutation)- assert_equal(await probe.width(), published, "actual screencast frame published layout")+ assert_equal(await probe.width(), published if is_moli_browser() else mutation, "geometry after screencast and mutation")return {"firstFrameWidth": 80, "newFrameWidth": 120}@@ -231,7 +260,7 @@ async def _invalid_clip(probe: Probe) -> dict[str, Any]:"format": "png", "clip": {"x": 0, "y": 0, "width": 0, "height": 0, "scale": 1},}, session_id=probe.session)response, _ = await _response_for_id(probe.client, message_id)- assert_equal(response.get("error", {}).get("code"), -32602, "empty clip parameter error")+ assert_equal(response.get("error", {}).get("code"), -32602 if is_moli_browser() else -32000, "empty clip parameter error")return await _does_not_publish(probe, lambda _, phase: reject(phase))@@ -243,26 +272,29 @@ async def _live_metrics(probe: Probe) -> dict[str, Any]:"width": 900, "height": 500, "deviceScaleFactor": 1, "mobile": False,})warm = await probe.call("Page.getLayoutMetrics")- assert_equal(warm["cssContentSize"], initial["cssContentSize"], "content size remains frozen")+ if is_moli_browser():+ assert_equal(warm["cssContentSize"], initial["cssContentSize"], "content size remains frozen")+ else:+ assert_equal(warm["cssContentSize"]["height"], 1600, "Chromium updates content extent immediately")assert_equal(warm["cssLayoutViewport"]["clientWidth"], 900, "viewport remains live")assert_equal(warm["cssLayoutViewport"]["pageY"], 100, "scroll remains live")await _capture(probe.client, probe.session)refreshed = await probe.call("Page.getLayoutMetrics")assert_equal(refreshed["cssContentSize"]["height"], 1600, "capture updates content extent")assert_equal(refreshed["cssContentSize"]["width"], 900, "capture updates content width")- return {"coldContentHeight": 1200, "warmContentHeight": 1200, "refreshedContentHeight": 1600}+ return {"coldContentHeight": 1200, "warmContentHeight": warm["cssContentSize"]["height"], "refreshedContentHeight": 1600}async def _missing_box(probe: Probe) -> dict[str, Any]:assert_equal(await probe.width(), 80, "initial screen layout")await probe.evaluate("const late = document.createElement('div'); late.id = 'late'; late.style.width = '200px'; document.body.append(late)")expression = "document.getElementById('late').getBoundingClientRect().width"- assert_equal(await probe.evaluate(expression), 0, "new node does not refresh snapshot")+ assert_equal(await probe.evaluate(expression), 0 if is_moli_browser() else 200, "new node geometry")await probe.call("Page.getLayoutMetrics")- assert_equal(await probe.evaluate(expression), 0, "metrics do not refresh a missing box")+ assert_equal(await probe.evaluate(expression), 0 if is_moli_browser() else 200, "new node geometry after metrics")await _capture(probe.client, probe.session)assert_equal(await probe.evaluate(expression), 200, "capture publishes the new node")- return {"missingBoxWidth": 0, "afterCaptureWidth": 200}+ return {"missingBoxWidth": 0 if is_moli_browser() else 200, "afterCaptureWidth": 200}def _replacement(kind: str) -> Callable[[Probe], Awaitable[dict[str, Any]]]:@@ -280,16 +312,12 @@ def _replacement(kind: str) -> Callable[[Probe], Awaitable[dict[str, Any]]]:await probe.set_width(160)assert_equal(await probe.width(), 160, "replacement Document gets a fresh initial layout")await probe.set_width(200)- assert_equal(await probe.width(), 160, "replacement Document also freezes after initialization")+ assert_equal(await probe.width(), 160 if is_moli_browser() else 200, "replacement Document geometry after mutation")return {"oldWidth": 80, "newDocumentWidth": 160}return runasync def run_layout_policy_group(endpoint: str, fixture: str, results: list[dict[str, Any]]) -> None:- if not (await discover_websocket_url(endpoint)).endswith("/devtools/browser/moli-browser"):- record(results, "layout_policy_not_applicable", {"reason": "Moli's frozen screen-layout contract"})- return-object_params = lambda p, phase: {"objectId": p.object_id}initializers: list[tuple[str, Operation]] = [("Page.getLayoutMetrics", _command("Page.getLayoutMetrics")),@@ -308,8 +336,8 @@ async def run_layout_policy_group(endpoint: str, fixture: str, results: list[dic("Input.dispatchMouseEvent/move", _input("Input.dispatchMouseEvent", {"type": "mouseMoved", "x": 40, "y": 30}, "mousemove")),("Input.dispatchMouseEvent/wheel", _input("Input.dispatchMouseEvent", {"type": "mouseWheel", "x": 40, "y": 30, "deltaX": 0, "deltaY": 10}, "wheel")),("Input.dispatchTouchEvent/start", _input("Input.dispatchTouchEvent", {"type": "touchStart", "touchPoints": [{"x": 40, "y": 30, "id": 1}]}, "touchstart")),- ("Input.dispatchDragEvent/enter", _input("Input.dispatchDragEvent", {"type": "dragEnter", "x": 40, "y": 30, "data": {"items": [], "dragOperationsMask": 1}}, "dragenter")),- ("Input.synthesizeTapGesture", _input("Input.synthesizeTapGesture", {"x": 40, "y": 30}, "click")),+ ("Input.dispatchDragEvent/enter", _input("Input.dispatchDragEvent", {"type": "dragEnter", "x": 40, "y": 30, "data": {"items": [{"mimeType": "text/plain", "data": "layout-probe"}], "dragOperationsMask": 1}}, "dragenter")),+ ("Input.synthesizeTapGesture", _input("Input.synthesizeTapGesture", {"x": 40, "y": 30, "gestureSourceType": "mouse"}, "click")),]non_publishers: list[tuple[str, Operation]] = [("Runtime.evaluate/plain", _script("[document.getElementById('probe').textContent, innerWidth, innerHeight, scrollX, scrollY]")),@@ -319,12 +347,12 @@ async def run_layout_policy_group(endpoint: str, fixture: str, results: list[dic("DOM/reads", _dom_reads),("CSS/computed-style-and-grid", _style_reads),("CSS/stylesheet-read-write", _style_sheet),- ("DOM.setAttributeValue", _command("DOM.setAttributeValue", lambda p, phase: {"nodeId": p.node_id, "name": "style", "value": "width:100px"})),+ ("DOM.setAttributeValue", _attribute_width),("Emulation/viewport-and-media", _viewport),("Page.captureSnapshot", _command("Page.captureSnapshot", lambda p, phase: {"format": "mhtml"})),("DOMSnapshot.captureSnapshot", _command("DOMSnapshot.captureSnapshot", lambda p, phase: {"computedStyles": ["display", "width"], "includeDOMRects": True})),("Runtime.focus/preventScroll", _script("document.getElementById('probe').focus({preventScroll:true})")),- ("Input.dispatchTouchEvent/idle-end", _command("Input.dispatchTouchEvent", lambda p, phase: {"type": "touchEnd", "touchPoints": []})),+ ("Input.dispatchTouchEvent/idle-end", _idle_touch_end),("Page.printToPDF", _pdf),]checks: list[tuple[str, Callable[[Probe], Awaitable[dict[str, Any]]]]] = [@@ -344,7 +372,7 @@ async def run_layout_policy_group(endpoint: str, fixture: str, results: list[dictry:async with _fresh_probe(client) as probe:observed = await run(probe)- record(results, "layout_policy/" + name, observed)+ record(results, "layout_policy/" + name, {"policy": "frozen" if is_moli_browser() else "live", **observed})except Exception as error:failures.append(f"{name}: {error}")results.append({"name": "layout_policy/" + name, "ok": False, "error": str(error)})diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/layout_screenshot.py b/moli-cdp-smoke/moli_cdp_smoke/groups/layout_screenshot.pyindex d56b1e1ec..6b6ce8a17 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/layout_screenshot.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/layout_screenshot.py@@ -9,7 +9,7 @@ from ..assertions import SmokeError, assert_equal, recordfrom ..jpeg_image import jpeg_dimensionsfrom ..png_image import decode_pngfrom ..raw_cdp import RawCdpClient, connect_raw_cdp, discover_websocket_url-from ..serve import start_moli_serve, stop_moli_serve, wait_for_moli_endpoint+from ..serve import start_moli_serve, stop_browser, wait_for_browser_endpointSCREENSHOT_UNSUPPORTED = (@@ -649,7 +649,7 @@ async def _run_default_mock_boundary(results: list[dict[str, Any]],) -> None:serve = await start_moli_serve(layout=False)- endpoint = await wait_for_moli_endpoint(serve)+ endpoint = await wait_for_browser_endpoint(serve)client: RawCdpClient | None = Nonetarget_id: str | None = Nonetry:@@ -715,4 +715,4 @@ async def _run_default_mock_boundary(except Exception:passawait client.websocket.close()- await stop_moli_serve(serve)+ await stop_browser(serve)diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/multi_context.py b/moli-cdp-smoke/moli_cdp_smoke/groups/multi_context.pyindex 436ae86b0..368980bb6 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/multi_context.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/multi_context.py@@ -9,7 +9,8 @@ from playwright.async_api import Error as PlaywrightErrorfrom playwright.async_api import TimeoutError as PlaywrightTimeoutErrorfrom ..assertions import SmokeError, assert_equal, record, wait_until-from ..helpers import attach_cdp_event_collector+from ..config import is_moli_browser+from ..helpers import read_io_to_eof, attach_cdp_event_collectorBODY_TAKEN_CONTINUE_RESPONSE_ERROR = "Unable to continue request as is after body is taken"@@ -772,19 +773,22 @@ async def run_multi_context_popup_response_stage_stream_owner_state_smoke("context B popup",)- first_a = await _send_cdp(cdp_a, "IO.read", {"handle": stream_a, "offset": 0, "size": 8})+ first_a = await _send_cdp(cdp_a, "IO.read", {"handle": stream_a, "size": 8})assert_equal(first_a.get("base64Encoded"), False, "context A popup stream first chunk encoding")assert_equal(first_a.get("data"), "response", "context A popup stream first chunk")assert_equal(first_a.get("eof"), False, "context A popup stream first chunk eof")- offset_b = await _send_cdp(cdp_b, "IO.read", {"handle": stream_b, "offset": 9, "size": 5})- assert_equal(offset_b.get("base64Encoded"), False, "context B popup stream offset encoding")- assert_equal(offset_b.get("data"), "stage", "context B popup stream offset chunk")- assert_equal(offset_b.get("eof"), False, "context B popup stream offset eof")- first_b = await _send_cdp(cdp_b, "IO.read", {"handle": stream_b, "offset": 0, "size": 8})+ first_b = await _send_cdp(cdp_b, "IO.read", {"handle": stream_b, "size": 8})assert_equal(first_b.get("base64Encoded"), False, "context B popup stream first chunk encoding")assert_equal(first_b.get("data"), "response", "context B popup stream first chunk")- tail_b = await _send_cdp(cdp_b, "IO.read", {"handle": stream_b})+ if is_moli_browser():+ offset_b = await _send_cdp(cdp_b, "IO.read", {"handle": stream_b, "offset": 9, "size": 5})+ assert_equal(offset_b.get("base64Encoded"), False, "context B popup stream offset encoding")+ assert_equal(offset_b.get("data"), "stage", "context B popup stream offset chunk")+ assert_equal(offset_b.get("eof"), False, "context B popup stream offset eof")+ reset = await _send_cdp(cdp_b, "IO.read", {"handle": stream_b, "offset": 0, "size": 8})+ assert_equal(reset, first_b, "Moli buffered stream supports seeking back to the first chunk")+ tail_b = await read_io_to_eof(cdp_b, stream_b)assert_equal(tail_b.get("base64Encoded"), False, "context B popup stream tail encoding")assert_equal(tail_b.get("data"), "-stage body", "context B popup stream tail")assert_equal(tail_b.get("eof"), True, "context B popup stream tail eof")@@ -792,11 +796,12 @@ async def run_multi_context_popup_response_stage_stream_owner_state_smoke(if fetch_a.done() or fetch_b.done():raise SmokeError("popup response-stage stream fetch completed before fulfillRequest")- await _expect_cdp_error(- _send_cdp(cdp_b, "Fetch.continueResponse", {"requestId": request_id_b}),- BODY_TAKEN_CONTINUE_RESPONSE_ERROR,- "context B popup stream continueResponse after body taken",- )+ if is_moli_browser():+ await _expect_cdp_error(+ _send_cdp(cdp_b, "Fetch.continueResponse", {"requestId": request_id_b}),+ BODY_TAKEN_CONTINUE_RESPONSE_ERROR,+ "context B popup stream continueResponse after body taken",+ )await _fulfill_response_stage_body(cdp_b, request_id_b)continued_b = Trueassert_equal(@@ -811,7 +816,7 @@ async def run_multi_context_popup_response_stage_stream_owner_state_smoke(await _send_cdp(cdp_b, "IO.close", {"handle": stream_b})await _expect_cdp_error(_send_cdp(cdp_b, "IO.read", {"handle": stream_b}),- "StreamHandleNotFound",+ "StreamHandleNotFound" if is_moli_browser() else "Invalid stream handle","context B popup stream read after close",)stream_b = None@@ -821,15 +826,16 @@ async def run_multi_context_popup_response_stage_stream_owner_state_smoke(if _has_loading_finished(events_a[start_a:], network_id_a):raise SmokeError("context A popup response-stage stream Network.loadingFinished fired before fulfillRequest")- tail_a = await _send_cdp(cdp_a, "IO.read", {"handle": stream_a})+ tail_a = await read_io_to_eof(cdp_a, stream_a)assert_equal(tail_a.get("base64Encoded"), False, "context A popup stream tail encoding")assert_equal(tail_a.get("data"), "-stage body", "context A popup stream tail")assert_equal(tail_a.get("eof"), True, "context A popup stream tail eof")- await _expect_cdp_error(- _send_cdp(cdp_a, "Fetch.continueResponse", {"requestId": request_id_a}),- BODY_TAKEN_CONTINUE_RESPONSE_ERROR,- "context A popup stream continueResponse after body taken",- )+ if is_moli_browser():+ await _expect_cdp_error(+ _send_cdp(cdp_a, "Fetch.continueResponse", {"requestId": request_id_a}),+ BODY_TAKEN_CONTINUE_RESPONSE_ERROR,+ "context A popup stream continueResponse after body taken",+ )await _fulfill_response_stage_body(cdp_a, request_id_a)continued_a = Trueassert_equal(@@ -945,50 +951,52 @@ async def run_multi_context_popup_response_stage_stream_wrong_session_smoke(raise SmokeError("popup response-stage streams should be target-owner scoped")await _expect_cdp_error(- _send_cdp(cdp_b, "IO.read", {"handle": stream_a, "offset": 0, "size": 4}),- "StreamHandleNotFound",+ _send_cdp(cdp_b, "IO.read", {"handle": stream_a, "size": 4}),+ "StreamHandleNotFound" if is_moli_browser() else "Invalid stream handle","context B should not read context A popup stream",)await _expect_cdp_error(_send_cdp(cdp_b, "IO.close", {"handle": stream_a}),- "StreamHandleNotFound",+ "StreamHandleNotFound" if is_moli_browser() else "Invalid stream handle","context B should not close context A popup stream",)await _expect_cdp_error(- _send_cdp(cdp_a, "IO.read", {"handle": stream_b, "offset": 0, "size": 4}),- "StreamHandleNotFound",+ _send_cdp(cdp_a, "IO.read", {"handle": stream_b, "size": 4}),+ "StreamHandleNotFound" if is_moli_browser() else "Invalid stream handle","context A should not read context B popup stream",)await _expect_cdp_error(_send_cdp(cdp_a, "IO.close", {"handle": stream_b}),- "StreamHandleNotFound",+ "StreamHandleNotFound" if is_moli_browser() else "Invalid stream handle","context A should not close context B popup stream",)- first_a = await _send_cdp(cdp_a, "IO.read", {"handle": stream_a, "offset": 0, "size": 8})+ first_a = await _send_cdp(cdp_a, "IO.read", {"handle": stream_a, "size": 8})assert_equal(first_a.get("data"), "response", "context A popup stream remains readable by owner")- tail_a = await _send_cdp(cdp_a, "IO.read", {"handle": stream_a})+ tail_a = await read_io_to_eof(cdp_a, stream_a)assert_equal(tail_a.get("data"), "-stage body", "context A popup stream owner tail")assert_equal(tail_a.get("eof"), True, "context A popup stream owner tail eof")- first_b = await _send_cdp(cdp_b, "IO.read", {"handle": stream_b, "offset": 0, "size": 8})+ first_b = await _send_cdp(cdp_b, "IO.read", {"handle": stream_b, "size": 8})assert_equal(first_b.get("data"), "response", "context B popup stream remains readable by owner")- tail_b = await _send_cdp(cdp_b, "IO.read", {"handle": stream_b})+ tail_b = await read_io_to_eof(cdp_b, stream_b)assert_equal(tail_b.get("data"), "-stage body", "context B popup stream owner tail")assert_equal(tail_b.get("eof"), True, "context B popup stream owner tail eof")- await _expect_cdp_error(- _send_cdp(cdp_a, "Fetch.continueResponse", {"requestId": request_id_a}),- BODY_TAKEN_CONTINUE_RESPONSE_ERROR,- "context A popup stream owner continueResponse after body taken",- )+ if is_moli_browser():+ await _expect_cdp_error(+ _send_cdp(cdp_a, "Fetch.continueResponse", {"requestId": request_id_a}),+ BODY_TAKEN_CONTINUE_RESPONSE_ERROR,+ "context A popup stream owner continueResponse after body taken",+ )await _fulfill_response_stage_body(cdp_a, request_id_a)continued_a = True- await _expect_cdp_error(- _send_cdp(cdp_b, "Fetch.continueResponse", {"requestId": request_id_b}),- BODY_TAKEN_CONTINUE_RESPONSE_ERROR,- "context B popup stream owner continueResponse after body taken",- )+ if is_moli_browser():+ await _expect_cdp_error(+ _send_cdp(cdp_b, "Fetch.continueResponse", {"requestId": request_id_b}),+ BODY_TAKEN_CONTINUE_RESPONSE_ERROR,+ "context B popup stream owner continueResponse after body taken",+ )await _fulfill_response_stage_body(cdp_b, request_id_b)continued_b = Trueassert_equal(@@ -1779,7 +1787,7 @@ def _websocket_received_payload_length(and any(event["method"] == "Network.webSocketFrameReceived"and event["params"].get("requestId") == request_id- and event["params"].get("response", {}).get("payloadLength") == payload_length+ and _websocket_payload_length(event["params"].get("response", {})) == payload_lengthfor event in events))@@ -1812,7 +1820,7 @@ def _assert_no_cross_websocket_payload(eventfor event in eventsif event.get("method") == "Network.webSocketFrameReceived"- and event["params"].get("response", {}).get("payloadLength")+ and _websocket_payload_length(event["params"].get("response", {}))== forbidden_payload_length),None,@@ -1821,6 +1829,18 @@ def _assert_no_cross_websocket_payload(raise SmokeError(f"{label} received another context's WebSocket frame event: {leaked}")+def _websocket_payload_length(response: dict[str, Any]) -> int:+ if is_moli_browser():+ length = response.get("payloadLength")+ if not isinstance(length, int):+ raise SmokeError(f"missing Moli payloadLength: {response}")+ return length+ payload = response.get("payloadData")+ if not isinstance(payload, str):+ raise SmokeError(f"missing Chromium payloadData: {response}")+ return len(payload.encode())++async def _expect_cdp_error(awaitable: Awaitable[Any], expected: str, label: str) -> None:try:await awaitablediff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page_contracts.py b/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page_contracts.pyindex fc5b6fed8..907c87f61 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page_contracts.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page_contracts.py@@ -5,6 +5,7 @@ from contextlib import suppressfrom typing import Anyfrom ..assertions import SmokeError, assert_equal, record_contract, wait_until+from ..config import is_moli_browserfrom ..helpers import attach_cdp_event_collectorfrom .multi_page_support import (MultiPageCase,@@ -2248,6 +2249,8 @@ async def _network_profiles_are_target_local_with_shared_native_environment("timezone": "Europe/Paris",},]+ if not is_moli_browser():+ expected_runtime_profiles[1].update(locale=baseline_runtime["locale"], timezone=baseline_runtime["timezone"])assert_equal(runtime_profiles,expected_runtime_profiles,@@ -2312,10 +2315,10 @@ async def _network_profiles_are_target_local_with_shared_native_environment("multi_page_network_and_emulation_profile_ownership",contract=("Headers and navigator identity are target-local. Date/Intl defaults "- "are process-wide; owner detach restores those defaults for every peer "- "without changing peer network/navigator policy."+ "are process-wide in Moli and renderer-local in Chromium; owner detach "+ "restores defaults without changing peer network/navigator policy."),- source="Chromium single-renderer ICU defaults and target-local Network policy",+ source="Measured Moli process-wide and Chromium renderer-local ICU ownership",commands=["Network.setExtraHTTPHeaders","Emulation.setUserAgentOverride",diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/network.py b/moli-cdp-smoke/moli_cdp_smoke/groups/network.pyindex 0277cb2f6..c3709b003 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/network.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/network.py@@ -7,7 +7,8 @@ from typing import Any, Awaitablefrom . import SmokeStatefrom ..assertions import SmokeError, assert_equal, wait_until-from ..helpers import attach_cdp_event_collector, evaluate_xhr+from ..config import is_moli_browser+from ..helpers import isolated_network_page, read_io_to_eof, attach_cdp_event_collector, evaluate_xhrBODY_TAKEN_CONTINUE_RESPONSE_ERROR = "Unable to continue request as is after body is taken"@@ -144,9 +145,9 @@ async def run_page_network_group(state: SmokeState) -> None:await _verify_response_stage_fetch_body_stream(state)await _verify_response_stage_fetch_binary_body(state)await _verify_response_stage_fetch_binary_body_stream(state)- await _verify_fetch_auth_challenge(state)- await _verify_fetch_auth_cancel(state)- await _verify_fetch_auth_response_stage(state)+ for scenario in [_verify_fetch_auth_challenge, _verify_fetch_auth_cancel, _verify_fetch_auth_response_stage]:+ async with isolated_network_page(state) as isolated:+ await scenario(isolated)await _verify_redirect_chain_network_events(state)await _verify_parser_script_network_events(state)await _verify_parser_stylesheet_network_events(state)@@ -927,32 +928,36 @@ async def _verify_response_stage_fetch_body_stream(state: SmokeState) -> None:stream_handle = stream.get("stream")if not isinstance(stream_handle, str) or not stream_handle:raise SmokeError(f"missing Fetch.takeResponseBodyAsStream handle: {stream}")- offset_chunk = await state.cdp.send(- "IO.read", {"handle": stream_handle, "offset": 9, "size": 5}- )- assert_equal(- offset_chunk.get("base64Encoded"),- False,- "Fetch response-stage stream offset chunk encoding",- )- assert_equal(offset_chunk.get("data"), "stage", "Fetch response-stage stream offset chunk")- assert_equal(offset_chunk.get("eof"), False, "Fetch response-stage stream offset chunk eof")first_chunk = await state.cdp.send(- "IO.read", {"handle": stream_handle, "offset": 0, "size": 8}+ "IO.read", {"handle": stream_handle, "size": 8})assert_equal(first_chunk.get("base64Encoded"), False, "Fetch response-stage stream first chunk encoding")assert_equal(first_chunk.get("data"), "response", "Fetch response-stage stream first chunk")assert_equal(first_chunk.get("eof"), False, "Fetch response-stage stream first chunk eof")- tail_chunk = await state.cdp.send("IO.read", {"handle": stream_handle})+ if is_moli_browser():+ offset_chunk = await state.cdp.send(+ "IO.read", {"handle": stream_handle, "offset": 9, "size": 5}+ )+ assert_equal(+ offset_chunk.get("base64Encoded"),+ False,+ "Fetch response-stage stream offset chunk encoding",+ )+ assert_equal(offset_chunk.get("data"), "stage", "Fetch response-stage stream offset chunk")+ assert_equal(offset_chunk.get("eof"), False, "Fetch response-stage stream offset chunk eof")+ reset = await state.cdp.send("IO.read", {"handle": stream_handle, "offset": 0, "size": 8})+ assert_equal(reset, first_chunk, "Moli buffered stream supports seeking back to the first chunk")+ tail_chunk = await read_io_to_eof(state.cdp, stream_handle)assert_equal(tail_chunk.get("base64Encoded"), False, "Fetch response-stage stream tail encoding")assert_equal(tail_chunk.get("data"), "-stage body", "Fetch response-stage stream tail chunk")assert_equal(tail_chunk.get("eof"), True, "Fetch response-stage stream tail eof")- await _expect_cdp_error(- state.cdp.send("Fetch.continueResponse", {"requestId": request_id}),- BODY_TAKEN_CONTINUE_RESPONSE_ERROR,- "Fetch response-stage stream continueResponse after body taken",- )+ if is_moli_browser():+ await _expect_cdp_error(+ state.cdp.send("Fetch.continueResponse", {"requestId": request_id}),+ BODY_TAKEN_CONTINUE_RESPONSE_ERROR,+ "Fetch response-stage stream continueResponse after body taken",+ )await state.cdp.send("Fetch.fulfillRequest",{@@ -979,7 +984,7 @@ async def _verify_response_stage_fetch_body_stream(state: SmokeState) -> None:await state.cdp.send("IO.close", {"handle": stream_handle})await _expect_cdp_error(state.cdp.send("IO.read", {"handle": stream_handle}),- "StreamHandleNotFound",+ "StreamHandleNotFound" if is_moli_browser() else "Invalid stream handle","Fetch response-stage stream read after close",)stream_handle = None@@ -1146,16 +1151,17 @@ async def _verify_response_stage_fetch_binary_body_stream(state: SmokeState) ->stream_handle = stream.get("stream")if not isinstance(stream_handle, str) or not stream_handle:raise SmokeError(f"missing binary Fetch.takeResponseBodyAsStream handle: {stream}")- chunk = await state.cdp.send("IO.read", {"handle": stream_handle})+ chunk = await read_io_to_eof(state.cdp, stream_handle)assert_equal(chunk.get("base64Encoded"), True, "Fetch binary response-stage stream encoding")assert_equal(chunk.get("data"), "AP9h", "Fetch binary response-stage stream base64 body")assert_equal(chunk.get("eof"), True, "Fetch binary response-stage stream eof")- await _expect_cdp_error(- state.cdp.send("Fetch.continueResponse", {"requestId": request_id}),- BODY_TAKEN_CONTINUE_RESPONSE_ERROR,- "Fetch binary response-stage stream continueResponse after body taken",- )+ if is_moli_browser():+ await _expect_cdp_error(+ state.cdp.send("Fetch.continueResponse", {"requestId": request_id}),+ BODY_TAKEN_CONTINUE_RESPONSE_ERROR,+ "Fetch binary response-stage stream continueResponse after body taken",+ )await state.cdp.send("Fetch.fulfillRequest",{@@ -1836,6 +1842,8 @@ async def _verify_chromium_resource_type_network_matrix(state: SmokeState) -> No"/chromium-resource-xhr.bin": (base64.b64encode(b"\x00\xffmoli-xhr").decode("ascii"), True),}for path, (expected_body, expected_base64) in expected_bodies.items():+ if path.endswith(".vtt") and not is_moli_browser():+ expected_body, expected_base64 = base64.b64encode(expected_body.encode()).decode(), Truebody = await state.cdp.send("Network.getResponseBody", {"requestId": request_ids[path]})assert_equal(body.get("base64Encoded"), expected_base64, f"{path} Network.getResponseBody encoding")assert_equal(body.get("body"), expected_body, f"{path} Network.getResponseBody body")@@ -1938,19 +1946,43 @@ async def _verify_blocked_websocket_events(state: SmokeState) -> None:page = state.pagefixture = state.fixturesubresource_events = state.subresource_events- blocked_ws_url = fixture.replace("http:", "ws:", 1) + "/ws-blocked"+ blocked_ws_url = fixture.replace("http:", "ws:", 1) + "/ws-echo"blocked_ws_start = len(subresource_events)+ socket_events = attach_cdp_event_collector(state.cdp, [+ "Network.webSocketCreated", "Network.webSocketHandshakeResponseReceived",+ "Network.webSocketFrameReceived", "Network.webSocketClosed",+ ])await state.cdp.send("Network.setBlockedURLs", {"urls": [blocked_ws_url + "*"]})blocked_ws_result = await page.evaluate("""async url => await new Promise(resolve => {- const socket = new WebSocket(url);+ const socket = new WebSocket(url, 'smoke');const timer = setTimeout(() => { socket.close(); resolve(`timeout:${socket.readyState}`); }, 5000);- socket.onopen = () => { clearTimeout(timer); resolve('open'); };+ socket.onopen = () => { socket.close(); clearTimeout(timer); resolve('open'); };socket.onerror = () => { clearTimeout(timer); resolve(`error:${socket.readyState}`); };socket.onclose = event => { clearTimeout(timer); resolve(`close:${event.code}:${event.wasClean}`); };})""",blocked_ws_url,)+ if not is_moli_browser():+ assert_equal(blocked_ws_result, "open", "Chromium setBlockedURLs does not block WebSocket handshakes")+ await wait_until(lambda: any(e["method"] == "Network.webSocketHandshakeResponseReceived"+ and e["params"].get("response", {}).get("status") == 101+ for e in socket_events), "Chromium WebSocket handshake event")+ created = next((e for e in socket_events if e["method"] == "Network.webSocketCreated"+ and e["params"].get("url") == blocked_ws_url), None)+ if created is None:+ raise SmokeError(f"missing Chromium WebSocket identity: {socket_events}")+ request_id = created["params"]["requestId"]+ assert_equal(any(e["method"] == "Network.webSocketHandshakeResponseReceived"+ and e["params"].get("requestId") == request_id+ and e["params"].get("response", {}).get("status") == 101+ for e in socket_events), True, "Chromium WebSocket handshake succeeded")+ assert_equal(any(e["params"].get("requestId") == request_id+ for e in subresource_events[blocked_ws_start:]), False,+ "WebSocket uses its own Network event family")+ await state.cdp.send("Network.setBlockedURLs", {"urls": []})+ state.record("blocked_websocket_network_events", {"policy": "chromium-websocket-exclusion"})+ returnif blocked_ws_result == "open" or str(blocked_ws_result).startswith("timeout:"):raise SmokeError(f"blocked WebSocket should fail, got {blocked_ws_result}")diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/process_environment.py b/moli-cdp-smoke/moli_cdp_smoke/groups/process_environment.pyindex 3ee48e039..397241e6d 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/process_environment.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/process_environment.py@@ -5,6 +5,7 @@ import contextlibfrom typing import Anyfrom ..assertions import SmokeError, assert_equal, record+from ..config import is_moli_browserREAD_DEFAULTS = """() => [@@ -56,7 +57,7 @@ async def _install_workers(page: Any) -> None:}""", READ_DEFAULTS)-async def _burst_environment_updates(control: Any, peer: Any) -> None:+async def _burst_environment_updates(control: Any, peer: Any, baseline: list[Any]) -> None:# Send a burst without interleaved observations. This is the latest-value# cache invalidation contract, not a requirement to replay every ICU value.updates = []@@ -69,7 +70,7 @@ async def _burst_environment_updates(control: Any, peer: Any) -> None:control.send("Emulation.setTimezoneOverride", {"timezoneId": timezone}),])await asyncio.wait_for(asyncio.gather(*updates), timeout=10)- expected = ["de-DE", "Asia/Shanghai", -480, -480]+ expected = ["de-DE", "Asia/Shanghai", -480, -480] if is_moli_browser() else baselineassert_equal(await peer.evaluate(READ_DEFAULTS), expected, "peer observes final burst defaults")assert_equal(await _worker_defaults(peer), [expected, expected], "workers observe final burst defaults")@@ -100,6 +101,12 @@ async def _override_while_peer_paused(control: Any, peer: Any, baseline: list[Anfor locale, timezone, expected in transitions:await control.send("Emulation.setLocaleOverride", {"locale": locale})await control.send("Emulation.setTimezoneOverride", {"timezoneId": timezone})+ if not is_moli_browser():+ owner = await control.send("Runtime.evaluate", {+ "expression": f"({READ_DEFAULTS})()", "returnByValue": True,+ })+ assert_equal(owner.get("result", {}).get("value"), expected, "owner observes its override")+ expected = baseline# No sleep, retry, resume, or unrelated command to drive delivery.result = await peer.send("Debugger.evaluateOnCallFrame", {"callFrameId": event["callFrames"][0]["callFrameId"],@@ -143,11 +150,13 @@ async def run_process_environment_group(assert_equal(await _worker_defaults(peer), [baseline, baseline], "worker baseline")record(results, "process_environment_workers_before_override")- await _burst_environment_updates(control, peer)+ await _burst_environment_updates(control, peer, baseline)record(results, "process_environment_burst_updates_reach_pages_and_workers")await _override_while_peer_paused(control, other, baseline)record(results, "process_environment_paused_change_replace_restore")- expected = ["fr-FR", "Europe/Paris", -60, -120]+ owner_expected = ["fr-FR", "Europe/Paris", -60, -120]+ expected = owner_expected if is_moli_browser() else baseline+ assert_equal(await owner.evaluate(READ_DEFAULTS), owner_expected, "owner override after paused peer")assert_equal(await peer.evaluate(READ_DEFAULTS), expected, "existing peer isolate")assert_equal(await _worker_defaults(peer), [expected, expected], "existing worker isolates")assert_equal(await peer.evaluate(@@ -161,20 +170,28 @@ async def run_process_environment_group(await _install_workers(late)assert_equal(await _worker_defaults(late), [expected, expected], "late workers inherit ICU")await owner.reload()- assert_equal(await owner.evaluate(READ_DEFAULTS), expected, "navigation keeps session claim")+ assert_equal(await owner.evaluate(READ_DEFAULTS), owner_expected, "navigation keeps session claim")record(results, "process_environment_new_isolate_and_navigation")- await _expect_error(other, "Emulation.setLocaleOverride", {"locale": "de_DE"})- await _expect_error(other, "Emulation.setLocaleOverride", {"locale": ""})- await _expect_error(other, "Emulation.setTimezoneOverride", {"timezoneId": "Asia/Shanghai"})- # Chromium accepts the installed timezone without granting a second lease.- await other.send("Emulation.setTimezoneOverride", {"timezoneId": "Europe/Paris"})- await other.send("Emulation.setTimezoneOverride", {"timezoneId": ""})+ if is_moli_browser():+ await _expect_error(other, "Emulation.setLocaleOverride", {"locale": "de_DE"})+ await _expect_error(other, "Emulation.setLocaleOverride", {"locale": ""})+ await _expect_error(other, "Emulation.setTimezoneOverride", {"timezoneId": "Asia/Shanghai"})+ await other.send("Emulation.setTimezoneOverride", {"timezoneId": "Europe/Paris"})+ await other.send("Emulation.setTimezoneOverride", {"timezoneId": ""})+ else:+ await other.send("Emulation.setLocaleOverride", {"locale": "de_DE"})+ await other.send("Emulation.setTimezoneOverride", {"timezoneId": "Asia/Shanghai"})+ assert_equal(await peer.evaluate(READ_DEFAULTS), ["de-DE", "Asia/Shanghai", -480, -480], "independent peer override")+ assert_equal(await owner.evaluate(READ_DEFAULTS), owner_expected, "peer override does not change owner")+ await other.send("Emulation.setLocaleOverride", {"locale": ""})+ await other.send("Emulation.setTimezoneOverride", {"timezoneId": ""})assert_equal(await peer.evaluate(READ_DEFAULTS), expected, "non-owner cannot clear")record(results, "process_environment_cross_target_exclusive_claims")await control.detach()sessions.remove(control)+ assert_equal(await owner.evaluate(READ_DEFAULTS), baseline, "detach restores owner defaults")assert_equal(await peer.evaluate(READ_DEFAULTS), baseline, "detach restores host defaults")assert_equal(await _worker_defaults(peer), [baseline, baseline], "worker restoration")assert_equal(await _worker_defaults(late), [baseline, baseline], "late worker restoration")@@ -186,7 +203,9 @@ async def run_process_environment_group(sessions.append(control)await control.send("Emulation.setLocaleOverride", {"locale": "de_DE"})await control.send("Emulation.setTimezoneOverride", {"timezoneId": "Asia/Shanghai"})- expected = ["de-DE", "Asia/Shanghai", -480, -480]+ owner_expected = ["de-DE", "Asia/Shanghai", -480, -480]+ expected = owner_expected if is_moli_browser() else baseline+ assert_equal(await owner.evaluate(READ_DEFAULTS), owner_expected, "new owner override")assert_equal(await peer.evaluate(READ_DEFAULTS), expected, "new owner after release")await owner.close()sessions.remove(control)@@ -199,6 +218,7 @@ async def run_process_environment_group(sessions.append(control)await control.send("Emulation.setLocaleOverride", {"locale": "de_DE"})await control.send("Emulation.setTimezoneOverride", {"timezoneId": "Asia/Shanghai"})+ assert_equal(await replacement.evaluate(READ_DEFAULTS), owner_expected, "replacement owner override")assert_equal(await peer.evaluate(READ_DEFAULTS), expected, "context owns live claims")await owner_context.close()sessions.remove(control)diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/protocol.py b/moli-cdp-smoke/moli_cdp_smoke/groups/protocol.pyindex 4d989dc0e..545c77eb6 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/protocol.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/protocol.py@@ -7,6 +7,7 @@ from dataclasses import dataclassfrom typing import Anyfrom ..assertions import SmokeError, assert_equal, record+from ..config import is_moli_browserfrom ..raw_cdp import RawCdpClient, connect_raw_cdp@@ -519,7 +520,7 @@ async def _javascript_dialog_protocol_shape()assert_equal(params.get("hasBrowserHandler"),- False,+ not is_moli_browser(),"raw Page.javascriptDialogOpening native browser handler",)if not isinstance(params.get("frameId"), str) or not params["frameId"]:diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/protocol_regressions.py b/moli-cdp-smoke/moli_cdp_smoke/groups/protocol_regressions.pyindex 8fc7e054a..031da0c8e 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/protocol_regressions.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/protocol_regressions.py@@ -4,6 +4,7 @@ import asynciofrom dataclasses import dataclassfrom typing import Any+from ..config import is_moli_browserfrom ..assertions import SmokeError, assert_equal, recordfrom ..raw_cdp import RawCdpClient, connect_raw_cdp@@ -284,7 +285,7 @@ async def _runtime_enable_stack_cost_probe(raise SmokeError(f"Runtime stack-cost probe returned invalid regression data: {probes}") from error- if ordered_r_squared[1] >= 0.5:+ if is_moli_browser() and ordered_r_squared[1] >= 0.5:raise SmokeError("Runtime.enable exposed a repeatable Error stack-depth timing slope: "f"{probes}"@@ -292,6 +293,7 @@ async def _runtime_enable_stack_cost_probe(return {"probes": probes,"medianRSquared": ordered_r_squared[1],+ "policy": "moli-stack-timing-privacy" if is_moli_browser() else "chromium-stack-timing-observation",}diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/scrollbar_visibility.py b/moli-cdp-smoke/moli_cdp_smoke/groups/scrollbar_visibility.pyindex 57c6ae5b6..a3fb10ea9 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/scrollbar_visibility.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/scrollbar_visibility.py@@ -7,12 +7,12 @@ import osfrom typing import Anyfrom urllib.parse import quote-from ..assertions import SmokeError, assert_equal, record-from ..config import clear_proxy_env, moli_binary+from ..assertions import SmokeError, assert_equal, record, wait_until+from ..config import clear_proxy_env, is_moli_browser, moli_binaryfrom ..png_image import decode_pngfrom ..process import run_captured_processfrom ..raw_cdp import RawCdpClient, connect_raw_cdp-from ..serve import start_moli_serve, stop_moli_serve, wait_for_moli_endpoint+from ..serve import start_browser, start_moli_serve, stop_browser, wait_for_browser_endpointfrom .layout_screenshot import _capture, _open_target, _response_for_id, _success, _wait_for_load@@ -134,16 +134,22 @@ async def _assert_input(client: RawCdpClient, session: str, visible: bool) -> No"buttons": buttons, "clickCount": 1,}, session_id=session)await _capture(client, session)+ async def click_settled() -> bool:+ return await _evaluate(client, session, "[document.getElementById('scroller').scrollTop, clicks]") == ([20, []] if visible else [60, ["content"]])+ await wait_until(click_settled, "native scrollbar click reaches its final scroll position")assert_equal(await _evaluate(client, session,"[document.getElementById('scroller').scrollTop, clicks]"),[20, []] if visible else [60, ["content"]],"native scrollbar hit or DOM content hit")await _evaluate(client, session, "document.getElementById('scroller').scrollTop = 0")await _capture(client, session)+ async def wheel_settled() -> bool:+ return await _evaluate(client, session, "document.getElementById('scroller').scrollTop") == 30await _success(client, "Input.dispatchMouseEvent", {"type": "mouseWheel", "x": 80, "y": 50, "deltaX": 0, "deltaY": 30,}, session_id=session)await _capture(client, session)+ await wait_until(wheel_settled, "wheel scrolling reaches its final position")assert_equal(await _evaluate(client, session,"document.getElementById('scroller').scrollTop"), 30, "hidden and visible wheel scrolling")@@ -151,6 +157,9 @@ async def _assert_input(client: RawCdpClient, session: str, visible: bool) -> Noasync def _assert_emulation(client: RawCdpClient, target: str, session: str, startup_visible: bool,) -> None:+ # The pinned Chromium build applies this setting on the next document;+ # Moli also updates the existing document at the command reply.+ emulated_visible = False if is_moli_browser() else startup_visibleawait _assert_snapshot(client, session, startup_visible)for params in [{}, {"hidden": "true"}]:message_id = await client.send("Emulation.setScrollbarsHidden", params, session_id=session)@@ -159,8 +168,8 @@ async def _assert_emulation(await _assert_metrics(client, session, startup_visible)await _success(client, "Emulation.setScrollbarsHidden", {"hidden": True}, session_id=session)# Geometry is current at the command reply, before another output demand.- await _assert_metrics(client, session, False)- await _assert_snapshot(client, session, False)+ await _assert_metrics(client, session, emulated_visible)+ await _assert_snapshot(client, session, emulated_visible)other, peer = await _open_target(client, URL)try:await _assert_snapshot(client, peer, startup_visible)@@ -168,9 +177,13 @@ async def _assert_emulation(await _success(client, "Target.closeTarget", {"targetId": other})_, _, seen = await _success(client, "Page.navigate", {"url": URL}, session_id=session)await _wait_for_load(client, session, seen)- assert_equal(await _evaluate(client, session, "firstClient"), 800, "hidden emulation before navigation scripts")+ assert_equal(await _evaluate(client, session, "firstClient"), 800, "scrollbar emulation before navigation scripts")await _assert_snapshot(client, session, False)await _success(client, "Emulation.setScrollbarsHidden", {"hidden": False}, session_id=session)+ if not is_moli_browser():+ await _assert_metrics(client, session, False)+ _, _, seen = await _success(client, "Page.navigate", {"url": URL}, session_id=session)+ await _wait_for_load(client, session, seen)await _assert_metrics(client, session, startup_visible)await _assert_snapshot(client, session, startup_visible)await _success(client, "Emulation.setScrollbarsHidden", {"hidden": True}, session_id=session)@@ -195,7 +208,7 @@ async def _serve_case(serve = await start_moli_serve(extra_args=args, env_overrides={"MOLI_SCROLLBARS": env_value})client: RawCdpClient | None = Nonetry:- endpoint = await wait_for_moli_endpoint(serve)+ endpoint = await wait_for_browser_endpoint(serve)client = await connect_raw_cdp(endpoint)target, session = await _open_target(client, URL)metrics = await _assert_snapshot(client, session, visible)@@ -213,7 +226,7 @@ async def _serve_case(if client is not None:await client.websocket.close()finally:- await stop_moli_serve(serve)+ await stop_browser(serve)async def _fetch_case(@@ -250,7 +263,7 @@ async def _layout_boundaries(results: list[dict[str, Any]]) -> None:)client: RawCdpClient | None = Nonetry:- client = await connect_raw_cdp(await wait_for_moli_endpoint(serve))+ client = await connect_raw_cdp(await wait_for_browser_endpoint(serve))target, session = await _open_target(client, REPRO_URL)message_id = await client.send("Emulation.setScrollbarsHidden", {"hidden": True}, session_id=session)response, _ = await _response_for_id(client, message_id)@@ -263,7 +276,7 @@ async def _layout_boundaries(results: list[dict[str, Any]]) -> None:if client is not None:await client.websocket.close()finally:- await stop_moli_serve(serve)+ await stop_browser(serve)env = clear_proxy_env(os.environ)env.pop("MOLI_LAYOUT", None)@@ -284,6 +297,25 @@ async def _layout_boundaries(results: list[dict[str, Any]]) -> None:async def run_scrollbar_visibility_group(endpoint: str, fixture: str, results: list[dict[str, Any]],) -> None:+ if not is_moli_browser():+ for name, args, visible in [("default", (), True), ("hide-scrollbars", ("--hide-scrollbars",), False)]:+ serve = await start_browser(extra_args=args)+ client = None+ try:+ client = await connect_raw_cdp(await wait_for_browser_endpoint(serve))+ target, session = await _open_target(client, URL)+ metrics = await _assert_snapshot(client, session, visible)+ record(results, "scrollbar_chromium_startup_" + name, {"visible": visible, "metrics": metrics})+ await _assert_input(client, session, visible)+ _, _, seen = await _success(client, "Page.navigate", {"url": URL}, session_id=session)+ await _wait_for_load(client, session, seen)+ await _assert_emulation(client, target, session, visible)+ record(results, "scrollbar_chromium_input_and_emulation_" + name)+ finally:+ if client is not None:+ await client.websocket.close()+ await stop_browser(serve)+ return# Every startup case owns its process/environment; the caller's endpoint# cannot exercise CLI defaults or environment precedence.for name, args, env_value, visible in CASES:diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/target_lifecycle.py b/moli-cdp-smoke/moli_cdp_smoke/groups/target_lifecycle.pyindex bfd039a6c..92d14752b 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/target_lifecycle.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/target_lifecycle.py@@ -7,10 +7,10 @@ from typing import Anyfrom ..assertions import SmokeError, assert_equal, recordfrom ..raw_cdp import RawCdpClient, connect_raw_cdp-from ..serve import MoliServe+from ..serve import BrowserProcess-def process_resources(pid: int) -> dict[str, int] | None:+def process_resources(pid: int, profile_dir: str | None = None) -> dict[str, int] | None:if not sys.platform.startswith("linux"):return None# Inspect only the managed server, not this client or other smoke workers.@@ -24,6 +24,8 @@ def process_resources(pid: int) -> dict[str, int] | None:continuereturn {"fds": len(descriptors),+ "profileFileFds": sum(value.startswith(profile_dir.rstrip("/") + "/")+ for value in descriptors.values()) if profile_dir else 0,"eventpoll": sum(value == "anon_inode:[eventpoll]" for value in descriptors.values()),"eventfd": sum(value == "anon_inode:[eventfd]" for value in descriptors.values()),"threads": len(list(Path(f"/proc/{pid}/task").iterdir())),@@ -35,7 +37,14 @@ def assert_resources_bounded(baseline: dict[str, int], current: dict[str, int])# Permit a fixed amount of in-flight teardown/transport bookkeeping, never# a per-iteration allowance. The old +2 FD/page leak fails at the first batch.for key, allowance in (("fds", 8), ("eventpoll", 2), ("eventfd", 2), ("threads", 2)):- if current[key] > baseline[key] + allowance:+ initial, observed = baseline[key], current[key]+ if key == "fds":+ # Chrome initializes profile database services after startup. These+ # regular files are recorded separately from target/transport FDs.+ # Moli supplies no profile path, so its all-FD budget is unchanged.+ initial -= baseline.get("profileFileFds", 0)+ observed -= current.get("profileFileFds", 0)+ if observed > initial + allowance:raise SmokeError(f"target teardown leaked {key}: baseline={baseline}, current={current}")@@ -114,9 +123,10 @@ class LifecycleProbe:async def run_target_lifecycle_group(- endpoint: str, fixture: str, results: list[dict[str, Any]], serve: MoliServe | None,+ endpoint: str, fixture: str, results: list[dict[str, Any]], serve: BrowserProcess | None,) -> None:pid = serve.process.pid if serve is not None else None+ profile_dir = serve.data_dir if serve is not None and serve.engine == "chromium" else Noneclient = await connect_raw_cdp(endpoint)probe = LifecycleProbe(client)try:@@ -135,9 +145,10 @@ async def run_target_lifecycle_group(for index in range(4):await probe.cycle(mode, index)await probe.navigate(f"{fixture}/plain?lifecycle-warmup")- baseline = process_resources(pid) if pid is not None else None+ baseline = process_resources(pid, profile_dir) if pid is not None else Nonerecord(results, "target_lifecycle_baseline", {"pid": pid, "resources": baseline,+ "fdBudget": "non-profile-fds" if profile_dir else "all-fds","fdSampling": ("external-endpoint-without-owned-pid" if pid is None else"linux-proc" if baseline is not None else "unavailable-on-this-platform"),})@@ -145,7 +156,7 @@ async def run_target_lifecycle_group(for index in range(count):await probe.cycle(mode, index)if (index + 1) % 100 == 0 or index + 1 == count:- current = process_resources(pid) if pid is not None else None+ current = process_resources(pid, profile_dir) if pid is not None else None# Persist the observation before asserting, so a failed# run retains the resource slope and exact failing batch.record(results, "target_lifecycle_sample", {diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/url_policy.py b/moli-cdp-smoke/moli_cdp_smoke/groups/url_policy.pyindex 884d8d46f..82ec0da05 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/url_policy.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/url_policy.py@@ -4,6 +4,7 @@ import asynciofrom typing import Anyfrom ..assertions import SmokeError, assert_equal, record+from ..config import is_moli_browserfrom ..raw_cdp import RawCdpClient, connect_raw_cdp@@ -43,15 +44,18 @@ async def run_url_policy_group(session_id=session_id,)navigate, navigation_messages = await _recv_until_response(client, navigate_id)- assert_equal(- navigate,- {- "id": navigate_id,- "sessionId": session_id,- "error": {"code": -32000, "message": NAVIGATION_POLICY_MESSAGE},- },- "CDP rejected file navigation response shape",- )+ if is_moli_browser():+ assert_equal(+ navigate,+ {"id": navigate_id, "sessionId": session_id,+ "error": {"code": -32000, "message": NAVIGATION_POLICY_MESSAGE}},+ "CDP rejected file navigation response shape",+ )+ else:+ assert_equal(navigate.get("result", {}).get("errorText"), "net::ERR_FILE_NOT_FOUND", "Chromium missing file navigation")+ assert_equal(any(m.get("method") == "Fetch.requestPaused" for m in navigation_messages), True, "Chromium intercepts file navigation")+ reset = await client.send("Page.navigate", {"url": "about:blank"}, session_id=session_id)+ await _recv_until_response(client, reset)location, location_messages = await _evaluate(client,@@ -59,15 +63,16 @@ async def run_url_policy_group("location.href",)assert_equal(location, "about:blank", "CDP rejected file navigation current URL")- _assert_no_navigation_or_transport_events(- navigation_messages + location_messages,- "CDP rejected file navigation",- )+ if is_moli_browser():+ _assert_no_navigation_or_transport_events(+ navigation_messages + location_messages,+ "CDP rejected file navigation",+ )record(results,"cdp_file_navigation_policy",{- "errorCode": -32000,+ "policy": "moli-hosted-file-capability" if is_moli_browser() else "chromium-local-file-navigation","sessionId": session_id,"urlAfterFailure": location,},@@ -97,7 +102,7 @@ async def run_url_policy_group({"resolved": False,"name": "TypeError",- "message": 'URL scheme "file" is not supported.',+ "message": 'URL scheme "file" is not supported.' if is_moli_browser() else "Failed to fetch",},"CDP Runtime.evaluate fetch(file:) rejection",)@@ -370,6 +375,8 @@ async def _recv_until_response(raise SmokeError(f"timed out waiting for CDP response id={message_id}: {seen[-20:]!r}")message = await asyncio.wait_for(client.recv(), timeout=remaining)seen.append(message)+ if not is_moli_browser() and message.get("method") == "Fetch.requestPaused":+ await client.send("Fetch.continueRequest", {"requestId": message["params"]["requestId"]}, session_id=message["sessionId"])if message.get("id") == message_id:return message, seen@@ -390,7 +397,7 @@ async def _evaluate(},session_id=session_id,)- response, messages = await client.recv_until_id(command_id)+ response, messages = await _recv_until_response(client, command_id)result = response.get("result", {}).get("result", {})if "exceptionDetails" in response.get("result", {}):raise SmokeError(f"Runtime.evaluate raised unexpectedly: {response!r}")@@ -416,11 +423,17 @@ def _assert_early_network_failure(request_url: str = FILE_URL,error_text: str = 'URL scheme "file" is not supported.',) -> list[str]:+ if not is_moli_browser():+ error_text = "net::ERR_UNSAFE_PORT" if request_url == BAD_PORT_URL else ""forbidden_methods = {- "Fetch.requestPaused","Network.responseReceived","Network.loadingFinished",}+ if is_moli_browser():+ forbidden_methods.add("Fetch.requestPaused")+ elif request_url == BAD_PORT_URL:+ assert_equal(any(m.get("method") == "Fetch.requestPaused" for m in messages), True,+ "Chromium intercepts synchronous bad-port XHR before rejecting it")unexpected = [message for message in messages if message.get("method") in forbidden_methods]diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/workers.py b/moli-cdp-smoke/moli_cdp_smoke/groups/workers.pyindex b0ff8f33e..23dac23ad 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/workers.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/workers.py@@ -3,10 +3,64 @@ from __future__ import annotationsimport asyncioimport jsonfrom typing import Any+from contextlib import asynccontextmanagerfrom . import SmokeStatefrom ..assertions import SmokeError, assert_equal, wait_until-from ..helpers import attach_cdp_event_collector, run_worker_command+from ..helpers import attach_cdp_event_collector, isolated_network_page, run_worker_command+from ..config import is_moli_browser+++@asynccontextmanager+async def _worker_network_events(state: SmokeState):+ if is_moli_browser():+ yield+ return+ # Chromium emits Worker Network events on the Worker session, while Moli+ # mirrors them on the owning Page. Enable Network before the Worker starts.+ pending: dict[tuple[str, int], asyncio.Future[Any]] = {}+ tasks: list[asyncio.Task[Any]] = []++ def received(event: dict[str, Any]) -> None:+ message = json.loads(event["message"])+ key = (event["sessionId"], message.get("id"))+ if key in pending and not pending[key].done():+ pending[key].set_result(message)+ if message.get("method", "").startswith("Network."):+ state.subresource_events.append(message)++ async def enable(event: dict[str, Any]) -> None:+ session = event["sessionId"]+ for identifier, method in enumerate(["Network.enable", "Runtime.runIfWaitingForDebugger"], 1):+ result = asyncio.get_running_loop().create_future()+ pending[session, identifier] = result+ await state.cdp.send("Target.sendMessageToTarget", {+ "sessionId": session, "message": json.dumps({"id": identifier, "method": method}),+ })+ response = await asyncio.wait_for(result, timeout=5)+ if "error" in response:+ raise SmokeError(f"worker {method} failed: {response}")++ def attached(event: dict[str, Any]) -> None:+ if event["targetInfo"]["type"] == "worker":+ tasks.append(asyncio.create_task(enable(event)))++ state.cdp.on("Target.attachedToTarget", attached)+ state.cdp.on("Target.receivedMessageFromTarget", received)+ try:+ await state.cdp.send("Target.setAutoAttach", {+ "autoAttach": True, "waitForDebuggerOnStart": True, "flatten": False,+ "filter": [{"type": "worker", "exclude": False}, {"exclude": True}],+ })+ yield+ finally:+ await state.cdp.send("Target.setAutoAttach", {+ "autoAttach": False, "waitForDebuggerOnStart": False, "flatten": False,+ })+ state.cdp.remove_listener("Target.attachedToTarget", attached)+ state.cdp.remove_listener("Target.receivedMessageFromTarget", received)+ if tasks:+ await asyncio.gather(*tasks)async def run_workers_group(state: SmokeState) -> None:@@ -59,12 +113,14 @@ async def run_workers_group(state: SmokeState) -> None:await context.unroute("**/worker-route-continue")await context.unroute("**/worker-route-abort")- await _verify_worker_fetch_auth_challenge(state)- await _verify_worker_fetch_auth_cancel(state)- await _verify_worker_fetch_auth_response_stage(state)- await _verify_worker_xhr_auth_challenge(state)- await _verify_worker_xhr_auth_cancel(state)- await _verify_worker_xhr_auth_response_stage(state)+ for scenario in [+ _verify_worker_fetch_auth_challenge, _verify_worker_fetch_auth_cancel,+ _verify_worker_fetch_auth_response_stage, _verify_worker_xhr_auth_challenge,+ _verify_worker_xhr_auth_cancel, _verify_worker_xhr_auth_response_stage,+ ]:+ async with isolated_network_page(state) as isolated:+ async with _worker_network_events(isolated):+ await scenario(isolated)async def _verify_shared_worker_postmessage_reuse(state: SmokeState) -> None:diff --git a/moli-cdp-smoke/moli_cdp_smoke/helpers.py b/moli-cdp-smoke/moli_cdp_smoke/helpers.pyindex 0c99abbe9..b3568efc2 100644--- a/moli-cdp-smoke/moli_cdp_smoke/helpers.py+++ b/moli-cdp-smoke/moli_cdp_smoke/helpers.py@@ -1,7 +1,53 @@from __future__ import annotations+import asyncioimport base64-from typing import Any+from contextlib import asynccontextmanager+from dataclasses import replace+from typing import Any, AsyncIterator++from .assertions import SmokeError+from .state import SmokeState+++@asynccontextmanager+async def isolated_network_page(state: SmokeState) -> AsyncIterator[SmokeState]:+ # Auth caches belong to a browser context. Different challenge realms on+ # the same path do not prevent Chromium from sending cached credentials.+ context = await state.browser.new_context()+ try:+ page = await context.new_page()+ cdp = await context.new_cdp_session(page)+ events = attach_cdp_event_collector(cdp, [+ "Network.requestWillBeSent", "Network.responseReceived", "Network.dataReceived",+ "Network.loadingFinished", "Network.loadingFailed",+ ])+ await cdp.send("Network.enable")+ await page.goto(state.fixture + "/plain", wait_until="load", timeout=10_000)+ yield replace(state, context=context, page=page, cdp=cdp, subresource_events=events)+ finally:+ await context.close()+++async def read_io_to_eof(client: Any, handle: str) -> dict[str, Any]:+ """Read through the explicit EOF marker, which can follow the last data chunk."""+ data: list[bytes] = []+ encoding: bool | None = None+ async with asyncio.timeout(5):+ while True:+ chunk = await client.send("IO.read", {"handle": handle})+ if not isinstance(chunk.get("data"), str) or not isinstance(chunk.get("eof"), bool):+ raise SmokeError(f"invalid IO.read response: {chunk}")+ current = chunk.get("base64Encoded", False)+ if encoding is None and chunk["data"]:+ encoding = current+ if chunk["data"] and current != encoding:+ raise SmokeError(f"IO.read changed encoding within a stream: {chunk}")+ data.append(base64.b64decode(chunk["data"], validate=True) if current else chunk["data"].encode())+ if chunk["eof"]:+ body = b"".join(data)+ return {"data": base64.b64encode(body).decode() if encoding else body.decode(),+ "base64Encoded": bool(encoding), "eof": True}async def capture_layout(page: Any) -> bytes:diff --git a/moli-cdp-smoke/moli_cdp_smoke/runner.py b/moli-cdp-smoke/moli_cdp_smoke/runner.pyindex d02673f55..9c7bf272d 100644--- a/moli-cdp-smoke/moli_cdp_smoke/runner.py+++ b/moli-cdp-smoke/moli_cdp_smoke/runner.py@@ -78,11 +78,14 @@ from .groups.xhr_sync_semantics import run_xhr_sync_semantics_groupfrom .helpers import attach_cdp_event_collectorfrom .progress import await_with_progressfrom .serve import (- MoliServe,- start_moli_serve,- stop_moli_serve,+ BROWSER_ENV,+ BROWSER_LAUNCHES,+ BrowserProcess,+ browser_identity,+ start_browser,+ stop_browser,wait_for_cdp_server,- wait_for_moli_endpoint,+ wait_for_browser_endpoint,)from .state import SmokeState@@ -94,7 +97,7 @@ RawGroupRunner = Callable[[str, str, list[dict[str, Any]]], Awaitable[None]]ExternalGroupRunner = Callable[[str, str, list[dict[str, Any]]], Awaitable[None]]PageGroupRunner = Callable[[SmokeState], Awaitable[None]]BrowserGroupRunner = Callable[[Any, str, list[dict[str, Any]]], Awaitable[None]]-ProcessGroupRunner = Callable[[str, str, list[dict[str, Any]], MoliServe | None], Awaitable[None]]+ProcessGroupRunner = Callable[[str, str, list[dict[str, Any]], BrowserProcess | None], Awaitable[None]]@dataclass(frozen=True)@@ -664,6 +667,8 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:"--endpoint",help="Use an existing HTTP CDP endpoint instead of starting moli serve.",)+ parser.add_argument("--browser", choices=("moli", "chromium"))+ parser.add_argument("--chromium-bin", help="Override the locked Playwright Chromium executable.")parser.add_argument("--result",type=Path,@@ -704,10 +709,15 @@ async def async_main(argv: list[str] | None = None) -> int:selected_group = selection.groups[0]fixture = FixtureServer()fixture_started = False- serve: MoliServe | None = None+ serve: BrowserProcess | None = Noneresults: list[dict[str, Any]] = []endpoint: str | None = Nonefailures: list[str] = []+ identity: dict[str, Any] | None = None+ BROWSER_LAUNCHES.clear()+ os.environ[BROWSER_ENV] = args.browser or "moli"+ if args.chromium_bin:+ os.environ["CHROMIUM_BIN"] = args.chromium_bintry:fixture.start()fixture_started = True@@ -718,17 +728,19 @@ async def async_main(argv: list[str] | None = None) -> int:port = int(port_env) if port_env else 0if port < 0 or port > 65535 or (port == 0 and port_env is not None):raise RuntimeError(f"invalid MOLI_CDP_PORT: {port_env}")- serve = await start_moli_serve(+ serve = await start_browser(port,extra_args=("--scrollbars",)- if selected_group.name in {"classic-scrollbar", "iframe-input"}+ if args.browser != "chromium" and selected_group.name in {"classic-scrollbar", "iframe-input"}else (),)- endpoint = await wait_for_moli_endpoint(serve)+ endpoint = await wait_for_browser_endpoint(serve)if endpoint is None:raise RuntimeError("CDP endpoint was not initialized")if serve is None:await wait_for_cdp_server(endpoint, serve)+ identity = await browser_identity(endpoint, args.browser or ("moli" if serve else None))+ os.environ[BROWSER_ENV] = identity["engine"]for current_group in selection.process_groups:await _await_group(current_group,@@ -749,7 +761,7 @@ async def async_main(argv: list[str] | None = None) -> int:failures.append("".join(traceback.format_exception(error)))finally:try:- await stop_moli_serve(serve)+ await stop_browser(serve)except Exception as error:failures.append("".join(traceback.format_exception(error)))if fixture_started:@@ -764,6 +776,8 @@ async def async_main(argv: list[str] | None = None) -> int:"group": selected_group.name,"endpoint": endpoint,"fixture": fixture.url,+ "browser": identity,+ "browserLaunches": BROWSER_LAUNCHES,"results": results,}if failures:diff --git a/moli-cdp-smoke/moli_cdp_smoke/serve.py b/moli-cdp-smoke/moli_cdp_smoke/serve.pyindex 1691b1992..1d9877e4b 100644--- a/moli-cdp-smoke/moli_cdp_smoke/serve.py+++ b/moli-cdp-smoke/moli_cdp_smoke/serve.py@@ -1,6 +1,7 @@from __future__ import annotationsimport asyncio+import jsonimport osimport reimport shutil@@ -10,8 +11,11 @@ import timeimport urllib.errorimport urllib.requestfrom dataclasses import dataclass+from pathlib import Pathfrom typing import Any+from playwright.async_api import async_playwright+from .config import (REPO_ROOT,TRACE_BACKGROUND_PROCESS_ENV,@@ -22,12 +26,17 @@ from .process import subprocess_starts_new_session, terminate_process_tree@dataclass-class MoliServe:+class BrowserProcess:process: asyncio.subprocess.Processlogs: list[str]tasks: list[asyncio.Task[Any]]- http_cache_dir: str+ data_dir: strendpoint_ready: asyncio.Future[str]+ engine: str = "moli"+++BROWSER_ENV = "MOLI_SMOKE_BROWSER"+BROWSER_LAUNCHES: list[dict[str, Any]] = []_ANSI_ESCAPE = re.compile(r"\x1b\[[0-9;]*m")@@ -36,7 +45,11 @@ _LISTENING_ADDRESS = re.compile()-def _moli_endpoint_from_log_line(line: str) -> str | None:+def _endpoint_from_log_line(line: str) -> str | None:+ chrome = re.search(r"DevTools listening on ws://127\.0\.0\.1:([0-9]+)/", line)+ if chrome is not None:+ port = int(chrome.group(1))+ return f"http://127.0.0.1:{port}" if 0 < port <= 65535 else Nonematch = _LISTENING_ADDRESS.search(_ANSI_ESCAPE.sub("", line))if match is None:return None@@ -58,6 +71,7 @@ async def _collect_process_output(logs: list[str],label: str,endpoint_ready: asyncio.Future[str],+ engine: str = "moli",) -> None:if stream is None:return@@ -67,11 +81,11 @@ async def _collect_process_output(returntext = line.decode("utf-8", errors="replace").rstrip()logs.append(f"{label}: {text}")- endpoint = _moli_endpoint_from_log_line(text)+ endpoint = _endpoint_from_log_line(text)if endpoint is not None and not endpoint_ready.done():endpoint_ready.set_result(endpoint)if os.environ.get(TRACE_BACKGROUND_PROCESS_ENV) == "1":- print(f"[moli serve {label}] {text}", file=sys.stderr, flush=True)+ print(f"[{engine} {label}] {text}", file=sys.stderr, flush=True)async def start_moli_serve(@@ -80,9 +94,11 @@ async def start_moli_serve(layout: bool = True,extra_args: tuple[str, ...] = (),env_overrides: dict[str, str | None] | None = None,-) -> MoliServe:+) -> BrowserProcess:+ if os.environ.get(BROWSER_ENV) == "chromium":+ raise RuntimeError("a Chromium smoke worker must not launch Moli")binary = moli_binary()- http_cache_dir = tempfile.mkdtemp(prefix="moli-cdp-smoke-cache-")+ data_dir = tempfile.mkdtemp(prefix="moli-cdp-smoke-cache-")command = [str(binary),"serve",@@ -96,7 +112,7 @@ async def start_moli_serve(]if layout:command.append("--layout")- command.extend(("--http-cache-dir", http_cache_dir, *extra_args))+ command.extend(("--http-cache-dir", data_dir, *extra_args))env = clear_proxy_env(os.environ)for key, value in (env_overrides or {}).items():if value is None:@@ -113,7 +129,7 @@ async def start_moli_serve(start_new_session=subprocess_starts_new_session(),)except Exception:- shutil.rmtree(http_cache_dir, ignore_errors=True)+ shutil.rmtree(data_dir, ignore_errors=True)raiselogs: list[str] = []endpoint_ready = asyncio.get_running_loop().create_future()@@ -125,16 +141,64 @@ async def start_moli_serve(_collect_process_output(process.stderr, logs, "stderr", endpoint_ready)),]- return MoliServe(+ BROWSER_LAUNCHES.append({"engine": "moli", "command": command, "pid": process.pid})+ return BrowserProcess(process=process,logs=logs,tasks=tasks,- http_cache_dir=http_cache_dir,+ data_dir=data_dir,endpoint_ready=endpoint_ready,)-async def stop_moli_serve(serve: MoliServe | None) -> None:+async def start_browser(port: int = 0, *, extra_args: tuple[str, ...] = ()) -> BrowserProcess:+ if os.environ.get(BROWSER_ENV, "moli") == "moli":+ return await start_moli_serve(port, extra_args=extra_args)+ async with async_playwright() as playwright:+ binary = Path(+ os.environ.get("CHROMIUM_BIN") or playwright.chromium.executable_path+ ).expanduser().resolve()+ if not binary.is_file():+ raise RuntimeError("missing Chromium; run `playwright install chromium` or set CHROMIUM_BIN")+ profile = tempfile.mkdtemp(prefix="moli-cdp-smoke-chromium-")+ command = [+ str(binary), "--headless=new", "--no-sandbox", "--disable-dev-shm-usage",+ "--disable-back-forward-cache",+ "--no-first-run", "--no-default-browser-check", "--remote-allow-origins=*",+ "--remote-debugging-address=127.0.0.1", f"--remote-debugging-port={port}",+ f"--user-data-dir={profile}", *extra_args, "about:blank",+ ]+ try:+ process = await asyncio.create_subprocess_exec(+ *command, cwd=str(REPO_ROOT), env=clear_proxy_env(os.environ),+ stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,+ start_new_session=subprocess_starts_new_session(),+ )+ except BaseException:+ shutil.rmtree(profile, ignore_errors=True)+ raise+ logs: list[str] = []+ endpoint_ready = asyncio.get_running_loop().create_future()+ tasks = [asyncio.create_task(_collect_process_output(stream, logs, label, endpoint_ready, "chromium"))+ for stream, label in [(process.stdout, "stdout"), (process.stderr, "stderr")]]+ BROWSER_LAUNCHES.append({"engine": "chromium", "command": command, "pid": process.pid})+ return BrowserProcess(process, logs, tasks, profile, endpoint_ready, "chromium")+++async def browser_identity(endpoint: str, expected: str | None) -> dict[str, Any]:+ def read_version() -> dict[str, Any]:+ with urllib.request.urlopen(endpoint.rstrip("/") + "/json/version", timeout=2) as response:+ return json.load(response)+ version = await asyncio.to_thread(read_version)+ engine = "moli" if version.get("webSocketDebuggerUrl", "").endswith("/moli-browser") else "chromium"+ if engine == "chromium" and not str(version.get("Browser", "")).startswith(("Chrome/", "HeadlessChrome/", "Chromium/")):+ raise RuntimeError(f"endpoint is not a Chromium browser: {version}")+ if expected is not None and engine != expected:+ raise RuntimeError(f"requested {expected}, but endpoint belongs to {engine}: {version}")+ return {"engine": engine, "version": version}+++async def stop_browser(serve: BrowserProcess | None) -> None:if serve is None:returnstopped = await terminate_process_tree(serve.process)@@ -145,9 +209,9 @@ async def stop_moli_serve(serve: MoliServe | None) -> None:_consume_task_result(task)for task in pending:task.add_done_callback(_consume_task_result)- shutil.rmtree(serve.http_cache_dir, ignore_errors=True)+ shutil.rmtree(serve.data_dir, ignore_errors=True)if not stopped:- raise RuntimeError(f"moli serve process {serve.process.pid} did not exit after SIGKILL")+ raise RuntimeError(f"{serve.engine} process {serve.process.pid} did not exit after SIGKILL")def _probe_url(url: str) -> bool:@@ -161,14 +225,14 @@ def _probe_url(url: str) -> bool:async def wait_for_cdp_server(endpoint: str,- serve: MoliServe | None,+ serve: BrowserProcess | None,) -> None:version_url = endpoint.rstrip("/") + "/json/version"deadline = time.monotonic() + 10while time.monotonic() < deadline:if serve is not None and serve.process.returncode is not None:tail = "\n".join(serve.logs[-80:])- raise RuntimeError(f"moli serve exited early with {serve.process.returncode}\n{tail}")+ raise RuntimeError(f"{serve.engine} exited early with {serve.process.returncode}\n{tail}")if await asyncio.to_thread(_probe_url, version_url):returnawait asyncio.sleep(0.05)@@ -177,8 +241,8 @@ async def wait_for_cdp_server(raise RuntimeError(f"timed out waiting for CDP server at {endpoint}{tail}")-async def wait_for_moli_endpoint(- serve: MoliServe,+async def wait_for_browser_endpoint(+ serve: BrowserProcess,*,timeout_seconds: float = 10,) -> str:@@ -192,16 +256,20 @@ async def wait_for_moli_endpoint(if serve.endpoint_ready in done:endpoint = serve.endpoint_ready.result()await wait_for_cdp_server(endpoint, serve)+ identity = await browser_identity(endpoint, serve.engine)+ for launch in BROWSER_LAUNCHES:+ if launch["pid"] == serve.process.pid:+ launch["browser"] = identityreturn endpointif process_exit in done:tail = "\n".join(serve.logs[-80:])raise RuntimeError(- f"moli serve exited early with {process_exit.result()}\n{tail}"+ f"{serve.engine} exited early with {process_exit.result()}\n{tail}")tail_text = "\n".join(serve.logs[-80:])tail = f"\n{tail_text}" if tail_text else ""raise RuntimeError(- "timed out waiting for moli to report its bound endpoint" + tail+ f"timed out waiting for {serve.engine} to report its bound endpoint" + tail)finally:if not process_exit.done():diff --git a/moli-cdp-smoke/moli_cdp_smoke/supervisor.py b/moli-cdp-smoke/moli_cdp_smoke/supervisor.pyindex ea26131f6..c3e276146 100644--- a/moli-cdp-smoke/moli_cdp_smoke/supervisor.py+++ b/moli-cdp-smoke/moli_cdp_smoke/supervisor.py@@ -26,6 +26,8 @@ class WorkerJob:attempt: intrepeat: intendpoint: str | None = None+ browser: str | None = None+ chromium_bin: str | None = None@propertydef label(self) -> str:@@ -51,6 +53,7 @@ class WorkerOutcome:scenario_count: intendpoint: str | None = Noneerror: str | None = None+ browser: dict[str, Any] | None = None@propertydef passed(self) -> bool:@@ -71,6 +74,8 @@ class WorkerOutcome:payload["error"] = self.errorif self.endpoint:payload["endpoint"] = self.endpoint+ if self.browser:+ payload["browser"] = self.browserreturn payload@@ -141,6 +146,8 @@ def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:action="store_true",help="List available groups as JSON and exit.",)+ parser.add_argument("--browser", choices=("moli", "chromium"), help="Managed browser engine (default: moli).")+ parser.add_argument("--chromium-bin", help="Override the locked Playwright Chromium executable.")return parser.parse_args(argv)@@ -161,6 +168,10 @@ def _worker_argv(job: WorkerJob, result_path: Path) -> list[str]:]if job.endpoint:argv.extend(("--endpoint", job.endpoint))+ if job.browser:+ argv.extend(("--browser", job.browser))+ if job.chromium_bin:+ argv.extend(("--chromium-bin", job.chromium_bin))return argv@@ -168,7 +179,7 @@ def _worker_environment() -> dict[str, str]:env = clear_proxy_env(os.environ)env[INHERIT_PROCESS_GROUP_ENV] = "1"# The supervisor already persists worker stdout/stderr in the artifact- # directory. Stream each worker's Moli child logs into that same file so a+ # directory. Stream each worker's browser logs into that same file so a# process-level timeout does not destroy the only copy of the renderer# diagnostics held in the worker's memory.env[TRACE_BACKGROUND_PROCESS_ENV] = "1"@@ -188,6 +199,32 @@ def _read_worker_payload(result_path: Path) -> tuple[dict[str, Any] | None, strreturn payload, None+def _coverage_error(job: WorkerJob, payload: dict[str, Any]) -> str | None:+ results = payload.get("results")+ if not isinstance(results, list) or not results:+ return "worker executed no scenarios"+ for result in results:+ if (+ not isinstance(result, dict)+ or result.get("ok") is not True+ or result.get("applicable") is False+ or "not_applicable" in str(result.get("name", ""))+ ):+ return f"worker did not validate scenario: {result}"+ if job.browser:+ identity = payload.get("browser") or {}+ if identity.get("engine") != job.browser:+ return f"worker browser mismatch: requested {job.browser}, got {identity}"+ launches = payload.get("browserLaunches") or []+ if not job.endpoint and not launches:+ return "managed worker published no browser process evidence"+ if any(launch.get("engine") != job.browser for launch in launches):+ return f"worker mixed browser engines: {launches}"+ if any((launch.get("browser") or {}).get("engine") != job.browser for launch in launches):+ return "worker did not verify every launched browser's discovery identity"+ return None++async def _wait_for_worker(process: asyncio.subprocess.Process,timeout_seconds: float,@@ -265,8 +302,8 @@ async def _run_worker_job(status = "crashed"error = f"worker reported the wrong group: {payload.get('group')!r}"elif exit_code == 0 and payload.get("ok") is True:- status = "passed"- error = None+ error = _coverage_error(job, payload)+ status = "failed" if error else "passed"else:status = "failed"worker_error = payload.get("error")@@ -282,6 +319,7 @@ async def _run_worker_job(scenario_count=scenario_count,endpoint=endpoint,error=error,+ browser=payload.get("browser") if payload else None,)print(f"[moli-cdp-supervisor] {status.upper()} {job.label} "@@ -317,6 +355,8 @@ async def run_supervisor(args: argparse.Namespace) -> tuple[int, dict[str, Any]]attempt=attempt,repeat=args.repeat,endpoint=args.endpoint.rstrip("/") if args.endpoint else None,+ browser=args.browser or ("moli" if args.endpoint is None else None),+ chromium_bin=args.chromium_bin,)for group in selection.groupsfor attempt in range(1, args.repeat + 1)@@ -373,6 +413,7 @@ async def run_supervisor(args: argparse.Namespace) -> tuple[int, dict[str, Any]]"timeoutSeconds": args.timeout,"repeat": args.repeat,"externalEndpoint": args.endpoint,+ "browser": args.browser or ("external" if args.endpoint else "moli"),"outputDirectory": str(output_dir),"groups": [outcome.summary() for outcome in outcomes],}diff --git a/moli-cdp-smoke/tests/test_browser_coverage.py b/moli-cdp-smoke/tests/test_browser_coverage.pynew file mode 100644index 000000000..bd542f5d9--- /dev/null+++ b/moli-cdp-smoke/tests/test_browser_coverage.py@@ -0,0 +1,117 @@+from __future__ import annotations++import io+import json+import os+import tempfile+import unittest+from copy import deepcopy+from pathlib import Path+from unittest.mock import AsyncMock, patch++from moli_cdp_smoke.assertions import SmokeError+from moli_cdp_smoke.config import moli_binary+from moli_cdp_smoke.helpers import read_io_to_eof+from moli_cdp_smoke.runner import GROUPS_BY_NAME, resolve_group_selection+from moli_cdp_smoke.serve import _endpoint_from_log_line, browser_identity, start_moli_serve+from moli_cdp_smoke.supervisor import WorkerJob, WorkerOutcome, _coverage_error, _worker_argv, parse_args, run_supervisor+++class BrowserCoverageTests(unittest.IsolatedAsyncioTestCase):+ async def test_both_engines_schedule_every_default_group(self) -> None:+ schedules = {}+ with tempfile.TemporaryDirectory() as directory, patch.dict(os.environ, {"MOLI_SMOKE_GROUPS": ""}):+ for engine in ("moli", "chromium"):+ seen = []++ async def worker(job, output, timeout):+ self.assertEqual(job.browser, engine)+ seen.append(job.group.name)+ return WorkerOutcome(job, "passed", 0, 0, output / "log", output / "result", 1)++ args = parse_args(["--browser", engine, "--output-dir", directory])+ with patch("moli_cdp_smoke.supervisor._run_worker_job", worker):+ code, _ = await run_supervisor(args)+ self.assertEqual(code, 0)+ schedules[engine] = seen+ self.assertEqual(schedules["chromium"], [g.name for g in resolve_group_selection().groups])+ self.assertEqual(schedules["chromium"], schedules["moli"])++ async def test_chromium_worker_cannot_launch_moli_or_invoke_its_cli(self) -> None:+ with patch.dict(os.environ, {"MOLI_SMOKE_BROWSER": "chromium"}):+ with self.assertRaisesRegex(RuntimeError, "must not invoke"):+ moli_binary()+ with self.assertRaisesRegex(RuntimeError, "must not launch"):+ await start_moli_serve()++ async def test_endpoint_identity_rejects_wrong_engine_and_non_chromium(self) -> None:+ for version, expected, message in [+ ({"Browser": "Chrome/145", "webSocketDebuggerUrl": "ws://localhost/devtools/browser/moli-browser"}, "chromium", "belongs to moli"),+ ({"Browser": "Firefox/145", "webSocketDebuggerUrl": "ws://localhost/devtools/browser/123"}, "chromium", "not a Chromium"),+ ]:+ with self.subTest(version=version), patch("urllib.request.urlopen", return_value=io.BytesIO(json.dumps(version).encode())):+ with self.assertRaisesRegex(RuntimeError, message):+ await browser_identity("http://localhost", expected)++ def test_no_assertions_no_skip_and_no_mixed_engine_can_pass(self) -> None:+ job = WorkerJob(GROUPS_BY_NAME["network"], 1, 1, browser="chromium")+ valid = {+ "results": [{"name": "body", "ok": True}],+ "browser": {"engine": "chromium"},+ "browserLaunches": [{"engine": "chromium", "browser": {"engine": "chromium"}}],+ }+ self.assertIsNone(_coverage_error(job, valid))+ invalid = [+ {"results": []},+ {"results": [{"name": "body", "ok": False}]},+ {"results": [{"name": "body_not_applicable", "ok": True}]},+ {"results": [{"name": "body", "ok": True, "applicable": False}]},+ {"browser": {"engine": "moli"}},+ {"browserLaunches": []},+ {"browserLaunches": [{"engine": "chromium"}]},+ {"browserLaunches": [{"engine": "chromium"}, {"engine": "moli"}]},+ ]+ for changes in invalid:+ with self.subTest(changes=changes):+ payload = deepcopy(valid)+ payload.update(changes)+ self.assertIsNotNone(_coverage_error(job, payload))++ def test_engine_and_binary_are_forwarded_without_shell_interpolation(self) -> None:+ binary = "/tmp/browser with spaces/chrome"+ job = WorkerJob(GROUPS_BY_NAME["network"], 1, 1, browser="chromium", chromium_bin=binary)+ argv = _worker_argv(job, Path("/tmp/result.json"))+ self.assertEqual(argv[argv.index("--browser") + 1], "chromium")+ self.assertEqual(argv[argv.index("--chromium-bin") + 1], binary)++ def test_chromium_endpoint_requires_a_valid_bound_loopback_port(self) -> None:+ self.assertEqual(_endpoint_from_log_line("DevTools listening on ws://127.0.0.1:43210/devtools/browser/123"), "http://127.0.0.1:43210")+ for port in (0, 65536):+ self.assertIsNone(_endpoint_from_log_line(f"DevTools listening on ws://127.0.0.1:{port}/devtools/browser/123"))++ async def test_sequential_stream_consumes_the_explicit_eof_marker(self) -> None:+ client = AsyncMock()+ client.send.side_effect = [+ {"data": "response", "base64Encoded": False, "eof": False},+ {"data": "-stage body", "base64Encoded": False, "eof": False},+ {"data": "", "eof": True},+ ]+ self.assertEqual(await read_io_to_eof(client, "1"), {"data": "response-stage body", "base64Encoded": False, "eof": True})+ self.assertEqual(client.send.await_count, 3)+ for call in client.send.await_args_list:+ self.assertEqual(call.args, ("IO.read", {"handle": "1"}))++ async def test_binary_stream_decodes_chunks_before_concatenating(self) -> None:+ client = AsyncMock()+ client.send.side_effect = [+ {"data": "AP8=", "base64Encoded": True, "eof": False},+ {"data": "YQ==", "base64Encoded": True, "eof": False},+ {"data": "", "eof": True},+ ]+ self.assertEqual(await read_io_to_eof(client, "1"), {"data": "AP9h", "base64Encoded": True, "eof": True})++ async def test_malformed_stream_response_fails(self) -> None:+ client = AsyncMock()+ client.send.return_value = {"data": "body"}+ with self.assertRaises(SmokeError):+ await read_io_to_eof(client, "1")diff --git a/moli-cdp-smoke/tests/test_serve.py b/moli-cdp-smoke/tests/test_serve.pyindex 2fcee549f..4a61ca6a2 100644--- a/moli-cdp-smoke/tests/test_serve.py+++ b/moli-cdp-smoke/tests/test_serve.py@@ -5,10 +5,10 @@ import unittestfrom typing import castfrom moli_cdp_smoke.serve import (- MoliServe,+ BrowserProcess,_collect_process_output,- _moli_endpoint_from_log_line,- wait_for_moli_endpoint,+ _endpoint_from_log_line,+ wait_for_browser_endpoint,)@@ -34,14 +34,14 @@ class ServeLogTests(unittest.IsolatedAsyncioTestCase):)self.assertEqual(- _moli_endpoint_from_log_line(plain), "http://127.0.0.1:41827"+ _endpoint_from_log_line(plain), "http://127.0.0.1:41827")self.assertEqual(- _moli_endpoint_from_log_line(ansi), "http://127.0.0.1:53109"+ _endpoint_from_log_line(ansi), "http://127.0.0.1:53109")- self.assertIsNone(_moli_endpoint_from_log_line("unrelated addr=127.0.0.1:9"))+ self.assertIsNone(_endpoint_from_log_line("unrelated addr=127.0.0.1:9"))self.assertIsNone(- _moli_endpoint_from_log_line(+ _endpoint_from_log_line("protocol server listening addr=127.0.0.1:99999"))@@ -66,31 +66,31 @@ class ServeLogTests(unittest.IsolatedAsyncioTestCase):endpoint_ready: asyncio.Future[str] = (asyncio.get_running_loop().create_future())- serve = MoliServe(+ serve = BrowserProcess(process=cast(asyncio.subprocess.Process, _FakeProcess(7)),logs=["stderr: startup failed"],tasks=[],- http_cache_dir="",+ data_dir="",endpoint_ready=endpoint_ready,)with self.assertRaisesRegex(RuntimeError, "exited early with 7"):- await wait_for_moli_endpoint(serve, timeout_seconds=1)+ await wait_for_browser_endpoint(serve, timeout_seconds=1)async def test_wait_for_listening_log_has_a_bounded_timeout(self) -> None:endpoint_ready: asyncio.Future[str] = (asyncio.get_running_loop().create_future())- serve = MoliServe(+ serve = BrowserProcess(process=cast(asyncio.subprocess.Process, _FakeProcess()),logs=[],tasks=[],- http_cache_dir="",+ data_dir="",endpoint_ready=endpoint_ready,)with self.assertRaisesRegex(RuntimeError, "bound endpoint"):- await wait_for_moli_endpoint(serve, timeout_seconds=0.01)+ await wait_for_browser_endpoint(serve, timeout_seconds=0.01)if __name__ == "__main__":diff --git a/moli-cdp-smoke/tests/test_target_lifecycle.py b/moli-cdp-smoke/tests/test_target_lifecycle.pyindex 46155f99f..7314f3194 100644--- a/moli-cdp-smoke/tests/test_target_lifecycle.py+++ b/moli-cdp-smoke/tests/test_target_lifecycle.py@@ -1,6 +1,10 @@from __future__ import annotationsimport unittest+import os+import tempfile+import sys+from pathlib import Pathfrom unittest.mock import patchfrom moli_cdp_smoke.assertions import SmokeError@@ -10,6 +14,23 @@ from moli_cdp_smoke.groups.target_lifecycle import (class TargetLifecycleTests(unittest.TestCase):+ def test_profile_startup_files_do_not_mask_transport_resource_leaks(self) -> None:+ baseline = {"fds": 100, "profileFileFds": 40, "eventpoll": 5, "eventfd": 8, "threads": 40}+ current = dict(baseline, fds=141, profileFileFds=80)+ assert_resources_bounded(baseline, current)+ for change in ({"fds": 149}, {"eventpoll": 8}, {"eventfd": 11}, {"threads": 43}):+ with self.subTest(change=change), self.assertRaises(SmokeError):+ assert_resources_bounded(baseline, dict(current, **change))++ @unittest.skipUnless(sys.platform.startswith("linux"), "requires Linux /proc")+ def test_profile_file_fds_are_counted_separately_and_total_is_retained(self) -> None:+ with tempfile.TemporaryDirectory() as profile:+ with (Path(profile) / "database").open("w"):+ resources = process_resources(os.getpid(), profile)+ self.assertEqual(resources["profileFileFds"], 1)+ self.assertGreater(resources["fds"], resources["profileFileFds"])+ self.assertEqual(process_resources(os.getpid())["profileFileFds"], 0)+def test_resource_budget_is_fixed_not_proportional_to_iterations(self) -> None:baseline = {"fds": 24, "eventpoll": 7, "eventfd": 4, "threads": 20}assert_resources_bounded(baseline, baseline)