Skip to content

The agent that grows with you

test(browser): restore the coverage the browser_exec port weakened

Tekniumb3b176a64ede
diff --git a/tests/tools/test_browser_pm.py b/tests/tools/test_browser_pm.py
index 3a7ef0e0f98..9b655e6eb94 100644
--- a/tests/tools/test_browser_pm.py
+++ b/tests/tools/test_browser_pm.py
@@ -102,8 +102,33 @@ def test_execution_acquires_missing_browser_through_pm(browser_store, monkeypatc
assert requests == [("ensure", {"name": "chromium", "explicit": False})]
+def test_doctor_fix_publishes_and_reads_the_pm_browser(browser_store, monkeypatch, capsys):
+ """Plain ``hermes doctor`` never acquires Chromium; ``--fix`` acquires it explicitly through PM and reports
+ the published binary. Only the worker/download boundary is replaced: selection, admission, facts and
+ environment composition are the actual PM implementation."""
+ from hermes_cli import doctor_tools
+ import pm.client
+
+ _, _, publish = browser_store
+ requests, published = [], []
+
+ def request(operation, payload, **kwargs):
+ requests.append((operation, payload))
+ published.append(publish("chromium"))
+
+ monkeypatch.setattr(pm.client, "_request", request)
+ doctor_tools._check_chromium(False)
+ assert requests == []
+ assert "Chromium not installed" in capsys.readouterr().out
+ doctor_tools._check_chromium(True)
+ assert requests == [("ensure", {"name": "chromium", "explicit": True})]
+ assert str(published[0]) in capsys.readouterr().out
+
+
def test_termux_ownership_policy_never_provisions(browser_store, monkeypatch):
# Exercise the real environment policy, not an emulated Android binary.
+ from hermes_cli import doctor_tools
+
monkeypatch.setenv("TERMUX_VERSION", "test")
monkeypatch.setenv("PATH", "")
monkeypatch.setenv("HERMES_DISABLE_LAZY_INSTALLS", "0")
@@ -115,6 +140,7 @@ def test_termux_ownership_policy_never_provisions(browser_store, monkeypatch):
monkeypatch.setattr(pm, "ensure", forbidden)
assert launcher._maybe_autoinstall_chromium() is False
assert launcher.chromium_ready()[0] is False
+ doctor_tools._check_chromium(True) # not even `hermes doctor --fix`
def test_cdp_override_does_not_require_pm_browser(browser_store, monkeypatch):
diff --git a/tests/tools/test_browser_real_profile.py b/tests/tools/test_browser_real_profile.py
index 0e967c66e58..e9350c8978f 100644
--- a/tests/tools/test_browser_real_profile.py
+++ b/tests/tools/test_browser_real_profile.py
@@ -8,6 +8,7 @@ are limited to OS detection and process launch.
"""
import json
import os
+import sys
from types import SimpleNamespace
from unittest.mock import Mock, patch
@@ -179,6 +180,11 @@ class TestSnapshotRealProfile:
assert stat.S_IMODE(os.stat(cookies).st_mode) == 0o600
+# A stand-in browser process for the argv scan. The base interpreter, not a venv's: a Windows venv launcher
+# re-spawns it with the same argv, which would put two processes on the dir.
+_SLEEPER = [getattr(sys, "_base_executable", sys.executable), "-c", "import time; time.sleep(60)"]
+
+
class TestRealProfileCdpLaunch:
"""The launcher-based real-profile browser in browser_session_real_profile.real_profile_cdp."""
@@ -316,6 +322,49 @@ class TestRealProfileCdpLaunch:
snapshot.assert_called_once()
assert cdp is None and "boom" in err
+ @pytest.mark.platforms("windows")
+ def test_windows_reattach_finds_the_surviving_chrome_by_its_argv(self, tmp_path):
+ """Windows Chrome leaves no ``SingletonLock`` symlink: the surviving browser is the process whose argv
+ names the copy dir, and finding it is what keeps the snapshot off its open databases."""
+ import subprocess
+
+ (tmp_path / "DevToolsActivePort").write_text("41000\n/devtools/browser/x\n", encoding="utf-8")
+ chrome = subprocess.Popen([*_SLEEPER, f"--user-data-dir={tmp_path}"])
+ version = Mock()
+ version.json.return_value = {"webSocketDebuggerUrl": "ws://127.0.0.1:41000/devtools/browser/x"}
+ try:
+ with patch.object(bs_cloud, "use_real_profile", return_value=True), \
+ patch("hermes_cli.browser_connect.detect_default_chromium", return_value="chrome"), \
+ patch("hermes_cli.browser_connect.real_profile_copy_dir", return_value=str(tmp_path)), \
+ patch("hermes_cli.browser_connect.chromium_executable", return_value="chrome.exe"), \
+ patch("hermes_cli.browser_connect.snapshot_real_profile", return_value=(None, "boom")) as snapshot, \
+ patch("requests.get", return_value=version):
+ cdp, err = rp.real_profile_cdp()
+ finally:
+ chrome.kill()
+ chrome.wait(timeout=30)
+ 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)
+ assert attached is not None and attached.owned is False and attached.pid == chrome.pid
+
+ def test_the_browser_holding_a_dir_is_found_by_its_argv_never_a_helper(self, tmp_path):
+ """The argv scan behind the Windows singleton check (real processes, any host): the browser process
+ naming the dir, never a ``--type=`` helper naming it too, and nothing for another dir."""
+ import subprocess
+
+ helper = subprocess.Popen([*_SLEEPER, "--type=renderer", f"--user-data-dir={tmp_path}"])
+ browser = subprocess.Popen([*_SLEEPER, f"--user-data-dir={tmp_path}"])
+ try:
+ found = launcher._pid_naming_dir(str(tmp_path))
+ other = launcher._pid_naming_dir(str(tmp_path / "other"))
+ finally:
+ for proc in (helper, browser):
+ proc.kill()
+ proc.wait(timeout=30)
+ assert found == browser.pid
+ assert other is None
+
class TestConsentConfigRead:
"""Unmocked config read: use_real_profile against a real config.yaml."""
diff --git a/tests/tools/test_browser_use_session_expiry.py b/tests/tools/test_browser_use_session_expiry.py
index 136888d67fe..716270d2e10 100644
--- a/tests/tools/test_browser_use_session_expiry.py
+++ b/tests/tools/test_browser_use_session_expiry.py
@@ -3,7 +3,6 @@
from unittest.mock import Mock
from plugins.browser.browser_use import provider as browser_use_provider
-from tools import browser_launcher
from tools import browser_session as bs
from tools import browser_session_cloud as bs_cloud
@@ -72,8 +71,10 @@ def test_expired_cloud_session_is_replaced_without_reusing_dead_cdp(monkeypatch)
}
bs._session_last_activity["task-1"] = 1.0
+ events = []
provider = Mock()
- provider.create_session.return_value = {
+ provider.close_session.side_effect = lambda sid: events.append(("close", sid))
+ provider.create_session.side_effect = lambda task_id: events.append(("create", task_id)) or {
"session_name": "replacement",
"bb_session_id": "browser-session-new",
"cdp_url": "ws://browser-use.example/devtools/browser/new",
@@ -81,15 +82,14 @@ def test_expired_cloud_session_is_replaced_without_reusing_dead_cdp(monkeypatch)
}
monkeypatch.setattr(bs_cloud, "get_cloud_provider", lambda: provider)
monkeypatch.setattr("tools.browser_session_cdp.get_cdp_override", lambda: "")
- monkeypatch.setattr("tools.browser_session_cdp.stop_cdp_supervisor", Mock())
- local_stop = Mock()
- monkeypatch.setattr(browser_launcher, "stop_browser", local_stop)
+ monkeypatch.setattr("tools.browser_session_cdp.stop_cdp_supervisor", lambda key: events.append(("stop", key)))
session = bs.get_session_info("task-1")
assert session["bb_session_id"] == "browser-session-new"
+ assert session["cdp_url"] == "ws://browser-use.example/devtools/browser/new"
assert bs._active_sessions["task-1"] is session
assert "task-1" in bs._session_last_activity
- provider.close_session.assert_called_once_with("browser-session-old")
- provider.create_session.assert_called_once_with("task-1")
- local_stop.assert_not_called()
+ # The supervisor WebSocket on the dead endpoint closes first, then the provider session, and only
+ # then is the replacement created: nothing keeps driving the expired CDP URL.
+ assert events == [("stop", "task-1"), ("close", "browser-session-old"), ("create", "task-1")]
diff --git a/tests/tools/test_browser_windows_headless.py b/tests/tools/test_browser_windows_headless.py
index 9b2d0e9d40b..2a8e6aa6ecd 100644
--- a/tests/tools/test_browser_windows_headless.py
+++ b/tests/tools/test_browser_windows_headless.py
@@ -2,9 +2,10 @@
Windows Desktop opened a blank top-level window during local browser automation: anything that
resolves the launch to headed turns local mode's documented "zero-cost headless Chromium" into a
-visible browser over the Desktop chat. ``browser_launcher._resolve_headed`` keeps Windows headless
-unless ``browser.headed`` is on, and the launch argv carries ``--headless=new``. These run only where
-the behaviour lives, on the Windows lane (the Linux display rule is covered in test_browser_launcher.py).
+visible browser over the Desktop chat. ``browser_launcher._resolve_headed`` keeps every launch headless
+unless the profile's ``browser.headed`` is on, and the launch argv then carries ``--headless=new``. The
+setting is read from a real ``config.yaml``. The Windows-only rule (an opted-in headed launch needs no
+DISPLAY) runs on the Windows lane; the Linux display rule is covered in test_browser_launcher.py.
"""
from pathlib import Path
@@ -12,37 +13,49 @@ from pathlib import Path
import pytest
from tools import browser_launcher as launcher
+from tools import browser_session_cloud as bs_cloud
+
+_WITH_DISPLAY = {"DISPLAY": ":0", "WAYLAND_DISPLAY": "wayland-0"}
@pytest.fixture(autouse=True)
-def _isolated_home(monkeypatch, tmp_path):
+def home(monkeypatch, tmp_path):
+ home = tmp_path / ".hermes"
+ home.mkdir()
monkeypatch.setattr(Path, "home", lambda: tmp_path)
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ monkeypatch.setenv("HERMES_HOME", str(home))
monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "tools"))
monkeypatch.setattr("tools.browser_session_cloud.chromium_args", list)
- yield
+ bs_cloud.reset_caches()
+ yield home
+ bs_cloud.reset_caches()
-def test_windows_stays_headless_unless_headed_is_configured(monkeypatch):
- monkeypatch.setattr("tools.browser_session_cloud.is_headed_mode", lambda: False)
- assert launcher._resolve_headed(None, {"PATH": "C:/Windows"}) is False
- argv = launcher.build_chromium_argv("chrome.exe", "C:/p", packaged=True, headed=False)
- assert "--headless=new" in argv
+def _configure(home: Path, body: str) -> None:
+ (home / "config.yaml").write_text(body, encoding="utf-8")
+ bs_cloud.reset_caches()
+
+
+def test_launch_is_headless_unless_browser_headed_is_configured(home):
+ """No ``browser.headed`` (or ``false``) is headless even where a display exists; ``true`` opts in."""
+ assert launcher._resolve_headed(None, _WITH_DISPLAY) is False
+ _configure(home, "browser:\n headed: false\n")
+ assert launcher._resolve_headed(None, _WITH_DISPLAY) is False
+ _configure(home, "browser:\n headed: true\n")
+ assert launcher._resolve_headed(None, _WITH_DISPLAY) is True
+ assert launcher._resolve_headed(False, _WITH_DISPLAY) is False # an explicit headless launch wins
@pytest.mark.platforms("windows")
-def test_explicit_headed_setting_is_never_overridden(monkeypatch):
- # Windows always has a desktop session: an opted-in headed launch needs no DISPLAY.
- monkeypatch.setattr("tools.browser_session_cloud.is_headed_mode", lambda: True)
+def test_windows_headed_opt_in_needs_no_display(home):
+ """Windows always has a desktop session: no DISPLAY, still headless by default, headed once opted in."""
+ assert launcher._resolve_headed(None, {"PATH": "C:/Windows"}) is False
+ _configure(home, "browser:\n headed: true\n")
assert launcher._resolve_headed(None, {}) is True
- assert launcher._resolve_headed(True, {}) is True
-def test_local_launch_argv_is_headless(monkeypatch, tmp_path):
- """A local launch's real argv carries --headless=new and no headed window (#64867)."""
- monkeypatch.setattr("tools.browser_session_cloud.is_headed_mode", lambda: False)
+def test_default_local_launch_argv_is_headless(monkeypatch, tmp_path):
+ """A default local launch's real argv carries --headless=new, even with a display (#64867)."""
monkeypatch.setattr(launcher, "needs_chromium_sandbox_bypass", lambda: False)
captured = []
@@ -60,7 +73,8 @@ def test_local_launch_argv_is_headless(monkeypatch, tmp_path):
monkeypatch.setattr(launcher, "_start_time", lambda pid: None)
monkeypatch.setattr(launcher, "_terminate", lambda pid, start_time, proc: None)
browser, err = launcher.launch_chromium("win-headless", executable="chrome.exe",
- user_data_dir=str(tmp_path / "udd"), env={}, timeout=1)
+ user_data_dir=str(tmp_path / "udd"), env=dict(_WITH_DISPLAY),
+ timeout=1)
assert browser is None and "exited" in err # the fake exits at once; only the argv matters
assert len(captured) == 1
diff --git a/tests/tui_gateway/test_served_profile_child_env.py b/tests/tui_gateway/test_served_profile_child_env.py
index 2a2be66b271..4ef77367618 100644
--- a/tests/tui_gateway/test_served_profile_child_env.py
+++ b/tests/tui_gateway/test_served_profile_child_env.py
@@ -19,7 +19,8 @@ from agent.secret_scope import set_multiplex_active
from hermes_constants import reset_hermes_home_override, set_hermes_home_override
_PROBE = ("import json,os;print(json.dumps({k:os.environ.get(k) for k in "
- "('HERMES_HOME','A_MARKER','B_MARKER','TERMINAL_ENV','HERMES_MODEL','FIRECRAWL_API_KEY')}))")
+ "('HERMES_HOME','A_MARKER','B_MARKER','TERMINAL_ENV','HERMES_MODEL','FIRECRAWL_API_KEY',"
+ "'BROWSER_USE_API_KEY')}))")
@pytest.fixture
@@ -28,11 +29,12 @@ def mux_homes(tmp_path, monkeypatch):
a = tmp_path / ".hermes"
b = a / "profiles" / "b"
b.mkdir(parents=True)
- (a / ".env").write_text("A_MARKER=a\nHERMES_MODEL=a-model\nTERMINAL_ENV=docker\nFIRECRAWL_API_KEY=a-fc\n", encoding="utf-8")
- (b / ".env").write_text("B_MARKER=b\nFIRECRAWL_API_KEY=b-fc\n", encoding="utf-8")
+ (a / ".env").write_text("A_MARKER=a\nHERMES_MODEL=a-model\nTERMINAL_ENV=docker\nFIRECRAWL_API_KEY=a-fc\n"
+ "BROWSER_USE_API_KEY=a-bu\n", encoding="utf-8")
+ (b / ".env").write_text("B_MARKER=b\nFIRECRAWL_API_KEY=b-fc\nBROWSER_USE_API_KEY=b-bu\n", encoding="utf-8")
monkeypatch.setenv("HERMES_HOME", str(a))
for key, val in (("A_MARKER", "a"), ("HERMES_MODEL", "a-model"), ("TERMINAL_ENV", "docker"),
- ("FIRECRAWL_API_KEY", "a-fc")):
+ ("FIRECRAWL_API_KEY", "a-fc"), ("BROWSER_USE_API_KEY", "a-bu")):
monkeypatch.setenv(key, val)
monkeypatch.delenv("B_MARKER", raising=False)
set_multiplex_active(True)
@@ -119,6 +121,7 @@ def test_helper_children_resolve_secrets_through_the_served_profile(mux_homes):
from agent.command_token_source import _mint
from gateway.run import _profile_runtime_scope
from tools.browser_session import build_browser_env
+ from tools.browser_use_cli import _base_subprocess_env
_a, b = mux_homes
helper = (f"{sys.executable} -c \"import os;print(os.environ.get('B_MARKER','-')+'|'"
@@ -126,7 +129,12 @@ def test_helper_children_resolve_secrets_through_the_served_profile(mux_homes):
with _profile_runtime_scope(b, hydrate_secrets=False):
token, _ttl = _mint(helper, "b-provider")
browser_env = build_browser_env()
+ harness_env = _base_subprocess_env()
assert token == f"b|-|{b}"
seen = _child_view(browser_env)
_assert_is_b_env(seen, b, with_secrets=False) # provider tier stays scrubbed for the browser
- assert seen["FIRECRAWL_API_KEY"] is None # browser children get no provider keys, never the launch profile's
+ assert seen["FIRECRAWL_API_KEY"] is None and seen["BROWSER_USE_API_KEY"] is None # no provider keys
+ # The browser_exec harness child carries its own credential: B's, never the launch profile's.
+ seen = _child_view(harness_env)
+ _assert_is_b_env(seen, b, with_secrets=False)
+ assert seen["BROWSER_USE_API_KEY"] == "b-bu" and seen["FIRECRAWL_API_KEY"] is None
diff --git a/tests/tui_gateway/test_served_profile_child_env_authority.py b/tests/tui_gateway/test_served_profile_child_env_authority.py
index 55e83201445..1e8e3407694 100644
--- a/tests/tui_gateway/test_served_profile_child_env_authority.py
+++ b/tests/tui_gateway/test_served_profile_child_env_authority.py
@@ -8,7 +8,7 @@ Two authority edges of ``served_profile_child_env`` (review of #111617):
a scoped miss is *no credential*, never ambient fallback);
* the Desktop/dashboard backend serves ``?profile=B`` by installing a HERMES_HOME override WITHOUT
the gateway-wide multiplex flag — the strip must key on "this task serves a routed home", not on
- that flag; the browser passthrough must not fall through to the launch key on a B miss either.
+ that flag; the browser_exec harness credential must not fall through to the launch key on a B miss either.
"""
import os
@@ -29,11 +29,12 @@ def homes(tmp_path, monkeypatch):
a = tmp_path / ".hermes"
b = a / "profiles" / "b"
b.mkdir(parents=True)
- (a / ".env").write_text("A_MARKER=a\nHERMES_MODEL=a-model\nFIRECRAWL_API_KEY=a-fc\n", encoding="utf-8")
+ (a / ".env").write_text("A_MARKER=a\nHERMES_MODEL=a-model\nFIRECRAWL_API_KEY=a-fc\nBROWSER_USE_API_KEY=a-bu\n",
+ encoding="utf-8")
(b / ".env").write_text("B_MARKER=b\n", encoding="utf-8")
monkeypatch.setenv("HERMES_HOME", str(a))
for key, val in (("A_MARKER", "a"), ("HERMES_MODEL", "a-model"), ("FIRECRAWL_API_KEY", "a-fc"),
- ("OPENAI_API_KEY", "sk-ambient-launch-only")):
+ ("BROWSER_USE_API_KEY", "a-bu"), ("OPENAI_API_KEY", "sk-ambient-launch-only")):
monkeypatch.setenv(key, val)
monkeypatch.delenv("B_MARKER", raising=False)
set_multiplex_active(False)
@@ -62,8 +63,10 @@ def test_ambient_only_launch_credential_never_reaches_a_routed_child(homes):
def test_routed_home_with_multiplex_flag_off_gets_no_launch_residue(homes, monkeypatch):
"""Desktop/dashboard topology: B served via the HERMES_HOME override only. The slash-worker /
- helper child sees B's env, and the browser child env carries no provider key for either profile."""
+ helper child sees B's env, the browser child env carries no provider key for either profile, and the
+ browser_exec harness resolves B's (absent) credential as no credential."""
from tools.browser_session import build_browser_env
+ from tools.browser_use_cli import _harness_credentials
_a, b = homes
token = set_hermes_home_override(str(b))
@@ -73,10 +76,13 @@ def test_routed_home_with_multiplex_flag_off_gets_no_launch_residue(homes, monke
assert "A_MARKER" not in env and "HERMES_MODEL" not in env and "OPENAI_API_KEY" not in env
browser_env = build_browser_env()
assert "FIRECRAWL_API_KEY" not in browser_env and browser_env["HERMES_HOME"] == str(b)
+ assert _harness_credentials() == {}
finally:
reset_hermes_home_override(token)
- # Control: the launch profile's browser env is credential-free too; its other children keep their settings.
+ # Control: the launch profile's browser env is credential-free too, its harness keeps its own key, and
+ # its other children keep their settings.
assert "FIRECRAWL_API_KEY" not in build_browser_env()
+ assert _harness_credentials() == {"BROWSER_USE_API_KEY": "a-bu"}
assert served_profile_child_env(inherit_credentials=True)["HERMES_MODEL"] == "a-model"