Skip to content

The agent that grows with you

fix(browser): fence captured CDP dispatch and retain late replies

web3blindaad11beae05a
diff --git a/tests/tools/test_browser_supervisor_capture_dispatch.py b/tests/tools/test_browser_supervisor_capture_dispatch.py
new file mode 100644
index 00000000000..1505dab7bd4
--- /dev/null
+++ b/tests/tools/test_browser_supervisor_capture_dispatch.py
@@ -0,0 +1,118 @@
+"""Dispatch/lossless-wait extension exercised through the real public capture API."""
+import asyncio
+import json
+import threading
+import time
+import pytest
+from tests.tools.test_browser_supervisor_capture import _FakeCDP, _wait
+from tools.browser_supervisor import _SupervisorRegistry
+
+class DelayedCDP(_FakeCDP):
+ async def _handle(self, ws):
+ self.connections.append(ws)
+ conn = len(self.connections)
+ async for raw in ws:
+ msg = json.loads(raw)
+ method, sid = msg['method'], msg.get('sessionId')
+ self.frames.append((conn, method, sid))
+ result = {'echo':method}
+ if method == 'Target.getTargets':
+ result = {'targetInfos':[{'targetId':'fixture-parent','type':'page','url':'about:blank'}]}
+ elif method == 'Target.attachToTarget':
+ if msg.get('params',{}).get('targetId') == 'late-child':
+ await asyncio.sleep(.2)
+ result = {'sessionId':'late-owned-session'}
+ else:
+ result = {'sessionId':'default-session'}
+ await ws.send(json.dumps({'id':msg['id'],'result':result}))
+
+def pair():
+ server, registry = DelayedCDP(), _SupervisorRegistry()
+ sup = registry.get_or_start('fixture', server.url, start_timeout=5)
+ try:
+ yield server, registry, sup, registry.capture('fixture')
+ finally:
+ registry.stop_all()
+
+
+def test_unbounded_reply_retains_late_attachment_for_consumer_cleanup(pair):
+ server, registry, sup, handle = pair
+ abandoned = threading.Event()
+ outcomes = []
+ def worker():
+ result = handle.call('Target.attachToTarget', {'targetId':'late-child','flatten':True}, timeout=None)
+ outcomes.append(result['result']['sessionId'])
+ if abandoned.is_set():
+ handle.call('Target.detachFromTarget', {'sessionId':outcomes[-1]})
+ thread = threading.Thread(target=worker)
+ thread.start()
+ _wait(lambda: len([m for m in server.methods_on(1) if m == 'Target.attachToTarget']) == 2)
+ abandoned.set()
+ thread.join(3)
+ assert not thread.is_alive()
+ assert outcomes == ['late-owned-session']
+ assert server.methods_on(1).count('Target.detachFromTarget') == 1
+
+
+def test_dispatch_deadline_refuses_queued_command_after_timeout(pair):
+ server, registry, sup, handle = pair
+ entered, release = threading.Event(), threading.Event()
+ def block():
+ entered.set()
+ release.wait(4)
+ sup._loop.call_soon_threadsafe(block)
+ assert entered.wait(1)
+ try:
+ with pytest.raises(TimeoutError):
+ handle.call('Probe.expired', timeout=.03)
+ finally:
+ release.set()
+ handle.call('Target.getTargets', timeout=2)
+ assert 'Probe.expired' not in server.methods_on(1)
+
+
+def test_before_send_checks_cancellation_on_supervisor_loop(pair):
+ server, registry, sup, handle = pair
+ entered, release, abandoned = threading.Event(), threading.Event(), threading.Event()
+ failures = []
+ def block():
+ entered.set()
+ release.wait(4)
+ def check():
+ assert asyncio.get_running_loop() is sup._loop
+ if abandoned.is_set():
+ raise ValueError('fixture cancelled')
+ def caller():
+ try:
+ handle.call('Probe.cancelled', timeout=2, before_send=check)
+ except BaseException as exc:
+ failures.append(exc)
+ sup._loop.call_soon_threadsafe(block)
+ assert entered.wait(1)
+ thread = threading.Thread(target=caller)
+ thread.start()
+ abandoned.set()
+ release.set()
+ thread.join(3)
+ assert failures and isinstance(failures[0], ValueError)
+ assert 'Probe.cancelled' not in server.methods_on(1)
+
+
+def test_unbounded_reply_fails_promptly_on_socket_close(pair):
+ server, registry, sup, handle = pair
+ failures = []
+ # This fixture replies to ordinary methods; block the connection handler on attach instead.
+ def attach():
+ try:
+ handle.call('Target.attachToTarget', {'targetId':'late-child'}, timeout=None)
+ except BaseException as exc:
+ failures.append(exc)
+ thread = threading.Thread(target=attach)
+ thread.start()
+ _wait(lambda: server.methods_on(1).count('Target.attachToTarget') == 2)
+ server.drop_current()
+ thread.join(3)
+ assert not thread.is_alive()
+ assert failures
+
diff --git a/tests/tools/test_browser_supervisor_capture_validation.py b/tests/tools/test_browser_supervisor_capture_validation.py
new file mode 100644
index 00000000000..0179aa79f43
--- /dev/null
+++ b/tests/tools/test_browser_supervisor_capture_validation.py
@@ -0,0 +1,20 @@
+import pytest
+from tests.tools.test_browser_supervisor_capture_dispatch import pair # noqa: F401
+
[email protected]('timeout', [0, -1, float('inf'), float('nan'), 1e300, True, '5'])
+def test_invalid_timeout(pair, timeout):
+ server, _, _, cap = pair
+ before = list(server.methods_on(1))
+ with pytest.raises(ValueError):
+ cap.call('Probe.invalid', timeout=timeout)
+ assert server.methods_on(1) == before
+
+
+def test_async_validator_refuses(pair):
+ server, _, _, cap = pair
+ before = list(server.methods_on(1))
+ async def check():
+ return None
+ with pytest.raises(TypeError):
+ cap.call('Probe.async', before_send=check)
+ assert server.methods_on(1) == before
diff --git a/tools/browser_supervisor.py b/tools/browser_supervisor.py
index 6f5b022239d..d8945455e76 100644
--- a/tools/browser_supervisor.py
+++ b/tools/browser_supervisor.py
@@ -449,7 +449,7 @@ class CDPSupervisor(DialogSupervisionMixin, FrameTrackingMixin):
await self._install_dialog_bridge(sid)
async def _cdp(self, method: str, params: Optional[dict[str, Any]] = None, *,
- session_id: Optional[str] = None, timeout: float = 10.0) -> dict[str, Any]:
+ session_id: Optional[str] = None, timeout: Optional[float] = 10.0) -> dict[str, Any]:
"""Send a CDP command and await its response."""
if self._ws is None:
raise RuntimeError("supervisor WebSocket is not connected")
diff --git a/tools/browser_supervisor_capture.py b/tools/browser_supervisor_capture.py
index 29d9a10ab1f..913036e7a7f 100644
--- a/tools/browser_supervisor_capture.py
+++ b/tools/browser_supervisor_capture.py
@@ -14,7 +14,11 @@ from __future__ import annotations
import asyncio
import concurrent.futures
-from typing import TYPE_CHECKING, Any, Dict, Optional
+import inspect
+import math
+import threading
+import time
+from typing import TYPE_CHECKING, Any, Callable, Optional
if TYPE_CHECKING:
from tools.browser_supervisor import CDPSupervisor, _SupervisorRegistry
@@ -50,9 +54,22 @@ class CapturedCDP:
"(supervisor reconnected, stopped or was replaced); capture again")
async def _send(self, method: str, params: Optional[dict[str, Any]],
- session_id: Optional[str], timeout: float) -> dict[str, Any]:
+ session_id: Optional[str], timeout: Optional[float],
+ deadline: Optional[float], before_send: Optional[Callable[[], None]]) -> dict[str, Any]:
# ``_cdp`` reaches its send without awaiting, so this check and the send run in one
# loop step: a reconnect cannot swap the socket in between.
+ if not self.is_valid():
+ raise self._invalid()
+ if deadline is not None and time.monotonic() >= deadline:
+ raise TimeoutError("Captured CDP dispatch deadline expired")
+ if before_send is not None:
+ outcome = before_send()
+ if outcome is not None:
+ if inspect.iscoroutine(outcome):
+ outcome.close()
+ raise TypeError("before_send must return None synchronously")
+ if deadline is not None and time.monotonic() >= deadline:
+ raise TimeoutError("Captured CDP dispatch deadline expired")
if not self.is_valid():
raise self._invalid()
try:
@@ -65,7 +82,8 @@ class CapturedCDP:
raise
def call(self, method: str, params: Optional[dict[str, Any]] = None, *,
- session_id: Optional[str] = None, timeout: float = 10.0) -> dict[str, Any]:
+ session_id: Optional[str] = None, timeout: Optional[float] = 10.0,
+ before_send: Optional[Callable[[], None]] = None) -> dict[str, Any]:
"""Send ``method`` on the captured connection and return the raw CDP reply
(``{"id", "result"}``). ``session_id=None`` targets the browser endpoint;
pass ``page_session_id`` (or a session you attached) for page domains.
@@ -73,7 +91,27 @@ class CapturedCDP:
Raises ``CapturedCDPInvalid`` when the connection is gone, ``TimeoutError`` when no
reply arrives in ``timeout`` seconds, ``RuntimeError`` for a CDP error reply.
Blocks the calling thread; never call it from the supervisor's own loop.
+
+ A finite timeout also fences send admission while this call waits in the
+ supervisor queue. ``timeout=None`` deliberately retains a reply until
+ the connection closes: use it only in a consumer-owned worker when a
+ late reply (for example an attachment session ID) must not be lost.
+ Keep the consumer's own wait/issuance deadline finite and retain cleanup
+ responsibility after it expires.
+
+ ``before_send`` is a trusted synchronous nonblocking validation callback
+ run on the supervisor loop immediately before CDP dispatch. It may raise
+ to refuse a cancelled/expired operation. It must not call a blocking
+ capture/CDP API. This is not origin or target-ownership authorization.
"""
+ if timeout is not None:
+ if (isinstance(timeout, bool) or not isinstance(timeout, (int, float))
+ or not math.isfinite(timeout) or timeout <= 0
+ or timeout > threading.TIMEOUT_MAX - 1.0):
+ raise ValueError("Captured CDP timeout must be positive and finite, or None")
+ if before_send is not None and not callable(before_send):
+ raise TypeError("before_send must be callable")
+ deadline = None if timeout is None else time.monotonic() + timeout
try:
running = asyncio.get_running_loop()
except RuntimeError:
@@ -84,11 +122,11 @@ class CapturedCDP:
raise self._invalid()
from agent.async_utils import safe_schedule_threadsafe
- fut = safe_schedule_threadsafe(self._send(method, params, session_id, timeout), self._loop)
+ fut = safe_schedule_threadsafe(self._send(method, params, session_id, timeout, deadline, before_send), self._loop)
if fut is None:
raise self._invalid()
try:
- return fut.result(timeout=timeout + 1.0)
+ return fut.result(timeout=None if timeout is None else timeout + 1.0)
except concurrent.futures.TimeoutError:
fut.cancel()
raise TimeoutError(f"CDP {method} got no reply within {timeout}s") from None
diff --git a/website/docs/developer-guide/browser-supervisor.md b/website/docs/developer-guide/browser-supervisor.md
index 2d8adef0acf..8dfcee65f7f 100644
--- a/website/docs/developer-guide/browser-supervisor.md
+++ b/website/docs/developer-guide/browser-supervisor.md
@@ -116,11 +116,14 @@ title = reply["result"]["result"]["value"]
- `SUPERVISOR_REGISTRY.capture(task_id, *, timeout=10.0) -> CapturedCDP` pins the
supervisor's current WebSocket and the default page session attached on it. It
never starts, reconnects or refocuses a supervisor.
-- `CapturedCDP.call(method, params=None, *, session_id=None, timeout=10.0) -> dict`
+- `CapturedCDP.call(method, params=None, *, session_id=None, timeout=10.0, before_send=None) -> dict`
returns the raw CDP reply (`{"id", "result"}`). `session_id=None` addresses the
browser endpoint (`Target.*`); pass `page_session_id` or a session you attached
yourself for page domains. A CDP error reply raises `RuntimeError`; no reply
- within `timeout` raises `TimeoutError`. The call blocks its thread, so call it
+ within a finite `timeout` raises `TimeoutError`. Finite timeouts fence queue
+ admission with a monotonic deadline. `timeout=None` retains the reply until
+ response or connection closure; acquisition owners can keep late attach IDs
+ for cleanup beyond their own outer deadline. The call blocks its thread, so call it
from a worker thread, never from the supervisor's own event loop.
- `CapturedCDP.is_valid()` stays true until the supervisor reconnects, stops, or
is replaced in the registry. After that every `call` raises
@@ -131,7 +134,11 @@ title = reply["result"]["result"]["value"]
`focus_page` on the supervisor does not change it.
- Sessions you attach (`Target.attachToTarget`) are yours to detach. A reply
that arrives after `timeout` is dropped, so a timed-out attach can leave a
- session attached until the connection closes; give attaches a generous timeout.
+ session attached until the connection closes. Use `timeout=None` with a retained
+ acquisition worker to own and detach late replies, rather than guessing a large timeout.
+- `before_send` is a trusted synchronous, nonblocking validator on the supervisor
+ loop immediately before dispatch. Return `None`, or raise to refuse; do not call
+ capture/CDP APIs from it. It does not revoke commands already dispatched.
This is a trusted, in-process seam. It grants nothing in-process Python could
not already reach, and it enforces no origin, consent or target-ownership