Skip to content

The agent that grows with you

fix(browser): gave-up supervisor unregisters itself; tests trimmed to two invariants

teknium1aefa50347971
diff --git a/tests/tools/test_browser_supervisor.py b/tests/tools/test_browser_supervisor.py
index 4c551308d16..6e56cc69e67 100644
--- a/tests/tools/test_browser_supervisor.py
+++ b/tests/tools/test_browser_supervisor.py
@@ -40,10 +40,17 @@ import time
import pytest
-_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",
-)
+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",
+ ),
+]
def _find_chrome() -> str:
@@ -212,8 +219,6 @@ 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
@@ -232,8 +237,6 @@ 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
@@ -253,8 +256,6 @@ 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
@@ -272,8 +273,6 @@ 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
@@ -294,8 +293,6 @@ 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
@@ -312,8 +309,6 @@ 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.
@@ -345,8 +340,6 @@ 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
@@ -358,97 +351,3 @@ 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/tests/tools/test_browser_supervisor_reconnect.py b/tests/tools/test_browser_supervisor_reconnect.py
new file mode 100644
index 00000000000..00c73e1e284
--- /dev/null
+++ b/tests/tools/test_browser_supervisor_reconnect.py
@@ -0,0 +1,81 @@
+"""CDPSupervisor reconnect budget: a supervisor that attached once must not retry a dead
+endpoint forever (#114172). No real Chrome — ``websockets.connect`` is stubbed."""
+
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+import websockets
+
+from tools import browser_supervisor as bs
+
+
+class _ClosingWebSocket:
+ async def close(self):
+ pass
+
+
+def unregister():
+ task_ids: list[str] = []
+ yield task_ids
+ for task_id in task_ids:
+ bs.SUPERVISOR_REGISTRY._pop(task_id)
+
+
+def test_post_attach_reconnects_stop_at_budget_and_unregister(monkeypatch, unregister, caplog):
+ """After the first attach, a dead endpoint gets MAX_POST_ATTACH_RECONNECT_FAILURES dials,
+ one final warning, and the supervisor leaves the registry — never an unbounded loop."""
+ supervisor = bs.CDPSupervisor(task_id="bounded-reconnect", cdp_url="ws://127.0.0.1:9222")
+ bs.SUPERVISOR_REGISTRY._by_task[supervisor.task_id] = supervisor
+ unregister.append(supervisor.task_id)
+ budget = bs.MAX_POST_ATTACH_RECONNECT_FAILURES
+ dials = 0
+
+ async def connect(*_args, **_kwargs):
+ nonlocal dials
+ dials += 1
+ if dials == 1:
+ return _ClosingWebSocket()
+ if dials <= budget + 1:
+ raise ConnectionError("CDP endpoint is gone")
+ await asyncio.Event().wait() # would hang forever: the loop must never get here
+
+ async def _noop(*_a, **_k):
+ pass
+
+ real_sleep = asyncio.sleep
+
+ async def fast_sleep(_delay):
+ await real_sleep(0) # yield so wait_for's deadline can fire on an unbounded loop
+
+ monkeypatch.setattr(websockets, "connect", connect)
+ monkeypatch.setattr(supervisor, "_attach_initial_page", _noop)
+ monkeypatch.setattr(supervisor, "_read_loop", _noop)
+ monkeypatch.setattr(bs.asyncio, "sleep", fast_sleep)
+
+ with caplog.at_level("WARNING", logger="tools.browser_supervisor"):
+ asyncio.run(asyncio.wait_for(supervisor._run(), timeout=2.0))
+
+ assert dials == budget + 1 # attach + budgeted reconnects
+ final = [r.getMessage() for r in caplog.records if "stopped after" in r.getMessage()]
+ assert len(final) == 1 and f"{budget} failed reconnect" in final[0]
+ assert supervisor.snapshot().active is False
+ assert bs.SUPERVISOR_REGISTRY.get(supervisor.task_id) is None
+
+
+def test_initial_connect_failure_stays_fatal_for_start(monkeypatch):
+ """The budget is post-attach only: a first-dial failure still propagates to ``start()``."""
+ 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")
+
+ 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 8b3d720967e..46f4c77b46c 100644
--- a/tools/browser_supervisor.py
+++ b/tools/browser_supervisor.py
@@ -352,6 +352,19 @@ class CDPSupervisor(DialogSupervisionMixin, FrameTrackingMixin):
with contextlib.suppress(Exception):
await ws.close()
+ def _reconnect_budget_spent(self, failures: int, e: BaseException) -> bool:
+ """True once ``failures`` consecutive post-attach reconnects failed: log ONE final line
+ and drop this supervisor from the registry so a dead endpoint (its Chrome exited with
+ the task) leaves neither a retrying thread nor a stale registry entry behind. A later
+ browser call for the task starts a fresh supervisor via ``get_or_start``."""
+ if failures < MAX_POST_ATTACH_RECONNECT_FAILURES:
+ return False
+ logger.warning("CDP supervisor %s: stopped after %s failed reconnect attempts: %s",
+ self.task_id, failures, _redact_cdp_error_text(e))
+ if SUPERVISOR_REGISTRY.get(self.task_id) is self:
+ SUPERVISOR_REGISTRY._pop(self.task_id)
+ return True
+
async def _run(self) -> None:
"""Top-level reconnecting supervisor coroutine. Browserbase tears down the CDP
socket whenever a short-lived client (agent-browser's per-command CDP client)
@@ -368,9 +381,7 @@ class CDPSupervisor(DialogSupervisionMixin, FrameTrackingMixin):
if self._fail_start(e):
return
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))
+ if self._reconnect_budget_spent(reconnect_failures, e):
return
logger.warning("CDP supervisor %s: connect failed (attempt %s/%s): %s",
self.task_id, reconnect_failures, MAX_POST_ATTACH_RECONNECT_FAILURES,
@@ -396,9 +407,7 @@ class CDPSupervisor(DialogSupervisionMixin, FrameTrackingMixin):
if self._fail_start(e):
raise
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))
+ if self._reconnect_budget_spent(reconnect_failures, 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,
diff --git a/website/docs/developer-guide/browser-supervisor.md b/website/docs/developer-guide/browser-supervisor.md
index a30abdbdaca..44a7823704c 100644
--- a/website/docs/developer-guide/browser-supervisor.md
+++ b/website/docs/developer-guide/browser-supervisor.md
@@ -73,6 +73,11 @@ frozen snapshot without awaiting.
Idempotent.
- **Stop:** session teardown or `/browser disconnect`. Cancels the asyncio
task, closes the WebSocket, discards state.
+- **Dropped endpoint:** after a successful attach the supervisor reconnects with
+ backoff (≤10 s) but gives up after `MAX_POST_ATTACH_RECONNECT_FAILURES`
+ consecutive failures — one final warning, the thread exits and the registry
+ entry is dropped. A dead local Chrome (its task finished) therefore never leaves
+ a retrying thread behind; the next browser call starts a fresh supervisor.
- **Rebind:** if the CDP URL changes (user reconnects to a new Chrome), the
old supervisor is stopped and a fresh one started — state is never reused
across endpoints.