Skip to content

armgit / moli

Public Imported from GitHub
0

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

test(frontend): preserve CDP timeout command and checkpoint context

ldm0a29b5fbe134e
diff --git a/moli-frontend-smoke/README.md b/moli-frontend-smoke/README.md
index a34ae7827..6f0f306ce 100644
--- a/moli-frontend-smoke/README.md
+++ b/moli-frontend-smoke/README.md
@@ -143,6 +143,10 @@ Generated files live under `dist/` and `artifacts/` and are ignored. The runner
fixture-tree hash against the manifest before starting browsers. A failed case gets its own
artifact directory with final DOM JSON, diagnostics, timeline metadata, normalized DOM JSON for
every captured frame, and per-frame unified diffs when both engines produced a tree.
+For a CDP timeout, diagnostics also include the pending method, request and session ids,
+observation stage, and last observed checkpoint. This distinguishes waiting for the next
+checkpoint from resuming the previous one, which can otherwise report the same `Runtime.evaluate`
+timeout with identical partial frames.
Validate the expected artifact set, recompute DOM hashes/node counts and diffs, and print
non-gating diagnostic projections:
diff --git a/moli-frontend-smoke/moli_frontend_smoke/cdp.py b/moli-frontend-smoke/moli_frontend_smoke/cdp.py
index 5ba3fd6e3..e24c0366f 100644
--- a/moli-frontend-smoke/moli_frontend_smoke/cdp.py
+++ b/moli-frontend-smoke/moli_frontend_smoke/cdp.py
@@ -17,6 +17,28 @@ class CdpError(RuntimeError):
pass
+class CdpTimeoutError(CdpError):
+ def __init__(
+ self,
+ method: str,
+ operation: str,
+ timeout: float,
+ *,
+ message_id: int | None = None,
+ session_id: str | None = None,
+ ) -> None:
+ super().__init__(
+ f"timed out waiting for {method} {operation} after {timeout:g}s"
+ )
+ self.context = {
+ "method": method,
+ "operation": operation,
+ "timeoutSeconds": timeout,
+ "commandId": message_id,
+ "sessionId": session_id,
+ }
+
+
class FixtureObservationError(CdpError):
"""The page or fixture violated its deterministic observation contract."""
@@ -92,15 +114,18 @@ class RawCdpClient:
) -> dict[str, Any]:
message_id = await self.send(method, params, session_id=session_id)
deadline = asyncio.get_running_loop().time() + timeout
- timeout_message = f"timed out waiting for {method} response after {timeout:g}s"
while True:
remaining = deadline - asyncio.get_running_loop().time()
if remaining <= 0:
- raise CdpError(timeout_message)
+ raise CdpTimeoutError(
+ method, "response", timeout, message_id=message_id, session_id=session_id,
+ )
try:
message = await asyncio.wait_for(self.recv(), timeout=remaining)
except TimeoutError as error:
- raise CdpError(timeout_message) from error
+ raise CdpTimeoutError(
+ method, "response", timeout, message_id=message_id, session_id=session_id,
+ ) from error
if message.get("id") == message_id:
if "error" in message:
raise CdpCommandError(method, message["error"])
@@ -127,15 +152,14 @@ class RawCdpClient:
if matches(message):
return message
deadline = asyncio.get_running_loop().time() + timeout
- timeout_message = f"timed out waiting for {method} event after {timeout:g}s"
while True:
remaining = deadline - asyncio.get_running_loop().time()
if remaining <= 0:
- raise CdpError(timeout_message)
+ raise CdpTimeoutError(method, "event", timeout, session_id=session_id)
try:
message = await asyncio.wait_for(self.recv(), timeout=remaining)
except TimeoutError as error:
- raise CdpError(timeout_message) from error
+ raise CdpTimeoutError(method, "event", timeout, session_id=session_id) from error
self.events.append(message)
if matches(message):
return message
@@ -436,6 +460,8 @@ async def observe_case(
frames: list[DomFrameObservation] = []
final_root: dict[str, Any] | None = None
diagnostics: dict[str, Any] = {}
+ observation_stage = "setup"
+ checkpoint: dict[str, Any] | None = None
command_timeout = max(10.0, timeout_ms / 1000 + 2.0)
try:
if client is None:
@@ -472,12 +498,14 @@ async def observe_case(
timeout=command_timeout,
)
await client.command("Network.enable", session_id=session_id, timeout=command_timeout)
+ observation_stage = "navigate"
await client.command(
"Page.navigate",
{"url": url},
session_id=session_id,
timeout=command_timeout,
)
+ observation_stage = "wait_load"
await client.wait_event(
"Page.loadEventFired",
session_id=session_id,
@@ -485,6 +513,7 @@ async def observe_case(
)
after_token: str | None = None
while True:
+ observation_stage = "wait_checkpoint"
evaluation = await client.command(
"Runtime.evaluate",
{
@@ -527,6 +556,8 @@ async def observe_case(
raise FixtureObservationError(
"fixture exceeded the 32-frame safety limit"
)
+ checkpoint = pending
+ observation_stage = "capture_checkpoint"
root = await _capture_document(
client,
session_id=session_id,
@@ -535,6 +566,7 @@ async def observe_case(
frames.append(
DomFrameObservation(index=index, name=name, token=token, dom=root)
)
+ observation_stage = "resume_checkpoint"
resumed = await client.command(
"Runtime.evaluate",
{
@@ -571,6 +603,7 @@ async def observe_case(
)
break
+ observation_stage = "capture_settled"
final_root = await _capture_document(
client,
session_id=session_id,
@@ -603,6 +636,12 @@ async def observe_case(
except Exception as error:
if not diagnostics:
diagnostics = _diagnostics(client.events, session_id) if client and session_id else {}
+ if isinstance(error, CdpTimeoutError):
+ diagnostics["timeout"] = {
+ **error.context,
+ "observationStage": observation_stage,
+ "lastCheckpoint": checkpoint,
+ }
return EngineObservation(
engine=engine,
ok=False,
diff --git a/moli-frontend-smoke/tests/test_cdp.py b/moli-frontend-smoke/tests/test_cdp.py
index a55a133c3..cb05fc58b 100644
--- a/moli-frontend-smoke/tests/test_cdp.py
+++ b/moli-frontend-smoke/tests/test_cdp.py
@@ -6,6 +6,7 @@ import pytest
from moli_frontend_smoke.cdp import (
CdpCommandError,
+ CdpTimeoutError,
FixtureObservationError,
_DOM_ENABLE_PARAMS,
_OBSERVABLE_TREE_BARRIER_EXPRESSION,
@@ -117,6 +118,66 @@ def test_observe_case_marks_cdp_command_errors_as_infrastructure() -> None:
assert client.websocket.close_count == 0
[email protected]("timeout_stage", ["wait_checkpoint", "resume_checkpoint"])
+def test_timeout_distinguishes_waiting_after_a_frame_from_resuming_it(timeout_stage: str) -> None:
+ case = _case()
+ mounted = {"index": 1, "name": "mounted", "token": f"{case.id}:1:mounted"}
+
+ class Client(_FixtureFailureClient):
+ resumes = 0
+
+ async def command(self, method, params=None, **kwargs):
+ if method == "DOM.getDocument":
+ return {"root": {"nodeType": 9, "nodeName": "#document"}}
+ if method != "Runtime.evaluate":
+ return await super().command(method, params, **kwargs)
+ expression = params["expression"]
+ if expression == _OBSERVABLE_TREE_BARRIER_EXPRESSION:
+ return {"result": {"value": 1}}
+ resume = "__MOLI_FRONTEND_SMOKE_RESUME__" in expression
+ if (resume and self.resumes == 1 and timeout_stage == "resume_checkpoint") or (
+ not resume and self.resumes == 2
+ ):
+ raise CdpTimeoutError(
+ method, "response", 32, message_id=73, session_id="session",
+ )
+ if resume:
+ self.resumes += 1
+ return {"result": {"value": True}}
+ name = ["document", "mounted"][self.resumes]
+ return {"result": {"value": {
+ "id": case.id,
+ "phase": "checkpoint",
+ "pendingFrame": {
+ "index": self.resumes,
+ "name": name,
+ "token": f"{case.id}:{self.resumes}:{name}",
+ },
+ }}}
+
+ client = Client()
+ observation = asyncio.run(observe_case(
+ engine="moli", endpoint="http://127.0.0.1:9222", case=case,
+ url="http://127.0.0.1:3000/case", timeout_ms=30000,
+ client=client, # type: ignore[arg-type]
+ ))
+
+ assert not observation.ok
+ assert observation.failure_kind == "infrastructure"
+ assert [frame.name for frame in observation.frames] == ["document", "mounted"]
+ assert observation.ready_state["pendingFrame"] == mounted
+ assert observation.diagnostics["timeout"] == {
+ "method": "Runtime.evaluate",
+ "operation": "response",
+ "timeoutSeconds": 32,
+ "commandId": 73,
+ "sessionId": "session",
+ "observationStage": timeout_stage,
+ "lastCheckpoint": mounted,
+ }
+ assert client.methods[-1] == "Target.disposeBrowserContext"
+
+
def test_diagnostics_preserve_runtime_console_and_network_failures() -> None:
events = [
{
diff --git a/moli-frontend-smoke/tests/test_cdp_timeouts.py b/moli-frontend-smoke/tests/test_cdp_timeouts.py
index cc9cb3577..1abfc3418 100644
--- a/moli-frontend-smoke/tests/test_cdp_timeouts.py
+++ b/moli-frontend-smoke/tests/test_cdp_timeouts.py
@@ -7,7 +7,7 @@ import json
import pytest
from websockets.asyncio.server import serve
-from moli_frontend_smoke.cdp import CdpError, RawCdpClient, connect
+from moli_frontend_smoke.cdp import CdpError, CdpTimeoutError, RawCdpClient, connect
@pytest.mark.parametrize("timeout", [0.25, 5.0])
@@ -74,12 +74,20 @@ def test_timeout_diagnostic_identifies_the_pending_operation(operation: str) ->
async def scenario() -> None:
client = RawCdpClient(websocket=_SilentSocket()) # type: ignore[arg-type]
if operation == "command":
- with pytest.raises(CdpError, match="Target.createTarget response after 0.01s"):
- await client.command("Target.createTarget", timeout=0.01)
+ with pytest.raises(CdpError, match="Target.createTarget response after 0.01s") as raised:
+ await client.command("Target.createTarget", session_id="page", timeout=0.01)
else:
- with pytest.raises(CdpError, match="Page.loadEventFired event after 0.01s"):
+ with pytest.raises(CdpError, match="Page.loadEventFired event after 0.01s") as raised:
await client.wait_event(
"Page.loadEventFired", session_id="page", timeout=0.01,
)
+ assert isinstance(raised.value, CdpTimeoutError)
+ assert raised.value.context == {
+ "method": "Target.createTarget" if operation == "command" else "Page.loadEventFired",
+ "operation": "response" if operation == "command" else "event",
+ "timeoutSeconds": 0.01,
+ "commandId": 1 if operation == "command" else None,
+ "sessionId": "page",
+ }
asyncio.run(scenario())