Skip to content

The agent that grows with you

fix(browser): a session that resolved the old endpoint during /browser connect is closed, not kept

Teknium37e36cda3220
diff --git a/tests/tools/test_browser_profile_scope_edges.py b/tests/tools/test_browser_profile_scope_edges.py
index 737fee293e3..8cfdbb66cb3 100644
--- a/tests/tools/test_browser_profile_scope_edges.py
+++ b/tests/tools/test_browser_profile_scope_edges.py
@@ -184,3 +184,60 @@ def test_an_unscoped_shutdown_reload_reaches_the_daemon_with_its_own_tmp_dir(pro
bu_cli.stop_harness_daemons()
assert [(e["BH_TMP_DIR"], e["BH_TMP_DIR_SHARED"], e["BU_NAME"]) for e in seen] == [
(env["BH_TMP_DIR"], "1", "s1")]
+
+
+# --- reap/publish race within one profile -----------------------------------------------------------
+
+
+def test_a_session_that_resolved_the_old_endpoint_during_a_connect_is_closed_not_kept(profiles, monkeypatch):
+ """``/browser connect`` reaps, publishes the new endpoint, then reaps again. A tool call that
+ resolved the OLD endpoint before the publish but inserted its session after the second reap kept
+ driving the old browser. The real ``_browser_connect`` handler runs mid-creation here."""
+ from tools import browser_tool, browser_tool_lifecycle as lifecycle, browser_tool_session as bt_session
+ from tui_gateway import server # binds methods_browser helpers onto server globals
+
+ a, _b = profiles
+ sessions = {}
+ monkeypatch.setattr(browser_tool, "_active_sessions", sessions)
+ monkeypatch.setattr(lifecycle, "_start_browser_cleanup_thread", lambda: None)
+ monkeypatch.setattr(bt_cdp, "_ensure_cdp_supervisor", lambda key: None)
+ monkeypatch.setattr(server, "_cdp_http_reachable", lambda parsed, timeout=2.0: True)
+ closed = []
+ monkeypatch.setattr(lifecycle, "_cleanup_single_browser_session",
+ lambda task_id: closed.append(sessions.pop(task_id, {}).get("cdp_url")))
+ created = []
+
+ def create(task_id, local):
+ url = bt_cdp._get_cdp_override_raw() # resolved before the connect publishes
+ if not created:
+ assert server._browser_connect("r1", {"url": "http://127.0.0.1:9502"})["result"]["connected"]
+ created.append(url)
+ return {"session_name": f"s{len(created)}", "cdp_url": url}
+ monkeypatch.setattr(bt_session, "_create_session_for_key", create)
+
+ with _profile_runtime_scope(a, hydrate_secrets=False):
+ bt_cdp.set_live_cdp_override("http://127.0.0.1:9501")
+ info = bt_session._get_session_info("task-a")
+ assert info["cdp_url"] == "http://127.0.0.1:9502"
+ assert sessions["task-a"] is info
+ assert closed == ["http://127.0.0.1:9501"]
+
+
+def test_another_profiles_connect_does_not_invalidate_this_profiles_new_session(profiles, monkeypatch):
+ from tools import browser_tool, browser_tool_lifecycle as lifecycle, browser_tool_session as bt_session
+ a, b = profiles
+ sessions = {}
+ monkeypatch.setattr(browser_tool, "_active_sessions", sessions)
+ monkeypatch.setattr(lifecycle, "_start_browser_cleanup_thread", lambda: None)
+ monkeypatch.setattr(bt_cdp, "_ensure_cdp_supervisor", lambda key: None)
+ closed = []
+ monkeypatch.setattr(lifecycle, "_cleanup_single_browser_session", closed.append)
+
+ def create(task_id, local):
+ with _profile_runtime_scope(b, hydrate_secrets=False):
+ bt_cdp.set_live_cdp_override("http://127.0.0.1:9601")
+ return {"session_name": "s", "cdp_url": "x"}
+ monkeypatch.setattr(bt_session, "_create_session_for_key", create)
+ with _profile_runtime_scope(a, hydrate_secrets=False):
+ info = bt_session._get_session_info("task-a")
+ assert sessions == {"task-a": info} and closed == []
diff --git a/tools/browser_tool_cdp.py b/tools/browser_tool_cdp.py
index 59c7bfd0b02..ff5126c37e8 100644
--- a/tools/browser_tool_cdp.py
+++ b/tools/browser_tool_cdp.py
@@ -70,7 +70,7 @@ def live_cdp_override() -> str:
def set_live_cdp_override(url: Optional[str]) -> None:
- """Set (or with a falsy ``url`` clear) the current profile's live endpoint."""
+ """Set (or with a falsy ``url`` clear) the current profile's live endpoint and bump its generation."""
from hermes_constants import hermes_home_key
key = hermes_home_key()
with _live_overrides_lock:
@@ -78,6 +78,20 @@ def set_live_cdp_override(url: Optional[str]) -> None:
_live_overrides[key] = url
else:
_live_overrides.pop(key, None)
+ _live_generations[key] = _live_generations.get(key, 0) + 1
+
+
+# Per-profile count of live-endpoint publishes. A browser session records the value it saw before
+# resolving its endpoint; ``_get_session_info`` closes one whose profile published in between (it may
+# have resolved the old URL after ``/browser connect``'s second reap had already run).
+_live_generations: dict[str, int] = {}
+
+
+def live_cdp_generation(home_key: Optional[str] = None) -> int:
+ """The current (or ``home_key``'s) profile's live-endpoint generation."""
+ from hermes_constants import hermes_home_key
+ with _live_overrides_lock:
+ return _live_generations.get(home_key or hermes_home_key(), 0)
def env_cdp_url() -> str:
diff --git a/tools/browser_tool_session.py b/tools/browser_tool_session.py
index 9ee13dfe0b5..1623c768613 100644
--- a/tools/browser_tool_session.py
+++ b/tools/browser_tool_session.py
@@ -374,6 +374,11 @@ def _create_session_for_key(task_id: str, force_local: bool) -> dict[str, Any]:
return _create_cloud_session_or_fallback(task_id, provider)
+# A session built while its profile published a new live endpoint is closed and rebuilt; bounded so a
+# flapping connect/disconnect loop cannot keep a tool call building browsers forever.
+_STALE_ENDPOINT_RETRIES = 2
+
+
def _get_session_info(task_id: Optional[str] = None) -> dict[str, Any]:
"""Get or create session info for a session key (thread-safe); also starts the
inactivity thread and touches activity. A ``::local`` key forces local Chromium
@@ -413,17 +418,32 @@ def _get_session_info(task_id: Optional[str] = None) -> dict[str, Any]:
return replacement
force_local = _bt._is_local_sidecar_key(task_id)
- session_info = _create_session_for_key(task_id, force_local)
-
- with _bt._cleanup_lock:
- if task_id in _bt._active_sessions: # created concurrently during the network call — don't leak ours
- return _bt._active_sessions[task_id]
- session_info = dict(session_info)
- session_info.setdefault("session_key", task_id)
- session_info.setdefault("owner_task_id", _bt._bare_task_id_for_session_key(task_id))
- session_info.setdefault("home_key", hermes_home_key()) # the profile reaped on /browser connect
- _bt._active_sessions[task_id] = session_info
- _bt._suspect_browser_sessions.pop(task_id, None) # brand-new session is healthy by definition
+ home_key = hermes_home_key()
+ for attempt in range(_STALE_ENDPOINT_RETRIES + 1):
+ generation = _cdp.live_cdp_generation(home_key)
+ session_info = _create_session_for_key(task_id, force_local)
+ with _bt._cleanup_lock:
+ if task_id in _bt._active_sessions: # created concurrently during the network call — don't leak ours
+ return _bt._active_sessions[task_id]
+ session_info = dict(session_info)
+ session_info.setdefault("session_key", task_id)
+ session_info.setdefault("owner_task_id", _bt._bare_task_id_for_session_key(task_id))
+ session_info.setdefault("home_key", home_key) # the profile reaped on /browser connect
+ _bt._active_sessions[task_id] = session_info
+ _bt._suspect_browser_sessions.pop(task_id, None) # brand-new session is healthy by definition
+ stale = _cdp.live_cdp_generation(home_key) != generation
+ if not stale or attempt == _STALE_ENDPOINT_RETRIES:
+ break
+ # This profile published a new live endpoint while ours was being created: it may have resolved
+ # the old one after /browser connect's second reap. Close it (registered, so the normal teardown
+ # finds it) and build again on the endpoint published now.
+ _bt.logger.info("Browser endpoint changed during session creation for %s; recreating", task_id)
+ with _bt._cleanup_lock:
+ current = _bt._active_sessions.get(task_id)
+ if current is not None and current is not session_info: # another thread already replaced it
+ return current
+ _lifecycle._cleanup_single_browser_session(task_id)
+ _lifecycle._update_session_activity(task_id)
# Lazy-start the CDP supervisor (idempotent). Skip local sidecars (no CDP URL) and
# Lightpanda sessions (Browser Use mode hides the tools that consume supervisor state).