Skip to content

The agent that grows with you

fix(browser): key the real-profile browser per profile home

Tekniumbd1a7c390f1b
diff --git a/tests/tools/test_browser_orphan_reaper.py b/tests/tools/test_browser_orphan_reaper.py
index a1479f586a8..9879189232a 100644
--- a/tests/tools/test_browser_orphan_reaper.py
+++ b/tests/tools/test_browser_orphan_reaper.py
@@ -60,10 +60,8 @@ class TestReapOrphanedBrowserSessions:
"""#100855: the shared real-profile browser is not ``<prefix>_<hex>`` named, so it must still be
found. Same owner-liveness rule as every other lane: dead owner => reaped. Its persistent
profile copy is never deleted by the reap."""
- from tools.browser_session_real_profile import REAL_PROFILE_KEY
-
- copy_dir = tmp_path / REAL_PROFILE_KEY
- copy_dir.mkdir()
+ copy_dir = tmp_path / "browser-profile" / "chrome"
+ copy_dir.mkdir(parents=True)
rec = _record(records, pid=4242, udd=str(copy_dir), ephemeral=False)
monkeypatch.setattr(launcher, "_pid_alive", _alive(4242)) # browser alive, owning hermes gone
monkeypatch.setattr(launcher, "_start_time", lambda pid: 777)
diff --git a/tests/tools/test_browser_profile_scope_edges.py b/tests/tools/test_browser_profile_scope_edges.py
index a9de8e38c99..0115c9b5c64 100644
--- a/tests/tools/test_browser_profile_scope_edges.py
+++ b/tests/tools/test_browser_profile_scope_edges.py
@@ -441,3 +441,78 @@ def test_a_connect_that_lands_while_browser_exec_spawns_its_daemon_reloads_it(pr
assert connects[0]["result"]["connected"]
nxt = json.loads(bu_cli.browser_exec("print(1)", task_id="t1"))
assert nxt["output"] == "http://127.0.0.1:9712"
+
+
+# --- real-profile browser per profile home (one process, many profiles) -----------------------------
+
+def real_profile_launches(tmp_path, monkeypatch):
+ """Session + launcher registries isolated; the real-profile and fresh launches register a fake browser
+ under whatever key the session layer asks for (what the launcher does), and every stop is recorded."""
+ import os
+ from tools import browser_launcher as launcher, browser_lightpanda, browser_session as bs
+ from tools import browser_session_lifecycle as lifecycle
+ from tools.bot_desktop import placement, runtime
+ import hermes_cli.browser_connect as bc
+ for name in ("_active_sessions", "_session_last_activity", "_session_owner_homes", "_cleanup_failures"):
+ monkeypatch.setattr(bs, name, {})
+ monkeypatch.setattr(lifecycle, "start_cleanup_thread", lambda: None)
+ monkeypatch.setattr(launcher, "_browsers", {})
+ monkeypatch.setattr(runtime, "tool_placement", lambda: placement.GATEWAY)
+ monkeypatch.setattr(bs, "ensure_screen_for_headed_chromium", lambda: None)
+ monkeypatch.setattr(browser_lightpanda, "using_lightpanda_engine", lambda: False)
+ monkeypatch.setattr(bc, "detect_default_chromium", lambda system=None: "chrome")
+ monkeypatch.setattr(bc, "chromium_executable", lambda name, system=None: "/usr/bin/chrome")
+ monkeypatch.setattr(bc, "snapshot_real_profile", lambda name: (str(get_hermes_home() / "rp-copy"), None))
+ stopped = []
+ monkeypatch.setattr(launcher, "_terminate", lambda pid, start_time, proc: stopped.append(pid))
+
+ def launch(key, **kw):
+ port = 9500 + len(launcher._browsers)
+ browser = launcher.LaunchedBrowser(
+ key=key, pid=os.getpid(), start_time=None, cdp_url=f"ws://127.0.0.1:{port}/devtools/browser/{port}",
+ http_url=f"http://127.0.0.1:{port}", user_data_dir=kw.get("user_data_dir") or str(tmp_path / key),
+ owned=True, ephemeral=False, home_key=hermes_home_key())
+ launcher._browsers[key] = browser
+ return browser, None
+ monkeypatch.setattr(launcher, "launch_chromium", launch)
+ return stopped
+
+
+def _consent(home, on: bool) -> None:
+ (home / "config.yaml").write_text(f"browser:\n cloud_provider: local\n use_real_profile: {'true' if on else 'false'}\n",
+ encoding="utf-8")
+
+
+def test_a_consent_off_profile_never_stops_another_profiles_real_profile_browser(profiles, real_profile_launches):
+ """Profile B (consent off, the default) creating a local session revokes only ITS real-profile browser;
+ profile A's keeps serving A's session."""
+ from tools import browser_session as bs
+ a, b = profiles
+ _consent(a, True)
+ _consent(b, False)
+ with _profile_runtime_scope(a, hydrate_secrets=False):
+ info_a = bs.get_session_info("task@a")
+ assert info_a["features"].get("real_profile")
+ with _profile_runtime_scope(b, hydrate_secrets=False):
+ info_b = bs.get_session_info("task@b")
+ assert not info_b["features"].get("real_profile")
+
+ assert real_profile_launches == [], "B's consent-off must not terminate A's real-profile browser"
+ with _profile_runtime_scope(a, hydrate_secrets=False):
+ assert bs._backend_dead(info_a) is False
+ assert bs.get_session_info("task@a")["cdp_url"] == info_a["cdp_url"]
+
+
+def test_a_consenting_profile_never_reuses_another_profiles_real_profile_browser(profiles, real_profile_launches):
+ """Two consenting profiles each get their own real-profile browser (their own snapshot, their own cookies)."""
+ from tools.browser_session_real_profile import real_profile_cdp
+ a, b = profiles
+ _consent(a, True)
+ _consent(b, True)
+ with _profile_runtime_scope(a, hydrate_secrets=False):
+ cdp_a, err_a = real_profile_cdp()
+ with _profile_runtime_scope(b, hydrate_secrets=False):
+ cdp_b, err_b = real_profile_cdp()
+ assert err_a is None and err_b is None
+ assert cdp_a != cdp_b
diff --git a/tests/tools/test_browser_real_profile.py b/tests/tools/test_browser_real_profile.py
index 3b174c2a8b3..c0f01adf575 100644
--- a/tests/tools/test_browser_real_profile.py
+++ b/tests/tools/test_browser_real_profile.py
@@ -285,7 +285,7 @@ class TestRealProfileCdpLaunch:
assert "--password-store=basic" not in argv and "--use-mock-keychain" not in argv
assert not set(launcher.CHROMIUM_SANDBOX_BYPASS_ARGS) & set(argv)
assert (copy_dir / "Default" / "Cookies").read_text(encoding="utf-8") == "copied-cookies"
- running = launcher.get_browser(rp.REAL_PROFILE_KEY)
+ running = launcher.get_browser(rp.real_profile_key())
assert running is not None and running.owned and not running.ephemeral
@pytest.mark.platforms("posix")
@@ -309,7 +309,7 @@ class TestRealProfileCdpLaunch:
if live_browser_id == "/devtools/browser/x":
assert (cdp, err) == ("ws://127.0.0.1:41000/devtools/browser/x", None)
snapshot.assert_not_called()
- attached = launcher.get_browser(rp.REAL_PROFILE_KEY)
+ attached = launcher.get_browser(rp.real_profile_key())
assert attached is not None and attached.owned is False
else:
snapshot.assert_called_once()
@@ -899,8 +899,8 @@ class TestReviewRound3:
"""When the live real-profile browser on our copy dir is reused, snapshot_real_profile
must NOT be called — otherwise it rewrites cookie DBs under a live
browser."""
- launcher._browsers[rp.REAL_PROFILE_KEY] = launcher.LaunchedBrowser(
- key=rp.REAL_PROFILE_KEY, pid=os.getpid(), start_time=None,
+ launcher._browsers[rp.real_profile_key()] = launcher.LaunchedBrowser(
+ key=rp.real_profile_key(), pid=os.getpid(), start_time=None,
cdp_url="ws://127.0.0.1:9251/devtools/browser/rp", http_url="http://127.0.0.1:9251",
user_data_dir=str(tmp_path), owned=False, ephemeral=False, home_key="h")
with patch.object(bs_cloud, "use_real_profile", return_value=True), \
diff --git a/tools/browser_session.py b/tools/browser_session.py
index 99961f1c081..e65600746ae 100644
--- a/tools/browser_session.py
+++ b/tools/browser_session.py
@@ -236,13 +236,14 @@ def _create_local_session(cache_key: str, allow_real_profile: bool = True) -> di
reach an arbitrary internal host the model chose."""
fallback_note = None
if allow_real_profile:
- from tools.browser_session_real_profile import real_profile_cdp, real_profile_fallback_note
+ from tools.browser_session_real_profile import real_profile_cdp, real_profile_fallback_note, real_profile_key
cdp_url, err = real_profile_cdp()
if err:
logger.warning("real-profile unavailable for %s, using a fresh browser: %s", cache_key, err)
fallback_note = real_profile_fallback_note(err)
elif cdp_url:
info = _session_record("rp", cdp_url, {"local": True, "real_profile": True})
+ info.update(launcher_key=real_profile_key(), shared_profile=True)
logger.info("Created real-profile local session %s for %s", info["session_name"], cache_key)
return info
from tools.browser_lightpanda import using_lightpanda_engine
@@ -306,8 +307,7 @@ def _backend_dead(session_info: dict[str, Any]) -> bool:
if features.get("sandbox"):
from tools.browser_session_sandbox import sandbox_browser_alive
return not sandbox_browser_alive(session_info)
- launcher_key = session_info.get("launcher_key") or (
- "hermes-real-profile" if features.get("real_profile") else None)
+ launcher_key = session_info.get("launcher_key")
if launcher_key:
from tools.browser_launcher import get_browser
browser = get_browser(launcher_key)
diff --git a/tools/browser_session_lifecycle.py b/tools/browser_session_lifecycle.py
index 12f5df61691..68b05e8a9e5 100644
--- a/tools/browser_session_lifecycle.py
+++ b/tools/browser_session_lifecycle.py
@@ -5,7 +5,7 @@ Teardown per session kind (CDP supervisor stopped first, so our WebSocket closes
cloud → ``provider.close_session``; Lightpanda → ``stop_lightpanda``; launcher Chromium → ``stop_browser``
(a shared persistent profile only once no other session uses it); sandbox → SIGTERM inside the sandbox
once no other session uses it;
-real profile → shared, terminated at exit / consent-off; CDP override → nothing (the user's browser).
+real profile → shared per profile home, terminated at exit / on that profile's consent-off; CDP override → nothing (the user's browser).
"""
from __future__ import annotations
@@ -139,7 +139,7 @@ def release_session_backend(cache_key: str, session_info: dict[str, Any]) -> Non
if features.get("sandbox"):
from tools.browser_session_sandbox import stop_sandbox_browser
stop_sandbox_browser(session_info)
- else:
+ elif not features.get("real_profile"): # outlives its sessions: stopped at exit / on consent-off
from tools.browser_launcher import stop_browser
stop_browser(launcher_key)
diff --git a/tools/browser_session_real_profile.py b/tools/browser_session_real_profile.py
index f986c5ec242..2ddfea5b957 100644
--- a/tools/browser_session_real_profile.py
+++ b/tools/browser_session_real_profile.py
@@ -3,8 +3,8 @@ launch the user's REAL browser binary on it through the launcher.
The real binary (not the packaged Chromium, and never ``--password-store=basic``/``--use-mock-keychain``)
keeps the OS keychain path intact, so macOS cookies decrypt and the copy stays signed in. One shared
-browser serves every session (concurrent tasks must not launch rival Chromiums on one copy dir); it is
-terminated at exit or when consent is turned off.
+browser per profile home serves every session of that profile (concurrent tasks must not launch rival
+Chromiums on one copy dir); it is terminated at exit or when THAT profile turns consent off.
"""
from __future__ import annotations
@@ -15,7 +15,6 @@ from typing import Optional
logger = logging.getLogger(__name__)
-REAL_PROFILE_KEY = "hermes-real-profile"
_RP = "browser.use_real_profile is on, but "
# Keep lock contention well inside the agent's 420-second outer tool deadline (an abandoned holder
# may be a daemon worker Python cannot terminate).
@@ -57,10 +56,17 @@ def _snapshot_error(err: str) -> str:
return f"{_RP}{err}"
+def real_profile_key() -> str:
+ """Launcher key of the CURRENT profile's real-profile browser. Per home: one process serves many profiles,
+ so a consent-off profile must never stop another's browser, nor a consenting one reuse its cookie jar."""
+ from hermes_constants import hermes_home_key
+ return f"hermes-real-profile@{hermes_home_key()}"
+
+
def terminate_real_profile_browser() -> None:
- """Stop the shared real-profile browser if this process launched it (idempotent, atexit-safe)."""
+ """Stop this profile's real-profile browser if this process launched it (idempotent)."""
from tools.browser_launcher import stop_browser
- stop_browser(REAL_PROFILE_KEY)
+ stop_browser(real_profile_key())
def _consent_revoked() -> tuple[None, None]:
@@ -90,7 +96,7 @@ def _launch(browser_name: str) -> tuple[Optional[str], Optional[str]]:
if real_binary is None:
return None, f"{_RP}the real browser binary for '{browser_name}' could not be found. Reinstall it or turn the toggle off."
ensure_screen_for_headed_chromium()
- launched, err = launch_chromium(REAL_PROFILE_KEY, executable=real_binary, user_data_dir=copy_dir,
+ launched, err = launch_chromium(real_profile_key(), executable=real_binary, user_data_dir=copy_dir,
ephemeral=False, extra_args=_REAL_PROFILE_EXTRA_FLAGS, timeout=30.0,
sandbox_bypass=False)
if launched is None:
@@ -119,7 +125,7 @@ def real_profile_cdp() -> tuple[Optional[str], Optional[str]]:
"finished. Retry after that call completes, or restart Hermes if it was abandoned.")
try:
from tools.browser_launcher import get_browser
- running = get_browser(REAL_PROFILE_KEY)
+ running = get_browser(real_profile_key())
if running is not None:
return running.cdp_url, None
from hermes_cli.browser_connect import detect_default_chromium