Skip to content

The agent that grows with you

test(browser): launcher + served-profile session invariants

Teknium701771c100de
diff --git a/tests/tools/conftest.py b/tests/tools/conftest.py
index 796e3a9775e..9929ed86ed9 100644
--- a/tests/tools/conftest.py
+++ b/tests/tools/conftest.py
@@ -15,12 +15,11 @@ import pytest
@pytest.fixture(autouse=True)
def _no_host_browser_use_cli():
- """Keep the host's PM-managed browser-use install out of tests.
+ """Keep the host's browser-harness install out of tests.
- Browser Use mode is default-on when the CLI is runnable, so a developer
- machine with the CLI installed would silently flip every built-in-browser test
- into CLI mode. Pin discovery to "not installed"; tests that exercise the
- CLI path monkeypatch ``bu_cli._find_cli`` themselves.
+ browser_exec is advertised whenever browser-harness is importable, so a developer machine
+ would expose (and could spawn) the real harness in every tool-surface test. Pin discovery to
+ "not installed"; tests that exercise the CLI path monkeypatch ``bu_cli._find_cli`` themselves.
"""
try:
import tools.browser_use_cli as bu_cli
@@ -35,6 +34,19 @@ def _no_host_browser_use_cli():
yield
[email protected](autouse=True)
+def _no_chromium_download():
+ """A test that reaches the launcher without a fake binary must never start PM's ~170 MB Chromium
+ download; the one-shot auto-install is pinned to "declined"."""
+ try:
+ import tools.browser_launcher as launcher
+ except Exception:
+ yield
+ return
+ with patch.object(launcher, "_maybe_autoinstall_chromium", lambda: False):
+ yield
+
+
@pytest.fixture(autouse=True)
def _no_shared_temp_socket_dirs():
"""A served profile's over-budget harness runtime dir is moved to a private ``hbh-<hash>`` dir
diff --git a/tests/tools/test_browser_launcher.py b/tests/tools/test_browser_launcher.py
new file mode 100644
index 00000000000..e78bdc125b8
--- /dev/null
+++ b/tests/tools/test_browser_launcher.py
@@ -0,0 +1,212 @@
+"""Behaviour contracts of the Python Chromium launcher (tools/browser_launcher.py).
+
+A fake ``chromium`` (a Python script) stands in for the real binary: it writes ``DevToolsActivePort``
+into its ``--user-data-dir`` exactly like Chromium and records its argv, so every path through the
+launcher runs for real (spawn, readiness poll, registry, records, parent-first stop, orphan reap).
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import signal
+import subprocess
+import sys
+import textwrap
+import time
+from pathlib import Path
+
+import pytest
+
+from tools import browser_launcher as launcher
+
+_FAKE_CHROMIUM = textwrap.dedent('''\
+ #!{python}
+ import json, os, signal, subprocess, sys, time
+ udd = next(a.split("=", 1)[1] for a in sys.argv if a.startswith("--user-data-dir="))
+ os.makedirs(udd, exist_ok=True)
+ log = os.path.join(udd, "order.log")
+ with open(os.path.join(udd, "argv.json"), "w") as f:
+ json.dump(sys.argv, f)
+ # A helper child like Chromium's zygote: records when IT is told to stop.
+ child = subprocess.Popen([sys.executable, "-c",
+ "import os,signal,sys,time\\n"
+ "def h(*_):\\n"
+ " open(sys.argv[1],'a').write('child\\\\n'); sys.exit(0)\\n"
+ "signal.signal(signal.SIGTERM, h)\\n"
+ "parent = os.getppid()\\n"
+ "while os.getppid() == parent: time.sleep(0.1)\\n"
+ "time.sleep(5)\\n", log]) # outlives a SIGKILLed parent briefly, then exits (no leak)
+ def on_term(*_):
+ open(log, "a").write("parent\\n")
+ sys.exit(0) # leaves the child running, as a browser mid-shutdown would
+ signal.signal(signal.SIGTERM, on_term)
+ with open(os.path.join(udd, "DevToolsActivePort"), "w") as f:
+ f.write("45678\\n/devtools/browser/fake-id\\n")
+ time.sleep(600)
+''')
+
+
+def fake_chromium(tmp_path, monkeypatch):
+ script = tmp_path / "chromium"
+ script.write_text(_FAKE_CHROMIUM.format(python=sys.executable))
+ script.chmod(0o755)
+ monkeypatch.setattr(launcher, "_resolve_executable", lambda: str(script))
+ monkeypatch.setattr(launcher, "needs_chromium_sandbox_bypass", lambda: False)
+ records = tmp_path / "records"
+ records.mkdir()
+ monkeypatch.setattr(launcher, "_records_dir", lambda: records)
+ monkeypatch.setattr("tools.browser_session_cloud.chromium_args", list)
+ monkeypatch.setattr("tools.browser_session_cloud.is_headed_mode", lambda: False)
+ yield script
+ launcher.stop_all_browsers()
+
+
+def _argv(browser) -> list[str]:
+ return json.loads(Path(browser.user_data_dir, "argv.json").read_text())
+
+
[email protected]_system_guard_bypass # the fake browser's reparented helper is ours to stop
+def test_launch_reads_devtools_port_and_runs_headless_on_an_ephemeral_home_profile(fake_chromium):
+ browser, err = launcher.launch_chromium("task-a", env=dict(os.environ))
+ assert err is None
+ assert browser.cdp_url == "ws://127.0.0.1:45678/devtools/browser/fake-id"
+ assert browser.http_url == "http://127.0.0.1:45678"
+ assert browser.owned and browser.ephemeral
+ from hermes_constants import get_hermes_home
+ assert Path(browser.user_data_dir).parent == Path(get_hermes_home()) / "cache" / "browser" / "chromium"
+ argv = _argv(browser)
+ assert "--remote-debugging-port=0" in argv
+ assert f"--user-data-dir={browser.user_data_dir}" in argv
+ assert "--headless=new" in argv
+ assert argv[-1] == "about:blank"
+
+
[email protected]_system_guard_bypass # the fake browser's reparented helper is ours to stop
+def test_one_browser_per_key_and_separate_browsers_for_separate_keys(fake_chromium):
+ a1, _ = launcher.launch_chromium("named-a", env=dict(os.environ))
+ a2, _ = launcher.launch_chromium("named-a", env=dict(os.environ))
+ b, _ = launcher.launch_chromium("named-b", env=dict(os.environ))
+ assert a1.pid == a2.pid
+ assert b.pid != a1.pid
+ assert b.user_data_dir != a1.user_data_dir
+
+
[email protected]_system_guard_bypass # the fake browser's reparented helper is ours to stop
+def test_stop_signals_the_browser_before_its_helpers_and_removes_the_ephemeral_profile(fake_chromium):
+ browser, _ = launcher.launch_chromium("stop-me", env=dict(os.environ))
+ order_log = Path(browser.user_data_dir, "order.log")
+ snapshot = order_log.parent.parent / "order-snapshot.log"
+ # The profile dir is removed on stop; mirror the log before it goes.
+ real_rmtree = launcher.shutil.rmtree
+
+ def keep_log(path, *a, **k):
+ if Path(path) == Path(browser.user_data_dir) and order_log.exists():
+ snapshot.write_text(order_log.read_text())
+ return real_rmtree(path, *a, **k)
+
+ launcher.shutil.rmtree = keep_log
+ try:
+ launcher.stop_browser("stop-me")
+ finally:
+ launcher.shutil.rmtree = real_rmtree
+ assert snapshot.read_text().splitlines() == ["parent", "child"]
+ assert not Path(browser.user_data_dir).exists()
+ assert launcher.get_browser("stop-me") is None
+
+
[email protected]_system_guard_bypass # the fake browser's reparented helper is ours to stop
+def test_a_dead_browser_is_dropped_so_the_next_launch_starts_a_new_one(fake_chromium):
+ first, _ = launcher.launch_chromium("crashy", env=dict(os.environ))
+ os.kill(first.pid, signal.SIGKILL)
+ launcher._procs["crashy"].wait(timeout=5)
+ assert launcher.get_browser("crashy") is None
+ second, err = launcher.launch_chromium("crashy", env=dict(os.environ))
+ assert err is None and second.pid != first.pid
+
+
[email protected]_system_guard_bypass # the fake browser's reparented helper is ours to stop
+def test_launch_failure_reports_the_exit_and_leaves_nothing_registered(tmp_path, monkeypatch, fake_chromium):
+ broken = tmp_path / "broken-chromium"
+ broken.write_text(f"#!{sys.executable}\nimport sys\nsys.stderr.write('No usable sandbox!')\nsys.exit(7)\n")
+ broken.chmod(0o755)
+ browser, err = launcher.launch_chromium("broken", executable=str(broken), env=dict(os.environ), timeout=10)
+ assert browser is None
+ assert "exited with code 7" in err and "--no-sandbox" in err
+ assert launcher.get_browser("broken") is None
+
+
+def _write_orphan_record(records: Path, pid: int, udd: str) -> Path:
+ dead_owner = subprocess.Popen([sys.executable, "-c", "pass"])
+ dead_owner.wait()
+ path = records / f"orphan-{pid}.json"
+ path.write_text(json.dumps({"owner_pid": dead_owner.pid, "owner_start_time": None, "pid": pid,
+ "start_time": launcher._start_time(pid), "user_data_dir": udd,
+ "home_key": "x", "ephemeral": False}))
+ return path
+
+
[email protected]_system_guard_bypass # the fake browser's reparented helper is ours to stop
+def test_orphan_reap_refuses_a_pid_whose_cmdline_lacks_the_recorded_user_data_dir(tmp_path, fake_chromium):
+ stranger = subprocess.Popen(["sleep", "3001"])
+ try:
+ record = _write_orphan_record(launcher._records_dir(), stranger.pid, str(tmp_path / "some-profile"))
+ assert launcher.reap_orphaned_browsers() == 0
+ assert stranger.poll() is None # never signalled
+ assert not record.exists() # the stale record is dropped
+ finally:
+ stranger.kill()
+ stranger.wait()
+
+
[email protected]_system_guard_bypass # the fake browser's reparented helper is ours to stop
+def test_orphan_reap_stops_a_crashed_owners_browser(tmp_path, fake_chromium):
+ udd = tmp_path / "orphan-profile"
+ proc = subprocess.Popen([str(fake_chromium), f"--user-data-dir={udd}"], start_new_session=True)
+ deadline = time.monotonic() + 10
+ while not (udd / "DevToolsActivePort").exists() and time.monotonic() < deadline:
+ time.sleep(0.05)
+ _write_orphan_record(launcher._records_dir(), proc.pid, str(udd))
+ assert launcher.reap_orphaned_browsers() == 1
+ proc.wait(timeout=10)
+
+
[email protected]_system_guard_bypass # the fake browser's reparented helper is ours to stop
+def test_records_of_a_live_owner_are_left_alone(tmp_path, fake_chromium):
+ launcher.launch_chromium("mine", env=dict(os.environ))
+ assert launcher.reap_orphaned_browsers() == 0
+ assert launcher.get_browser("mine") is not None
+ assert list(launcher._records_dir().glob("*.json"))
+
+
[email protected]("headed,display,expect_headless", [
+ (False, ":1", True),
+ (True, ":1", False),
+ (True, "", True), # Linux without a display: a headed launch would die
+])
+def test_headed_only_when_configured_and_a_display_exists(headed, display, expect_headless):
+ env = {"DISPLAY": display} if display else {}
+ assert launcher._resolve_headed(headed, env) is (not expect_headless)
+
+
+def test_packaged_only_flags_never_reach_an_explicit_binary(monkeypatch):
+ monkeypatch.setattr(launcher, "needs_chromium_sandbox_bypass", lambda: True)
+ monkeypatch.setattr("tools.browser_session_cloud.chromium_args", lambda: ["--lang=de"])
+ packaged = launcher.build_chromium_argv("/c", "/p", packaged=True, headed=False)
+ real = launcher.build_chromium_argv("/c", "/p", packaged=False, headed=True)
+ assert "--password-store=basic" in packaged and "--password-store=basic" not in real
+ assert "--headless=new" in packaged and "--headless=new" not in real
+ for argv in (packaged, real):
+ assert set(launcher.CHROMIUM_SANDBOX_BYPASS_ARGS) <= set(argv)
+ assert "--lang=de" in argv and argv[-1] == "about:blank"
diff --git a/tests/tools/test_browser_session_profile_keys.py b/tests/tools/test_browser_session_profile_keys.py
new file mode 100644
index 00000000000..6ffc3b5621b
--- /dev/null
+++ b/tests/tools/test_browser_session_profile_keys.py
@@ -0,0 +1,90 @@
+"""Served-profile isolation of local browsers: one process serving profile A, then B, then A again must hand
+each profile its OWN Chromium (profile dir under that profile's HERMES_HOME), and A's browser again on the
+return trip, never B's (#110032). Runs the real session layer + launcher against a fake Chromium binary."""
+
+from __future__ import annotations
+
+import json
+import sys
+import textwrap
+from pathlib import Path
+
+import pytest
+
+pytestmark = pytest.mark.platforms("posix")
+
+_FAKE_CHROMIUM = textwrap.dedent('''\
+ #!{python}
+ import os, sys, time
+ udd = next(a.split("=", 1)[1] for a in sys.argv if a.startswith("--user-data-dir="))
+ os.makedirs(udd, exist_ok=True)
+ with open(os.path.join(udd, "DevToolsActivePort"), "w") as f:
+ f.write("{port}\\n/devtools/browser/{{}}\\n".format(os.getpid()))
+ time.sleep(600)
+''')
+
+
+def two_profiles(tmp_path, monkeypatch):
+ from tools import browser_launcher as launcher
+ script = tmp_path / "chromium"
+ script.write_text(_FAKE_CHROMIUM.format(python=sys.executable, port=45679))
+ script.chmod(0o755)
+ monkeypatch.setattr(launcher, "_resolve_executable", lambda: str(script))
+ monkeypatch.setattr(launcher, "chromium_ready", lambda: (True, ""))
+ monkeypatch.setattr(launcher, "needs_chromium_sandbox_bypass", lambda: False)
+ records = tmp_path / "records"
+ records.mkdir()
+ monkeypatch.setattr(launcher, "_records_dir", lambda: records)
+ homes = {}
+ for name in ("a", "b"):
+ home = tmp_path / f"home-{name}"
+ home.mkdir()
+ (home / "config.yaml").write_text(json.dumps({"browser": {}}))
+ homes[name] = home
+ yield homes
+ from tools.browser_session_lifecycle import cleanup_all_browsers
+ cleanup_all_browsers()
+
+
+def _session_in(home: Path) -> dict:
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+ from tools.browser_session import get_session_info
+ from tools.browser_use_cli import _backend_cache_key
+ token = set_hermes_home_override(str(home))
+ try:
+ return get_session_info(_backend_cache_key("same-task"))
+ finally:
+ reset_hermes_home_override(token)
+
+
+def _pid(session: dict) -> int:
+ return int(session["cdp_url"].rsplit("/", 1)[1])
+
+
+def test_profile_a_then_b_then_a_each_get_their_own_browser(two_profiles):
+ first_a = _session_in(two_profiles["a"])
+ b = _session_in(two_profiles["b"])
+ again_a = _session_in(two_profiles["a"])
+
+ assert _pid(first_a) != _pid(b)
+ assert _pid(again_a) == _pid(first_a)
+
+ from tools.browser_launcher import get_browser
+ dirs = {name: Path(get_browser(s["launcher_key"]).user_data_dir)
+ for name, s in (("a", first_a), ("b", b))}
+ assert two_profiles["a"] in dirs["a"].parents
+ assert two_profiles["b"] in dirs["b"].parents
+
+
+def test_cleaning_up_one_profile_leaves_the_other_profiles_browser_running(two_profiles):
+ from hermes_constants import hermes_home_key
+ from tools.browser_launcher import get_browser
+ from tools.browser_session_lifecycle import cleanup_profile_browsers
+ a = _session_in(two_profiles["a"])
+ b = _session_in(two_profiles["b"])
+
+ cleanup_profile_browsers(hermes_home_key(two_profiles["b"]))
+
+ assert get_browser(b["launcher_key"]) is None
+ assert get_browser(a["launcher_key"]) is not None