The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(browser): a paused shared browser is waited for and refused, never launched over
Teknium5be06073927d
diff --git a/tests/tools/test_browser_launcher_unresponsive.py b/tests/tools/test_browser_launcher_unresponsive.pynew file mode 100644index 00000000000..c2fe3eb1bdf--- /dev/null+++ b/tests/tools/test_browser_launcher_unresponsive.py@@ -0,0 +1,60 @@+"""A live browser whose DevTools endpoint stops answering for a while is still the profile's browser.++Chromium paused (SIGSTOP, a debugger, a swapped-out host) keeps its profile singleton; a second launch on the+profile would only wipe the live browser's ``DevToolsActivePort`` and lose it for every later attach (its+singleton refuses the next launch with "SingletonLock exists"). The launcher waits for the live holder and then+refuses with a clear error, leaving its profile untouched (``tools/browser_launcher.py``). Runs the real launcher+against a fake Chromium that takes the profile singleton and serves ``/json/version`` like the real one.+"""++from __future__ import annotations++import os+import signal+import subprocess++import pytest++from tests.tools.browser_launcher_fakes import kill_fake, pids, write_fake_chromium+from tests.waiting import wait_until+from tools import browser_launcher as launcher++pytestmark = [pytest.mark.platforms("linux"),+ pytest.mark.live_system_guard_bypass] # the fake browser is ours to stop if a leg failed+++def _start_fake(script, udd) -> subprocess.Popen:+ proc = subprocess.Popen([str(script), "--remote-debugging-port=0", f"--user-data-dir={udd}"],+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+ assert wait_until(lambda: (udd / "DevToolsActivePort").exists(), timeout=15, what="the fake to come up")+ return proc+++def test_a_paused_shared_browser_is_refused_then_attached_once_it_answers_again(tmp_path):+ script = write_fake_chromium(tmp_path / "chromium")+ udd = tmp_path / "pinned-profile"+ browser = _start_fake(script, udd)+ port_file = (udd / "DevToolsActivePort").read_text()+ key = f"profile:{udd}"++ def attach():+ return launcher.launch_chromium(key, executable=str(script), user_data_dir=str(udd), ephemeral=False,+ headed=False, env=dict(os.environ), timeout=3)++ try:+ os.kill(browser.pid, signal.SIGSTOP)+ try:+ attached, err = attach()+ finally:+ os.kill(browser.pid, signal.SIGCONT)+ assert attached is None and err and str(browser.pid) in err, err+ assert (udd / "DevToolsActivePort").read_text() == port_file, "the live browser's endpoint file was wiped"+ assert pids(udd, "spawns") == [browser.pid], "a second Chromium was started on the live browser's profile"++ attached, err = attach()+ assert err is None and attached.pid == browser.pid and not attached.owned, err+ launcher.stop_browser(key)+ finally:+ for pid in pids(udd, "spawns"):+ kill_fake(pid, script)+ browser.wait(timeout=10)diff --git a/tests/tools/test_browser_real_profile.py b/tests/tools/test_browser_real_profile.pyindex 9376b20b39f..7506a4bd2af 100644--- a/tests/tools/test_browser_real_profile.py+++ b/tests/tools/test_browser_real_profile.py@@ -324,6 +324,9 @@ class TestRealProfileCdpLaunch:(tmp_path / "DevToolsActivePort").write_text("41000\n/devtools/browser/x\n", encoding="utf-8")chrome = subprocess.Popen([*_SLEEPER, f"--user-data-dir={tmp_path}"]) # the survivor holding the diros.symlink(f"{socket.gethostname()}-{chrome.pid}", tmp_path / "SingletonLock")+ if live_browser_id != "/devtools/browser/x": # the crash case: the dir's browser is gone, its lock stale+ chrome.kill()+ chrome.wait(timeout=30)version = Mock()version.json.return_value = {"webSocketDebuggerUrl": f"ws://127.0.0.1:41000{live_browser_id}"}try:diff --git a/tools/browser_launcher.py b/tools/browser_launcher.pyindex f1254779fa0..b2f84ccda02 100644--- a/tools/browser_launcher.py+++ b/tools/browser_launcher.py@@ -59,6 +59,7 @@ _MACOS_PACKAGED_ONLY_FLAGS: tuple[str, ...] = ("--use-mock-keychain",)_DEVTOOLS_FILE = "DevToolsActivePort"_LAUNCH_LOG = "hermes-chromium.log"_MIN_FIRST_LAUNCH_TIMEOUT_S = 120+_UNRESPONSIVE_WAIT_S = 10 # how long a live browser whose endpoint went silent (paused, swapped out) is waited for_POLL_INTERVAL_S = 0.1_STDERR_TAIL_CHARS = 1500@@ -486,6 +487,35 @@ def _attach_foreign(key: str, user_data_dir: str, home_key: str, pid: int) -> Opreturn browser+def _live_local_holder(user_data_dir: str) -> Optional[int]:+ """Pid of the live Chromium of this environment holding ``user_data_dir`` (its ``SingletonLock`` names a live+ process whose argv carries the dir), else None: no browser, or a stale lock a launch may take over."""+ pid = _singleton_pid(user_data_dir)+ return pid if pid is not None and _pid_alive(pid) and _cmdline_names_dir(pid, user_data_dir) else None+++def _attach_local(key: str, user_data_dir: str, home_key: str,+ timeout: Optional[float]) -> tuple[Optional[LaunchedBrowser], Optional[str]]:+ """Attach to this environment's live Chromium on ``user_data_dir``; ``(None, None)`` when none holds it (a+ launch may start one). A live holder whose endpoint does not answer (paused, hung) is waited for, then+ refused: a launch over it would only wipe its ``DevToolsActivePort`` and lose it for every later attach."""+ attached = _attach_running(key, user_data_dir, home_key)+ pid = _live_local_holder(user_data_dir) if attached is None else None+ if pid is None:+ return attached, None+ deadline = time.monotonic() + min(_UNRESPONSIVE_WAIT_S, _launch_timeout(timeout))+ delay = 0.25+ while attached is None and _live_local_holder(user_data_dir) == pid:+ if time.monotonic() >= deadline:+ return None, (f"The browser profile {user_data_dir} is in use by Chromium pid {pid}, which is not "+ "responding on its DevTools endpoint (paused, hung, or started without remote debugging). "+ "Hermes will not start a second browser on it; try again once it responds, or stop it.")+ time.sleep(min(delay, max(0.0, deadline - time.monotonic())))+ delay *= 2+ attached = _attach_running(key, user_data_dir, home_key)+ return attached, None++def _foreign_unreachable(user_data_dir: str) -> str:return (f"The browser profile {user_data_dir} is in use by a Chromium in another environment (a container or ""the host) that this process can neither reach nor verify, so Hermes will not start a second browser "@@ -510,7 +540,9 @@ def _start_shared(key: str, executable: str, udd: str, home_key: str, prepare,if attached is None:return None, _foreign_unreachable(udd)else:- attached = _attach_running(key, udd, home_key)+ attached, refused = _attach_local(key, udd, home_key, launch.get("timeout"))+ if refused:+ return None, refusedif attached is None:failure = prepare() if prepare is not None else Noneif failure: