Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

test(cdp): cover action window lifecycle

ldm09d5729a1f00d
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index dd04a2bb4..5bae5a61a 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -113,6 +113,12 @@ jobs:
uv sync --project moli-webdriver-smoke --locked
npm ci --prefix moli-cdp-smoke
+ - name: Test CDP smoke diagnostics
+ run: >-
+ uv run --project moli-cdp-smoke --no-sync
+ python -m unittest discover
+ --start-directory moli-cdp-smoke/tests
+
- name: Build moli
id: build_moli
run: cargo build --release -p moli
diff --git a/moli-cdp-smoke/README.md b/moli-cdp-smoke/README.md
index ce7b9d849..e66c6f17e 100644
--- a/moli-cdp-smoke/README.md
+++ b/moli-cdp-smoke/README.md
@@ -94,6 +94,16 @@ Covered well:
asynchronous request cancellation, and suppression of asynchronous events and
timers while a synchronous request owns the main thread.
- The focused `layout-screenshot` group drives a real raw WebSocket session through target creation/attachment, fixed viewport, lifecycle-gated navigation, DevTools-style PNG capture (`quality: 100`), paint/layout mutations, page clips, `captureBeyondViewport`, and the Chromium DevTools node-screenshot chain (`DOM.getBoxModel` + `Page.getLayoutMetrics` + page clip). It also covers Moli's uncached 1 FPS JPEG screencast: initial-frame delivery, 400x300 scaling, metadata/session routing, ACK backpressure, minimum cadence, mutation freshness, stop cleanup, and a separately restarted default-Mock boundary without `--layout`. The screenshot surface sequence can also run against Chromium as a coarse reference; the fixed-1-FPS and default-Mock branches are Moli-only.
+- The default raw `action-window` group holds Moli's on-demand input policy at
+ the public CDP boundary. Three acknowledged `Input.dispatchMouseEvent`
+ wheel commands remain delayed until one fixed one-second deadline, preserve
+ event order, defer their microtask checkpoint, and publish one derived
+ IntersectionObserver transition. `Page.captureScreenshot` must flush pending
+ wheel work before paint and retire that window so later input receives a
+ fresh deadline. A wheel handler that calls `document.open()` must also stop
+ the remainder of its batch from entering the replacement Document. These are
+ Moli scheduling contracts rather than Chromium-compatibility claims; the
+ group records a non-applicable result when pointed at Chromium.
- The focused `dom-hit-test` group drives `DOM.getNodeForLocation` through the real layout hit index and requires the same option-aware topmost node, backend node id, and frame id shape from Moli and Chromium.
- Node creation stack capture retains at most the newest 1,024 traces per Inspector session; focused renderer tests cover FIFO eviction, shared payloads, document replacement, and session detach while the wire smoke retains enable/disable/session semantics and verifies that `document.open()` preserves capture for replacement-document nodes.
- Optional chrome-remote-interface 0.34.0 and cdp-use 1.4.5 coverage for verified browser/page sessions, multiple targets, local/session storage ownership, history traversal, child-frame isolated worlds, Fetch fulfillment with page-session event routing, complete Network terminals, and the declared position-click boundary.
@@ -223,6 +233,8 @@ Runner layout:
- `groups/error_document.py`: failed main-document transport error Document identity, lifecycle, realm replacement, recovery, and multi-target isolation.
- `groups/dom_parser_mutations.py`: cross-engine raw-CDP parser-tail mutation publication and commit/DCL DOM binding barriers.
- `groups/layout_screenshot.py`: raw current-viewport PNG, DevTools parameter compatibility, paint/layout mutation freshness, uncached 1 FPS JPEG screencast/ACK behavior, and Moli default-Mock restart boundary.
+- `groups/action_window.py`: raw wheel admission/deadline batching, screenshot
+ flush/reset, derived-effect coalescing, and exact-Document retirement.
- `groups/pdf.py`: raw `Page.printToPDF` base64 and `ReturnAsStream` transport, `IO.read`, pagination, page ranges, orientation, PDF structure, and Chromium-shaped validation errors.
- `groups/dom_snapshot.py`: raw CDP `document.open()` replacement identity and
`DOMSnapshot.captureSnapshot` freshness workflows, intended to run unchanged
@@ -280,6 +292,7 @@ Run a focused subset while developing a CDP area:
uv run moli-cdp-smoke --group protocol --group network
uv run moli-cdp-smoke --group multi-client
uv run moli-cdp-smoke --group layout-screenshot
+uv run moli-cdp-smoke --group action-window
uv run moli-cdp-smoke --group pdf
uv run moli-cdp-smoke --group agent-episode
uv run moli-cdp-smoke --group fetch-runtime-teardown
diff --git a/moli-cdp-smoke/moli_cdp_smoke/fixture.py b/moli-cdp-smoke/moli_cdp_smoke/fixture.py
index b4c87d8bf..a9ba6a632 100644
--- a/moli-cdp-smoke/moli_cdp_smoke/fixture.py
+++ b/moli-cdp-smoke/moli_cdp_smoke/fixture.py
@@ -176,6 +176,69 @@ LAYOUT_SCREENSHOT_FIXTURE = (
/ "layout-screenshot-poc.html"
).read_text(encoding="utf-8")
+ACTION_WINDOW_DEADLINE_FIXTURE = """<!doctype html>
+<style>
+html, body { margin: 0; }
+body { height: 1200px; }
+#target { position: absolute; top: 250px; width: 20px; height: 20px; }
+</style>
+<div id="target"></div>
+<script>
+globalThis.__actionWindowWheelLog = [];
+globalThis.__actionWindowIoLog = [];
+addEventListener("wheel", event => {
+ __actionWindowWheelLog.push("event:" + event.deltaY);
+ Promise.resolve().then(() => {
+ __actionWindowWheelLog.push("microtask:" + event.deltaY);
+ });
+}, { capture: true });
+globalThis.__actionWindowObserver = new IntersectionObserver(entries => {
+ const entry = entries.find(candidate => candidate.target.id === "target");
+ if (!entry) return;
+ __actionWindowIoLog.push(entry.isIntersecting);
+ if (__actionWindowIoLog.length === 2 && entry.isIntersecting) {
+ fetch("/action-window-witness/entered?source=deadline");
+ }
+});
+__actionWindowObserver.observe(document.getElementById("target"));
+</script>
+"""
+
+ACTION_WINDOW_CAPTURE_FIXTURE = """<!doctype html>
+<style>
+html, body { margin: 0; background: white; }
+body { height: 1200px; }
+#witness { position: fixed; inset: 0; background: white; }
+</style>
+<div id="witness"></div>
+<script>
+globalThis.__actionWindowCaptureDeltas = [];
+addEventListener("wheel", event => {
+ __actionWindowCaptureDeltas.push(event.deltaY);
+ document.getElementById("witness").style.background =
+ __actionWindowCaptureDeltas.length === 1 ? "rgb(255, 0, 0)" : "rgb(0, 255, 0)";
+ fetch("/action-window-witness/entered?source=capture&delta=" + event.deltaY);
+}, { capture: true });
+</script>
+"""
+
+ACTION_WINDOW_REPLACEMENT_FIXTURE = """<!doctype html>
+<style>html, body { margin: 0; } body { height: 1200px; }</style>
+<script>
+globalThis.__actionWindowRetiredDeltas = [];
+globalThis.__actionWindowReplacementDeltas = [];
+document.addEventListener("wheel", event => {
+ __actionWindowRetiredDeltas.push(event.deltaY);
+ document.open();
+ document.write("<!doctype html><body style='height:1200px'>replacement</body>");
+ document.close();
+ document.addEventListener("wheel", replacementEvent => {
+ __actionWindowReplacementDeltas.push(replacementEvent.deltaY);
+ }, { capture: true });
+}, { capture: true, once: true });
+</script>
+"""
+
LDM0_TOP_DOM_WHITESPACE_FIXTURE = """<!doctype html>
<html>
<head>
@@ -491,6 +554,23 @@ class FixtureServer:
count = outer._increment_request_count(route)
self._send_text(f"entered-{count}")
return
+ if route == "/action-window-witness/reset":
+ outer.reset_request_count("/action-window-witness/entered")
+ self._send_json({"count": 0})
+ return
+ if route == "/action-window-witness/status":
+ self._send_json(
+ {
+ "count": outer.request_count(
+ "/action-window-witness/entered"
+ )
+ }
+ )
+ return
+ if route == "/action-window-witness/entered":
+ count = outer._increment_request_count(route)
+ self._send_json({"count": count})
+ return
if route == "/chromium-network-redirect-before-reset":
outer._increment_request_count(route)
self.send_response(HTTPStatus.FOUND)
@@ -548,6 +628,12 @@ class FixtureServer:
self._send_html("<!doctype html><main>plain ok</main>")
elif route == "/layout-screenshot-poc":
self._send_html(LAYOUT_SCREENSHOT_FIXTURE)
+ elif route == "/action-window-deadline":
+ self._send_html(ACTION_WINDOW_DEADLINE_FIXTURE)
+ elif route == "/action-window-capture":
+ self._send_html(ACTION_WINDOW_CAPTURE_FIXTURE)
+ elif route == "/action-window-replacement":
+ self._send_html(ACTION_WINDOW_REPLACEMENT_FIXTURE)
elif route == "/agent-episode-smoke":
self._send_html(
"<!doctype html><style>input,button{display:block;width:220px;height:32px}</style>"
diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/action_window.py b/moli-cdp-smoke/moli_cdp_smoke/groups/action_window.py
new file mode 100644
index 000000000..6d36592b1
--- /dev/null
+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/action_window.py
@@ -0,0 +1,465 @@
+from __future__ import annotations
+
+import asyncio
+import base64
+import json
+import urllib.request
+from typing import Any
+
+from ..assertions import SmokeError, assert_equal, record, record_contract
+from ..png_image import DecodedPng, decode_png
+from ..raw_cdp import RawCdpClient, connect_raw_cdp, discover_websocket_url
+
+
+async def _response_for_id(
+ client: RawCdpClient,
+ message_id: int,
+ *,
+ timeout: float = 10.0,
+) -> tuple[dict[str, Any], list[dict[str, Any]]]:
+ seen: list[dict[str, Any]] = []
+ deadline = asyncio.get_running_loop().time() + timeout
+ while True:
+ remaining = deadline - asyncio.get_running_loop().time()
+ if remaining <= 0:
+ raise SmokeError(
+ f"timed out waiting for action-window response id={message_id}: {seen[-20:]}"
+ )
+ message = await asyncio.wait_for(client.recv(), timeout=remaining)
+ seen.append(message)
+ if message.get("id") == message_id:
+ return message, seen
+
+
+async def _success(
+ client: RawCdpClient,
+ method: str,
+ params: dict[str, Any] | None = None,
+ *,
+ session_id: str | None = None,
+) -> tuple[dict[str, Any], list[dict[str, Any]]]:
+ message_id = await client.send(method, params, session_id=session_id)
+ response, seen = await _response_for_id(client, message_id)
+ if session_id is not None:
+ assert_equal(response.get("sessionId"), session_id, f"{method} response session")
+ if "error" in response:
+ raise SmokeError(f"{method} failed: {response['error']!r}")
+ result = response.get("result")
+ if not isinstance(result, dict):
+ raise SmokeError(f"{method} returned no result object: {response!r}")
+ return result, seen
+
+
+async def _wait_for_load(
+ client: RawCdpClient,
+ session_id: str,
+ seen: list[dict[str, Any]],
+) -> None:
+ if any(
+ message.get("sessionId") == session_id
+ and message.get("method") == "Page.loadEventFired"
+ for message in seen
+ ):
+ return
+ deadline = asyncio.get_running_loop().time() + 10.0
+ while True:
+ remaining = deadline - asyncio.get_running_loop().time()
+ if remaining <= 0:
+ raise SmokeError("timed out waiting for action-window Page.loadEventFired")
+ message = await asyncio.wait_for(client.recv(), timeout=remaining)
+ if (
+ message.get("sessionId") == session_id
+ and message.get("method") == "Page.loadEventFired"
+ ):
+ return
+
+
+async def _open_target(
+ client: RawCdpClient,
+) -> tuple[str, str]:
+ context, _ = await _success(client, "Target.createBrowserContext")
+ context_id = context.get("browserContextId")
+ if not isinstance(context_id, str) or not context_id:
+ raise SmokeError(f"Target.createBrowserContext returned no id: {context!r}")
+ created, _ = await _success(
+ client,
+ "Target.createTarget",
+ {"browserContextId": context_id, "url": "about:blank"},
+ )
+ target_id = created.get("targetId")
+ if not isinstance(target_id, str) or not target_id:
+ raise SmokeError(f"Target.createTarget returned no targetId: {created!r}")
+ attached, _ = await _success(
+ client,
+ "Target.attachToTarget",
+ {"targetId": target_id, "flatten": True},
+ )
+ session_id = attached.get("sessionId")
+ if not isinstance(session_id, str) or not session_id:
+ raise SmokeError(f"Target.attachToTarget returned no sessionId: {attached!r}")
+ await _success(client, "Page.enable", session_id=session_id)
+ await _success(
+ client,
+ "Emulation.setDeviceMetricsOverride",
+ {
+ "width": 200,
+ "height": 200,
+ "deviceScaleFactor": 1,
+ "mobile": False,
+ },
+ session_id=session_id,
+ )
+ return context_id, session_id
+
+
+async def _navigate(
+ client: RawCdpClient,
+ session_id: str,
+ url: str,
+) -> None:
+ navigation, seen = await _success(
+ client,
+ "Page.navigate",
+ {"url": url},
+ session_id=session_id,
+ )
+ if navigation.get("errorText"):
+ raise SmokeError(f"Page.navigate failed: {navigation!r}")
+ await _wait_for_load(client, session_id, seen)
+
+
+async def _evaluate_json(
+ client: RawCdpClient,
+ session_id: str,
+ expression: str,
+) -> Any:
+ evaluation, _ = await _success(
+ client,
+ "Runtime.evaluate",
+ {"expression": expression, "returnByValue": True},
+ session_id=session_id,
+ )
+ if evaluation.get("exceptionDetails"):
+ raise SmokeError(f"Runtime.evaluate failed: {evaluation!r}")
+ remote = evaluation.get("result")
+ value = remote.get("value") if isinstance(remote, dict) else None
+ if not isinstance(value, str):
+ raise SmokeError(f"Runtime.evaluate returned no JSON string: {evaluation!r}")
+ try:
+ return json.loads(value)
+ except json.JSONDecodeError as error:
+ raise SmokeError(f"Runtime.evaluate returned invalid JSON: {value!r}") from error
+
+
+async def _dispatch_wheel(
+ client: RawCdpClient,
+ session_id: str,
+ delta_y: float,
+) -> None:
+ await _success(
+ client,
+ "Input.dispatchMouseEvent",
+ {
+ "type": "mouseWheel",
+ "x": 20,
+ "y": 20,
+ "deltaX": 0,
+ "deltaY": delta_y,
+ },
+ session_id=session_id,
+ )
+
+
+async def _capture_png(client: RawCdpClient, session_id: str) -> DecodedPng:
+ capture, _ = await _success(
+ client,
+ "Page.captureScreenshot",
+ {
+ "format": "png",
+ "quality": 100,
+ "fromSurface": True,
+ "captureBeyondViewport": False,
+ },
+ session_id=session_id,
+ )
+ encoded = capture.get("data")
+ if not isinstance(encoded, str) or not encoded:
+ raise SmokeError(f"Page.captureScreenshot returned no image: {capture!r}")
+ try:
+ return decode_png(base64.b64decode(encoded, validate=True))
+ except ValueError as error:
+ raise SmokeError("Page.captureScreenshot returned an invalid PNG") from error
+
+
+def _read_json_url(url: str) -> dict[str, Any]:
+ with urllib.request.urlopen(url, timeout=2) as response:
+ value = json.loads(response.read().decode("utf-8"))
+ if not isinstance(value, dict):
+ raise SmokeError(f"fixture returned a non-object from {url}: {value!r}")
+ return value
+
+
+async def _fixture_json(url: str) -> dict[str, Any]:
+ return await asyncio.to_thread(_read_json_url, url)
+
+
+async def _reset_witness(fixture: str) -> None:
+ result = await _fixture_json(f"{fixture}/action-window-witness/reset")
+ assert_equal(result.get("count"), 0, "action-window witness reset")
+
+
+async def _witness_count(fixture: str) -> int:
+ result = await _fixture_json(f"{fixture}/action-window-witness/status")
+ count = result.get("count")
+ if not isinstance(count, int):
+ raise SmokeError(f"action-window witness returned no count: {result!r}")
+ return count
+
+
+async def _wait_for_witness(
+ fixture: str,
+ expected: int,
+ *,
+ timeout: float = 3.0,
+) -> None:
+ deadline = asyncio.get_running_loop().time() + timeout
+ while asyncio.get_running_loop().time() < deadline:
+ if await _witness_count(fixture) >= expected:
+ return
+ await asyncio.sleep(0.025)
+ raise SmokeError(
+ f"timed out waiting for action-window witness count {expected}; "
+ f"observed {await _witness_count(fixture)}"
+ )
+
+
+async def _wait_for_initial_intersection(
+ client: RawCdpClient,
+ session_id: str,
+) -> None:
+ deadline = asyncio.get_running_loop().time() + 2.0
+ while asyncio.get_running_loop().time() < deadline:
+ state = await _evaluate_json(
+ client,
+ session_id,
+ "JSON.stringify(__actionWindowIoLog)",
+ )
+ if state == [False]:
+ return
+ await asyncio.sleep(0.025)
+ raise SmokeError("initial IntersectionObserver state was not published")
+
+
+async def _run_deadline_contract(
+ client: RawCdpClient,
+ session_id: str,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ await _reset_witness(fixture)
+ await _navigate(client, session_id, f"{fixture}/action-window-deadline")
+ await _wait_for_initial_intersection(client, session_id)
+
+ opened_at = asyncio.get_running_loop().time()
+ for index, delta_y in enumerate((100, -100, 100)):
+ await _dispatch_wheel(client, session_id, delta_y)
+ assert_equal(
+ await _witness_count(fixture),
+ 0,
+ f"wheel {index + 1} remains delayed",
+ )
+ if index != 2:
+ # The final admission lands about half a window after the first.
+ # A fixed deadline still releases near 1.0s; a sliding debounce
+ # would move the release to roughly 1.5s.
+ await asyncio.sleep(0.25)
+
+ await _wait_for_witness(fixture, 1)
+ elapsed = asyncio.get_running_loop().time() - opened_at
+ if elapsed < 0.85:
+ raise SmokeError(f"action window applied before its one-second deadline: {elapsed:.3f}s")
+ if elapsed > 1.4:
+ raise SmokeError(f"later wheel input moved the fixed deadline: {elapsed:.3f}s")
+ state = await _evaluate_json(
+ client,
+ session_id,
+ """JSON.stringify({
+ scrollY,
+ wheelLog: __actionWindowWheelLog,
+ ioLog: __actionWindowIoLog
+ })""",
+ )
+ assert_equal(
+ state,
+ {
+ "scrollY": 100,
+ "wheelLog": [
+ "event:100",
+ "event:-100",
+ "event:100",
+ "microtask:100",
+ "microtask:-100",
+ "microtask:100",
+ ],
+ "ioLog": [False, True],
+ },
+ "fixed action-window batch state",
+ )
+ record_contract(
+ results,
+ "raw_cdp_action_window_fixed_deadline_batch",
+ contract=(
+ "wheel acknowledgements remain delayed until one fixed deadline, then preserve "
+ "event order and commit IntersectionObserver work once"
+ ),
+ source="Moli on-demand rendering policy, mirrored by renderer and action-window Rust tests",
+ commands=[
+ "Input.dispatchMouseEvent(mouseWheel) x3",
+ "Runtime.evaluate",
+ ],
+ observed={"elapsedSeconds": round(elapsed, 3), **state},
+ )
+
+
+async def _run_capture_barrier_contract(
+ client: RawCdpClient,
+ session_id: str,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ await _reset_witness(fixture)
+ await _navigate(client, session_id, f"{fixture}/action-window-capture")
+ initial = await _capture_png(client, session_id)
+ assert_equal(initial.pixel(10, 10), (255, 255, 255, 255), "initial capture pixel")
+
+ await _dispatch_wheel(client, session_id, 10)
+ assert_equal(await _witness_count(fixture), 0, "first wheel remains pending")
+ flushed = await _capture_png(client, session_id)
+ assert_equal(flushed.pixel(10, 10), (255, 0, 0, 255), "screenshot flush pixel")
+ await _wait_for_witness(fixture, 1)
+
+ # These two half-window waits straddle the retired window's old deadline
+ # while remaining before the second wheel's fresh deadline.
+ await asyncio.sleep(0.55)
+ second_opened_at = asyncio.get_running_loop().time()
+ await _dispatch_wheel(client, session_id, 20)
+ assert_equal(await _witness_count(fixture), 1, "second wheel starts a fresh window")
+ await asyncio.sleep(0.55)
+ assert_equal(
+ await _witness_count(fixture),
+ 1,
+ "reset window has no inherited periodic deadline",
+ )
+ await _wait_for_witness(fixture, 2)
+ second_elapsed = asyncio.get_running_loop().time() - second_opened_at
+ if second_elapsed < 0.85:
+ raise SmokeError(
+ f"post-screenshot wheel reused the retired window deadline: {second_elapsed:.3f}s"
+ )
+
+ settled = await _capture_png(client, session_id)
+ assert_equal(settled.pixel(10, 10), (0, 255, 0, 255), "fresh-window capture pixel")
+ state = await _evaluate_json(
+ client,
+ session_id,
+ "JSON.stringify({ scrollY, deltas: __actionWindowCaptureDeltas })",
+ )
+ assert_equal(
+ state,
+ {"scrollY": 30, "deltas": [10, 20]},
+ "capture barrier action state",
+ )
+ record_contract(
+ results,
+ "raw_cdp_action_window_screenshot_barrier_reset",
+ contract=(
+ "Page.captureScreenshot flushes pending wheel work before paint and resets the "
+ "window so later input receives a fresh one-second deadline"
+ ),
+ source="Moli on-demand screenshot/read barrier policy",
+ commands=[
+ "Input.dispatchMouseEvent(mouseWheel)",
+ "Page.captureScreenshot",
+ "Input.dispatchMouseEvent(mouseWheel)",
+ "Page.captureScreenshot",
+ ],
+ observed={
+ "firstPixel": list(flushed.pixel(10, 10)),
+ "secondPixel": list(settled.pixel(10, 10)),
+ "secondElapsedSeconds": round(second_elapsed, 3),
+ **state,
+ },
+ )
+
+
+async def _run_replacement_contract(
+ client: RawCdpClient,
+ session_id: str,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ await _navigate(client, session_id, f"{fixture}/action-window-replacement")
+ for delta_y in (10, 20, 30):
+ await _dispatch_wheel(client, session_id, delta_y)
+ await asyncio.sleep(1.1)
+ state = await _evaluate_json(
+ client,
+ session_id,
+ """JSON.stringify({
+ retired: __actionWindowRetiredDeltas,
+ replacement: __actionWindowReplacementDeltas
+ })""",
+ )
+ assert_equal(
+ state,
+ {"retired": [10], "replacement": []},
+ "in-batch Document replacement isolation",
+ )
+ record_contract(
+ results,
+ "raw_cdp_action_window_document_replacement_isolation",
+ contract=(
+ "wheel work admitted for one exact Document stops when its first handler calls "
+ "document.open and never continues in the replacement Document"
+ ),
+ source="Moli exact RendererDocumentLifecycleIdentity action scope",
+ commands=[
+ "Input.dispatchMouseEvent(mouseWheel) x3",
+ "Runtime.evaluate",
+ ],
+ observed=state,
+ )
+
+
+async def run_action_window_group(
+ endpoint: str,
+ fixture: str,
+ 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
+
+ client = await connect_raw_cdp(endpoint)
+ context_id: str | None = None
+ try:
+ context_id, session_id = await _open_target(client)
+ await _run_deadline_contract(client, session_id, fixture, results)
+ await _run_capture_barrier_contract(client, session_id, fixture, results)
+ await _run_replacement_contract(client, session_id, fixture, results)
+ finally:
+ if context_id is not None:
+ try:
+ await _success(
+ client,
+ "Target.disposeBrowserContext",
+ {"browserContextId": context_id},
+ )
+ except Exception:
+ pass
+ await client.websocket.close()
diff --git a/moli-cdp-smoke/moli_cdp_smoke/runner.py b/moli-cdp-smoke/moli_cdp_smoke/runner.py
index 49cfe0435..c767f1f1a 100644
--- a/moli-cdp-smoke/moli_cdp_smoke/runner.py
+++ b/moli-cdp-smoke/moli_cdp_smoke/runner.py
@@ -17,6 +17,7 @@ from playwright.async_api import async_playwright
from .assertions import record
from .config import clear_current_process_proxy_env, reserve_port
from .fixture import FixtureServer
+from .groups.action_window import run_action_window_group
from .groups.agent_browser import run_agent_browser_group
from .groups.agent_episode import run_agent_episode_group
from .groups.browser_semantics import run_browser_semantics_group, run_target_semantics_group
@@ -85,6 +86,12 @@ RAW_GROUPS: tuple[SmokeGroup, ...] = (
run_inspector_routing_group,
default=False,
),
+ SmokeGroup(
+ "action-window",
+ "Moli raw-CDP wheel batching, screenshot flush/reset, and exact-Document retirement contracts.",
+ "raw",
+ run_action_window_group,
+ ),
SmokeGroup(
"url-policy",
"Hosted file URL rejection across raw Page.navigate and Runtime fetch/XHR without lifecycle, interception, or transport leakage.",
diff --git a/moli-cdp-smoke/tests/test_action_window.py b/moli-cdp-smoke/tests/test_action_window.py
new file mode 100644
index 000000000..e9d2e7955
--- /dev/null
+++ b/moli-cdp-smoke/tests/test_action_window.py
@@ -0,0 +1,62 @@
+from __future__ import annotations
+
+import json
+import unittest
+import urllib.request
+
+from moli_cdp_smoke.fixture import FixtureServer
+from moli_cdp_smoke.runner import DEFAULT_GROUP_NAMES, GROUPS_BY_NAME
+
+
+class ActionWindowGroupTests(unittest.TestCase):
+ def test_group_is_a_default_raw_contract(self) -> None:
+ group = GROUPS_BY_NAME["action-window"]
+
+ self.assertEqual(group.phase, "raw")
+ self.assertTrue(group.default)
+ self.assertIn(group.name, DEFAULT_GROUP_NAMES)
+
+
+class ActionWindowFixtureTests(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls) -> None:
+ cls.fixture = FixtureServer()
+ cls.fixture.start()
+
+ @classmethod
+ def tearDownClass(cls) -> None:
+ cls.fixture.stop()
+
+ def read(self, path: str) -> tuple[str, str]:
+ with urllib.request.urlopen(f"{self.fixture.url}{path}", timeout=2) as response:
+ return response.headers.get_content_type(), response.read().decode("utf-8")
+
+ def read_json(self, path: str) -> dict[str, object]:
+ content_type, body = self.read(path)
+ self.assertEqual(content_type, "application/json")
+ value = json.loads(body)
+ self.assertIsInstance(value, dict)
+ return value
+
+ def test_witness_counter_resets_and_counts_entries(self) -> None:
+ self.assertEqual(self.read_json("/action-window-witness/reset"), {"count": 0})
+ self.assertEqual(self.read_json("/action-window-witness/status"), {"count": 0})
+ self.assertEqual(self.read_json("/action-window-witness/entered"), {"count": 1})
+ self.assertEqual(self.read_json("/action-window-witness/status"), {"count": 1})
+
+ def test_action_window_pages_expose_each_contract_fixture(self) -> None:
+ expected_markers = {
+ "/action-window-deadline": "__actionWindowObserver",
+ "/action-window-capture": "__actionWindowCaptureDeltas",
+ "/action-window-replacement": "__actionWindowReplacementDeltas",
+ }
+
+ for path, marker in expected_markers.items():
+ with self.subTest(path=path):
+ content_type, body = self.read(path)
+ self.assertEqual(content_type, "text/html")
+ self.assertIn(marker, body)
+
+
+if __name__ == "__main__":
+ unittest.main()