The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(browser): a session found stale after creation is closed by object, never published
Teknium71f009b5e2ca
diff --git a/tests/tools/test_browser_profile_scope_edges.py b/tests/tools/test_browser_profile_scope_edges.pyindex ce595637fd6..413a5904630 100644--- a/tests/tools/test_browser_profile_scope_edges.py+++ b/tests/tools/test_browser_profile_scope_edges.py@@ -258,9 +258,9 @@ def test_a_session_that_resolved_the_old_endpoint_during_a_connect_is_closed_notmonkeypatch.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")))+ closed = [] # released by object: the stale session is never in ``sessions``+ monkeypatch.setattr(lifecycle, "_release_session_backend", lambda task_id, info: closed.append(info["cdp_url"]))+ monkeypatch.setattr(bt_session, "_browser_command_preflight", lambda: {"error": "no CLI in this test"})created = []def create(task_id, local):@@ -279,6 +279,48 @@ def test_a_session_that_resolved_the_old_endpoint_during_a_connect_is_closed_notassert closed == ["http://127.0.0.1:9501"]+def test_a_stale_session_is_closed_without_ever_being_handed_to_a_concurrent_caller(profiles, monkeypatch):+ """A session found stale after creation is closed by object, never published first: while its+ backend ``close`` runs, a concurrent ``_get_session_info`` for the same key must not find it in+ ``_active_sessions`` (it would return a browser that is being closed underneath it)."""+ from tools import browser_tool, browser_tool_lifecycle as lifecycle, browser_tool_session as bt_session+ from tui_gateway import server++ 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(bt_cdp, "_stop_cdp_supervisor", lambda key: None)+ monkeypatch.setattr(server, "_cdp_http_reachable", lambda parsed, timeout=2.0: True)+ monkeypatch.setattr(bt_session, "_browser_command_preflight", lambda: {"browser_cmd": "agent-browser"})+ visible_during_close = []++ def dispatch(task_id, info, browser_cmd, command, args, timeout, engine):+ if command == "close": # what the existing-session path would hand a concurrent caller now+ visible_during_close.append((info["cdp_url"], (sessions.get(task_id) or {}).get("cdp_url")))+ return "chrome", {"success": True}+ monkeypatch.setattr(bt_session, "_dispatch_browser_command", dispatch)+ released = []+ monkeypatch.setattr(lifecycle, "_release_session_backend", lambda task_id, info: released.append(info["cdp_url"]))+ created = []++ def create(task_id, local):+ url = bt_cdp._get_cdp_override_raw()+ if not created:+ assert server._browser_connect("r1", {"url": "http://127.0.0.1:9512"})["result"]["connected"]+ created.append(url)+ return {"session_name": f"s{len(created)}", "cdp_url": url, "bb_session_id": None}+ 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:9511")+ info = bt_session._get_session_info("task-a")+ assert visible_during_close == [("http://127.0.0.1:9511", None)]+ assert released == ["http://127.0.0.1:9511"]+ assert info["cdp_url"] == "http://127.0.0.1:9512" and sessions["task-a"] is info++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_sessiona, b = profilesdiff --git a/tools/browser_tool_lifecycle.py b/tools/browser_tool_lifecycle.pyindex 11fb9569ca1..098c182d209 100644--- a/tools/browser_tool_lifecycle.py+++ b/tools/browser_tool_lifecycle.py@@ -660,15 +660,20 @@ def _release_session_resources(task_id: str, session_info: dict[str, Any]) -> Noforce-reap path (#100738), which skips the polite agent-browser/Camofox ``close`` that kept failing butmust still release the cloud session and the local Chromium."""- bb_session_id = session_info.get("bb_session_id", "unknown")_forget_session_tracking(task_id, session=True)+ _release_session_backend(task_id, session_info)++def _release_session_backend(task_id: str, session_info: dict[str, Any]) -> None:+ """Close ``session_info``'s cloud provider session and kill its daemon, by object: no shared+ session map is read or written (an unpublished session releases through this alone)."""+ bb_session_id = session_info.get("bb_session_id", "unknown")if bb_session_id: # cloud only — local sidecars have bb_session_id=Noneprovider = _cloud._get_cloud_provider()if provider is not None:try:provider.close_session(bb_session_id)- except Exception as e:+ except Exception as e: # health: allow BLE001 -- teardown boundary moved unchanged from _release_session_resources; a provider error must never abort the daemon kill below_bt.logger.warning("Could not close cloud browser session: %s", e)session_name = session_info.get("session_name", "")diff --git a/tools/browser_tool_session.py b/tools/browser_tool_session.pyindex 1623c768613..745c57d98e2 100644--- a/tools/browser_tool_session.py+++ b/tools/browser_tool_session.py@@ -425,25 +425,20 @@ def _get_session_info(task_id: Optional[str] = None) -> dict[str, Any]:with _bt._cleanup_lock:if task_id in _bt._active_sessions: # created concurrently during the network call — don't leak oursreturn _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+ # 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. Never publish it (a concurrent+ # caller would be handed a browser being closed); close it by object and build again.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.+ if not stale or attempt == _STALE_ENDPOINT_RETRIES:+ 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+ break_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)+ _close_unpublished_session(task_id, session_info)# 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).@@ -453,6 +448,20 @@ def _get_session_info(task_id: Optional[str] = None) -> dict[str, Any]:return session_info+def _close_unpublished_session(task_id: str, session_info: dict[str, Any]) -> None:+ """Close a session that was never put in ``_active_sessions``, by object: its backend ``close``+ and resources only, never a lookup by key (that entry, if any, is another caller's session)."""+ if (session_info.get("features") or {}).get("lightpanda"): # no daemon to ``close``+ from tools.browser_lightpanda import stop_lightpanda+ stop_lightpanda(session_info.get("session_name", ""))+ else:+ preflight = _browser_command_preflight()+ if "browser_cmd" in preflight:+ run_fenced_pair(session_info, lambda: _dispatch_browser_command(+ task_id, session_info, preflight["browser_cmd"], "close", [], 10, None))+ _lifecycle._release_session_backend(task_id, session_info)++def _discard_timed_out_browser_session(task_id: str, session_info: dict[str, Any], task_socket_dir: str) -> None:"""Drop a stuck client generation without losing cloud cleanup state."""with _bt._cleanup_lock: