Skip to content

The agent that grows with you

fix(browser): bound CDP supervisor reconnects

KoNit-K67b061a51cef
diff --git a/tests/tools/test_browser_supervisor.py b/tests/tools/test_browser_supervisor.py
index 6e56cc69e67..4c551308d16 100644
--- a/tests/tools/test_browser_supervisor.py
+++ b/tests/tools/test_browser_supervisor.py
@@ -40,17 +40,10 @@ import time
import pytest
-pytestmark = [
- pytest.mark.integration,
- pytest.mark.skipif(
- os.environ.get("HERMES_E2E_BROWSER", "").strip() != "1",
- reason="real-browser E2E: set HERMES_E2E_BROWSER=1 to opt in",
- ),
- pytest.mark.skipif(
- not shutil.which("google-chrome") and not shutil.which("chromium"),
- reason="Chrome/Chromium not installed",
- ),
-]
+_requires_browser = pytest.mark.skipif(
+ os.environ.get("HERMES_E2E_BROWSER", "").strip() != "1",
+ reason="real-browser E2E: set HERMES_E2E_BROWSER=1 to opt in",
+)
def _find_chrome() -> str:
@@ -219,6 +212,8 @@ def _wait_for_dialog(supervisor, timeout: float = 5.0):
return ()
+@_requires_browser
def test_supervisor_start_and_snapshot(chrome_cdp, supervisor_registry):
"""Supervisor attaches, exposes an active snapshot with a top frame."""
cdp_url, _port = chrome_cdp
@@ -237,6 +232,8 @@ def test_supervisor_start_and_snapshot(chrome_cdp, supervisor_registry):
assert snap.frame_tree.get("top") is not None
+@_requires_browser
def test_main_frame_alert_detection_and_dismiss(chrome_cdp, supervisor_registry):
"""alert() in the main frame surfaces and can be dismissed via the sync API."""
cdp_url, _port = chrome_cdp
@@ -256,6 +253,8 @@ def test_main_frame_alert_detection_and_dismiss(chrome_cdp, supervisor_registry)
assert supervisor.snapshot().pending_dialogs == ()
+@_requires_browser
def test_iframe_contentwindow_alert(chrome_cdp, supervisor_registry):
"""alert() fired from inside a same-origin iframe surfaces too."""
cdp_url, _port = chrome_cdp
@@ -273,6 +272,8 @@ def test_iframe_contentwindow_alert(chrome_cdp, supervisor_registry):
assert result["ok"] is True
+@_requires_browser
def test_prompt_dialog_with_response_text(chrome_cdp, supervisor_registry):
"""prompt() gets our prompt_text back inside the page."""
cdp_url, _port = chrome_cdp
@@ -293,6 +294,8 @@ def test_prompt_dialog_with_response_text(chrome_cdp, supervisor_registry):
assert result["ok"] is True
+@_requires_browser
def test_browser_dialog_tool_end_to_end(chrome_cdp, supervisor_registry):
"""Full agent-path check: fire an alert, call the tool handler directly."""
from tools.browser_dialog_tool import browser_dialog
@@ -309,6 +312,8 @@ def test_browser_dialog_tool_end_to_end(chrome_cdp, supervisor_registry):
assert "PYTEST-TOOL-END2END" in r["dialog"]["message"]
+@_requires_browser
def test_browser_cdp_frame_id_real_oopif_smoke_documented():
"""Document that real-OOPIF E2E was manually verified — see PR #14540.
@@ -340,6 +345,8 @@ def test_browser_cdp_frame_id_real_oopif_smoke_documented():
)
+@_requires_browser
def test_evaluate_runtime_unserializable_value(chrome_cdp, supervisor_registry):
"""``Infinity``/``NaN``/``BigInt`` come back via ``unserializableValue``."""
cdp_url, _port = chrome_cdp
@@ -351,3 +358,97 @@ def test_evaluate_runtime_unserializable_value(chrome_cdp, supervisor_registry):
out = supervisor.evaluate_runtime("Infinity")
assert out["ok"] is True
assert out["result"] == "Infinity"
+
+
+class _ClosingWebSocket:
+ async def close(self):
+ pass
+
+
+def test_supervisor_stops_after_bounded_post_attach_reconnect_failures(monkeypatch):
+ """A dead endpoint cannot keep a previously attached supervisor alive forever."""
+ from tools import browser_supervisor as bs
+
+ supervisor = bs.CDPSupervisor(task_id="bounded-reconnect", cdp_url="ws://127.0.0.1:9222")
+ attempts = 0
+
+ async def connect(*_args, **_kwargs):
+ nonlocal attempts
+ attempts += 1
+ if attempts == 1:
+ return _ClosingWebSocket()
+ if attempts <= 3:
+ raise ConnectionError("CDP endpoint is gone")
+ await asyncio.Event().wait()
+
+ async def attach():
+ pass
+
+ async def reader():
+ pass
+
+ async def immediate_sleep(_delay):
+ pass
+
+ import websockets
+
+ monkeypatch.setattr(websockets, "connect", connect)
+ monkeypatch.setattr(supervisor, "_attach_initial_page", attach)
+ monkeypatch.setattr(supervisor, "_read_loop", reader)
+ monkeypatch.setattr(bs.asyncio, "sleep", immediate_sleep)
+ monkeypatch.setattr(bs, "MAX_POST_ATTACH_RECONNECT_FAILURES", 2, raising=False)
+
+ asyncio.run(asyncio.wait_for(supervisor._run(), timeout=0.1))
+
+ assert attempts == 3 # Initial attach plus the bounded reconnect failures.
+ assert supervisor.snapshot().active is False
+
+
+def test_supervisor_does_not_reconnect_after_explicit_stop(monkeypatch):
+ """An explicit stop during a live session suppresses a reconnect attempt."""
+ from tools import browser_supervisor as bs
+
+ supervisor = bs.CDPSupervisor(task_id="explicit-stop", cdp_url="ws://127.0.0.1:9222")
+ attempts = 0
+
+ async def connect(*_args, **_kwargs):
+ nonlocal attempts
+ attempts += 1
+ return _ClosingWebSocket()
+
+ async def attach():
+ pass
+
+ async def reader():
+ supervisor._stop_requested = True
+
+ import websockets
+
+ monkeypatch.setattr(websockets, "connect", connect)
+ monkeypatch.setattr(supervisor, "_attach_initial_page", attach)
+ monkeypatch.setattr(supervisor, "_read_loop", reader)
+
+ asyncio.run(supervisor._run())
+
+ assert attempts == 1
+ assert supervisor.snapshot().active is False
+
+
+def test_supervisor_keeps_initial_connect_failures_fatal(monkeypatch):
+ """Reconnect budgeting applies only after the first successful attachment."""
+ from tools import browser_supervisor as bs
+
+ supervisor = bs.CDPSupervisor(task_id="initial-failure", cdp_url="ws://127.0.0.1:9222")
+
+ async def connect(*_args, **_kwargs):
+ raise ConnectionError("CDP endpoint is unavailable")
+
+ import websockets
+
+ monkeypatch.setattr(websockets, "connect", connect)
+
+ asyncio.run(supervisor._run())
+
+ assert isinstance(supervisor._start_error, ConnectionError)
+ assert supervisor._ready_event.is_set()
+ assert supervisor.snapshot().active is False
diff --git a/tools/browser_supervisor.py b/tools/browser_supervisor.py
index 5a35cf59b64..8b3d720967e 100644
--- a/tools/browser_supervisor.py
+++ b/tools/browser_supervisor.py
@@ -32,6 +32,12 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
+# Browserbase can transiently drop a CDP socket while a short-lived client
+# reconnects. A locally owned browser endpoint, however, is gone for good
+# once its process exits; leave enough room for the former without leaking a
+# supervisor thread and warnings forever for the latter.
+MAX_POST_ATTACH_RECONNECT_FAILURES = 5
+
def _redact_cdp_error_text(exc: object) -> str:
"""Redact CDP endpoint credentials from an exception's (or URL's) string form.
@@ -351,7 +357,7 @@ class CDPSupervisor(DialogSupervisionMixin, FrameTrackingMixin):
socket whenever a short-lived client (agent-browser's per-command CDP client)
disconnects, so on drop we reset per-session ids, re-attach, and keep going.
A failure before the first successful attach is fatal for ``start()``."""
- attempt, last_success_at, backoff = 0, 0.0, 0.5
+ reconnect_failures, last_success_at, backoff = 0, 0.0, 0.5
import websockets # deferred: only supervisors that connect pay the import
from agent.proxy_bypass import loopback_connect_kwargs
connect_kwargs = {"max_size": 50 * 1024 * 1024, **loopback_connect_kwargs(self.cdp_url)}
@@ -359,11 +365,16 @@ class CDPSupervisor(DialogSupervisionMixin, FrameTrackingMixin):
try:
self._ws = await asyncio.wait_for(websockets.connect(self.cdp_url, **connect_kwargs), timeout=10.0)
except Exception as e:
- attempt += 1
if self._fail_start(e):
return
- logger.warning("CDP supervisor %s: connect failed (attempt %s): %s",
- self.task_id, attempt, _redact_cdp_error_text(e))
+ reconnect_failures += 1
+ if reconnect_failures >= MAX_POST_ATTACH_RECONNECT_FAILURES:
+ logger.warning("CDP supervisor %s: stopped after %s failed reconnect attempts: %s",
+ self.task_id, reconnect_failures, _redact_cdp_error_text(e))
+ return
+ logger.warning("CDP supervisor %s: connect failed (attempt %s/%s): %s",
+ self.task_id, reconnect_failures, MAX_POST_ATTACH_RECONNECT_FAILURES,
+ _redact_cdp_error_text(e))
await asyncio.sleep(min(backoff, 10.0))
backoff = min(backoff * 2, 10.0)
continue
@@ -377,14 +388,21 @@ class CDPSupervisor(DialogSupervisionMixin, FrameTrackingMixin):
await self._attach_initial_page()
self._set_active(True)
last_success_at = time.time()
+ reconnect_failures = 0
backoff = 0.5 # reset after a successful attach
self._ready_event.set()
await reader_task
except BaseException as e:
if self._fail_start(e):
raise
- logger.warning("CDP supervisor %s: session dropped after %.1fs: %s",
- self.task_id, time.time() - last_success_at, _redact_cdp_error_text(e))
+ reconnect_failures += 1
+ if reconnect_failures >= MAX_POST_ATTACH_RECONNECT_FAILURES:
+ logger.warning("CDP supervisor %s: stopped after %s failed reconnect attempts: %s",
+ self.task_id, reconnect_failures, _redact_cdp_error_text(e))
+ return
+ logger.warning("CDP supervisor %s: session dropped after %.1fs (attempt %s/%s): %s",
+ self.task_id, time.time() - last_success_at, reconnect_failures,
+ MAX_POST_ATTACH_RECONNECT_FAILURES, _redact_cdp_error_text(e))
finally:
self._set_active(False)
if not reader_task.done():