Skip to content

The agent that grows with you

test(browser): port real-profile, Bot Desktop, multiplex and tool-surface tests to browser_session + launcher

Teknium8b73b4d3b46c
diff --git a/tests/tools/test_bot_desktop_browser.py b/tests/tools/test_bot_desktop_browser.py
index da0d5866fd8..db531c7f274 100644
--- a/tests/tools/test_bot_desktop_browser.py
+++ b/tests/tools/test_bot_desktop_browser.py
@@ -1,11 +1,13 @@
-"""The dock's Browser and agent-browser resolve to one identity: same executable, same user-data-dir —
+"""The dock's Browser and the agent's Chromium resolve to one identity: same executable, same user-data-dir —
and when a human opened that browser first, the agent attaches to it instead of launching a second one
(Chromium's profile singleton would forward the launch and kill it without a DevTools endpoint)."""
from __future__ import annotations
+import json
import os
-import socket
+import threading
+from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
from types import SimpleNamespace
@@ -14,43 +16,75 @@ import pytest
from tools.bot_desktop import browser, runtime
+def _browser_config(monkeypatch, home: Path, **browser_cfg) -> None:
+ """This profile's real config.yaml with a ``browser:`` section."""
+ home.mkdir(parents=True, exist_ok=True)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ (home / "config.yaml").write_text(json.dumps({"browser": browser_cfg}), encoding="utf-8")
+
+
+def _agent_launch(monkeypatch, display: str = ":37") -> dict:
+ """Create the agent's local browser session with the Bot Desktop screen up; returns the launcher call
+ (``key`` + kwargs) instead of starting Chromium."""
+ from tools import browser_launcher, browser_session, browser_session_cdp, browser_session_cloud
+ from tools import browser_session_lifecycle
+
+ for name in ("_active_sessions", "_session_last_activity", "_session_owner_homes", "_cleanup_failures"):
+ monkeypatch.setattr(browser_session, name, {})
+ monkeypatch.setattr(browser_session_lifecycle, "start_cleanup_thread", lambda: None)
+ monkeypatch.setattr(browser_session_cdp, "get_cdp_override", lambda: "")
+ monkeypatch.setattr(browser_session_cloud, "get_cloud_provider", lambda: None)
+ monkeypatch.setattr(browser_session, "browser_in_sandbox", lambda: False)
+ monkeypatch.setattr("tools.browser_session_real_profile.real_profile_cdp", lambda: (None, None))
+ monkeypatch.setattr("tools.browser_lightpanda.using_lightpanda_engine", lambda: False)
+ monkeypatch.setattr(runtime, "published_env", lambda: {"DISPLAY": display})
+ call: dict = {}
+
+ def launch(key, **kwargs):
+ call.update(kwargs, key=key)
+ return SimpleNamespace(cdp_url="ws://127.0.0.1:41234/devtools/browser/abc", pid=4242), None
+
+ monkeypatch.setattr(browser_launcher, "launch_chromium", launch)
+ browser_session.get_session_info("agent-task")
+ return call
+
+
def test_dock_and_agent_share_browser_identity(tmp_path, monkeypatch):
exe = tmp_path / "chrome"
exe.write_text("#!/bin/sh\n", encoding="utf-8")
exe.chmod(0o755)
- monkeypatch.setenv("AGENT_BROWSER_EXECUTABLE_PATH", str(exe))
- monkeypatch.delenv("AGENT_BROWSER_PROFILE", raising=False)
+ _browser_config(monkeypatch, tmp_path / "home", executable_path=str(exe))
monkeypatch.setattr(runtime, "state_dir", lambda: tmp_path / "bot-desktop")
dock_exe, dock_profile = browser.dock_launch()
- agent_env = browser.env_for_agent({})
+ agent = _agent_launch(monkeypatch)
- assert dock_exe == agent_env["AGENT_BROWSER_EXECUTABLE_PATH"] == str(exe)
- assert dock_profile == agent_env["AGENT_BROWSER_PROFILE"] == str(tmp_path / "bot-desktop" / "browser-profile")
+ assert dock_exe == agent["executable"] == str(exe)
+ assert dock_profile == agent["user_data_dir"] == str(tmp_path / "bot-desktop" / "browser-profile")
+ assert agent["ephemeral"] is False, "the shared profile's logins must survive the agent's browser"
def test_user_pinned_profile_wins(tmp_path, monkeypatch):
- monkeypatch.setenv("AGENT_BROWSER_PROFILE", str(tmp_path / "mine"))
+ _browser_config(monkeypatch, tmp_path / "home", user_data_dir=str(tmp_path / "mine"))
monkeypatch.setattr(runtime, "state_dir", lambda: tmp_path / "bot-desktop")
assert browser.profile_dir() == tmp_path / "mine"
def test_pinned_profile_honours_tilde_and_resolves_relative_paths_against_hermes_home(tmp_path, monkeypatch):
- """Regression for #110029: the docs say setting AGENT_BROWSER_PROFILE pins your own user-data-dir, but only
- an absolute value was honoured — `~/pin` and `pin` silently fell back to the default and the human's dock
- browser and the agent's browser could end up on different jars. A relative path is anchored where the rest
- of this profile's screen state lives (its HERMES_HOME), so two profiles never share one 'pin'."""
+ """Regression for #110029: the docs say pinning a user-data-dir pins your own, but only an absolute value
+ was honoured — `~/pin` and `pin` silently fell back to the default and the human's dock browser and the
+ agent's browser could end up on different jars. A relative path is anchored where the rest of this
+ profile's screen state lives (its HERMES_HOME), so two profiles never share one 'pin'."""
home = tmp_path / "hermes-home"
- monkeypatch.setenv("HERMES_HOME", str(home))
monkeypatch.setattr(runtime, "get_hermes_home", lambda: home)
monkeypatch.setattr(Path, "home", lambda: tmp_path / "user")
monkeypatch.setenv("HOME", str(tmp_path / "user"))
- monkeypatch.setenv("AGENT_BROWSER_PROFILE", "~/pin")
+ _browser_config(monkeypatch, home, user_data_dir="~/pin")
assert browser.profile_dir() == tmp_path / "user" / "pin"
- monkeypatch.setenv("AGENT_BROWSER_PROFILE", "pin")
+ _browser_config(monkeypatch, home, user_data_dir="pin")
assert browser.profile_dir() == home / "pin"
- assert browser.env_for_agent({})["AGENT_BROWSER_PROFILE"] == str(home / "pin"), "agent-browser gets the resolved path"
+ assert _agent_launch(monkeypatch)["user_data_dir"] == str(home / "pin"), "the agent's launch gets the resolved path"
def test_dock_browser_advertises_a_devtools_port():
@@ -71,59 +105,80 @@ def _fake_running_instance(user_data_dir, pid: int, port: int) -> None:
os.symlink(f"host-{pid}", user_data_dir / "SingletonLock")
+def _devtools_server():
+ """A loopback server answering ``/json/version`` like the dock's Chromium (browser id ``abc``)."""
+ class Handler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ port = self.server.server_address[1]
+ body = json.dumps({"webSocketDebuggerUrl": f"ws://127.0.0.1:{port}/devtools/browser/abc"}).encode()
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *_a):
+ pass
+
+ server = HTTPServer(("127.0.0.1", 0), Handler)
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ return server
+
+
def test_running_instance_port_requires_live_pid_and_open_port(tmp_path):
- listener = socket.socket()
- listener.bind(("127.0.0.1", 0))
- listener.listen(1)
- port = listener.getsockname()[1]
+ from tools import browser_launcher as launcher
+
+ server = _devtools_server()
+ port = server.server_address[1]
try:
_fake_running_instance(tmp_path, os.getpid(), port)
- assert browser.running_instance_cdp_port(str(tmp_path)) == port
+ assert launcher.running_instance(str(tmp_path)) == (port, "/devtools/browser/abc", os.getpid())
# Both files outlive a closed Chromium: a dead pid must not be trusted.
os.unlink(tmp_path / "SingletonLock")
os.symlink("host-2147483000", tmp_path / "SingletonLock")
- assert browser.running_instance_cdp_port(str(tmp_path)) is None
+ assert launcher.running_instance(str(tmp_path)) is None
finally:
- listener.close()
+ server.shutdown()
+ server.server_close()
# Live pid, port no longer accepting: still not attachable.
os.unlink(tmp_path / "SingletonLock")
os.symlink(f"host-{os.getpid()}", tmp_path / "SingletonLock")
- assert browser.running_instance_cdp_port(str(tmp_path)) is None
- assert browser.running_instance_cdp_port(str(tmp_path / "missing")) is None
-
+ assert launcher.running_instance(str(tmp_path)) is None
+ assert launcher.running_instance(str(tmp_path / "missing")) is None
-def test_agent_attaches_to_human_started_browser(monkeypatch):
- """With a live dock instance on the shared profile the local argv carries ``--cdp <port>``; without one
- it stays a plain ``--session`` launch."""
- from tools import browser_tool_session as session
- monkeypatch.setattr(runtime, "published_env", lambda: {"DISPLAY": ":37"})
- monkeypatch.setattr(session._cloud, "_get_browser_engine", lambda: "auto")
- monkeypatch.setattr(session._cloud, "_is_headed_mode", lambda: False)
- monkeypatch.setattr(session, "_agent_browser_argv", lambda cmd: [cmd])
- argvs: list = []
+def test_agent_attaches_to_human_started_browser(tmp_path, monkeypatch):
+ """With a live dock instance on the shared profile the agent's launch ATTACHES to it (never owned, so
+ never killed by Hermes); without one it launches its own Chromium on that profile."""
+ from tools import browser_launcher as launcher
- def spawn(task_id, session_info, cmd_parts, *rest):
- argvs.append(cmd_parts)
- return {"success": True}
+ monkeypatch.setattr(launcher, "_browsers", {})
+ monkeypatch.setattr(launcher, "_procs", {})
+ udd = str(tmp_path / "browser-profile")
+ spawned: list = []
- monkeypatch.setattr(session, "_spawn_and_collect", spawn)
- monkeypatch.setattr(session._lp, "_lightpanda_fallback_reason", lambda *a: None)
- info = {"session_name": "h_abc", "cdp_url": None, "features": {"local": True}}
+ def launch_owned(key, executable, user_data_dir, **_kw):
+ spawned.append((key, executable, user_data_dir))
+ return None, "spawn recorded"
- monkeypatch.setattr(browser, "running_instance_cdp_port", lambda d, **kw: 41234)
- session._dispatch_browser_command("t", info, "agent-browser", "open", ["https://x"], 10, None)
- assert argvs[-1][:5] == ["agent-browser", "--session", "h_abc", "--cdp", "41234"]
+ monkeypatch.setattr(launcher, "_launch_owned", launch_owned)
+ monkeypatch.setattr(launcher, "running_instance", lambda d: (41234, "/devtools/browser/abc", os.getpid()) if d == udd else None)
+ attached, err = launcher.launch_chromium(f"profile:{udd}", executable="/opt/chrome", user_data_dir=udd, ephemeral=False)
+ assert err is None and spawned == []
+ assert attached.cdp_url == "ws://127.0.0.1:41234/devtools/browser/abc"
+ assert attached.owned is False
- monkeypatch.setattr(browser, "running_instance_cdp_port", lambda d, **kw: None)
- session._dispatch_browser_command("t", info, "agent-browser", "open", ["https://x"], 10, None)
- assert "--cdp" not in argvs[-1] and argvs[-1][:3] == ["agent-browser", "--session", "h_abc"]
+ launcher._browsers.clear()
+ monkeypatch.setattr(launcher, "running_instance", lambda d: None)
+ launcher.launch_chromium(f"profile:{udd}", executable="/opt/chrome", user_data_dir=udd, ephemeral=False)
+ assert spawned == [(f"profile:{udd}", "/opt/chrome", udd)]
def _install_browsers(tmp_path, monkeypatch, *, playwright: bool, system: bool):
"""A Playwright build under a private PLAYWRIGHT_BROWSERS_PATH and/or a system chromium on PATH."""
monkeypatch.delenv("AGENT_BROWSER_EXECUTABLE_PATH", raising=False)
+ monkeypatch.setattr("tools.browser_session_cloud.executable_path", lambda: "")
roots = tmp_path / "pw"
roots.mkdir(parents=True)
monkeypatch.setenv("PLAYWRIGHT_BROWSERS_PATH", str(roots))
@@ -150,7 +205,7 @@ def test_unprivileged_user_under_apparmor_userns_restriction_gets_the_system_bro
kernel.apparmor_restrict_unprivileged_userns=1 it dies 'FATAL: No usable sandbox!' for a non-root user,
so the dock icon is dead. A distro chromium (which ships the sandbox helper) must win there — and
the Playwright build stays the answer when it is the only one, started with exactly the flags
- agent-browser starts it with on that host (one sandbox policy for the human's and the bot's browser)."""
+ the agent's launch starts it with on that host (one sandbox policy for the human's and the bot's browser)."""
pw_exe, sys_exe = _install_browsers(tmp_path, monkeypatch, playwright=True, system=True)
monkeypatch.setattr(browser.os, "geteuid", lambda: 1000)
monkeypatch.setattr(browser, "_userns_restricted", lambda: True)
@@ -163,39 +218,39 @@ def test_unprivileged_user_under_apparmor_userns_restriction_gets_the_system_bro
monkeypatch.setattr(browser, "_userns_restricted", lambda: True)
exe = browser.executable()
assert exe and exe.endswith("chrome-linux/chrome")
- from tools import browser_tool_session as session
-
- agent_env: dict = {}
- session._apply_chromium_sandbox_args(agent_env)
- agent_flags = set(agent_env.get("AGENT_BROWSER_ARGS", "").split(",")) - {""}
+ agent_flags = _agent_sandbox_flags(exe)
assert agent_flags <= set(browser.dock_argv(exe, "/p/dir"))
assert ("--no-sandbox" in browser.dock_argv(exe, "/p/dir")) == ("--no-sandbox" in agent_flags)
+def _agent_sandbox_flags(exe: str) -> set:
+ """The sandbox-bypass flags the agent's launch of ``exe`` on the shared profile carries."""
+ from tools.browser_launcher import CHROMIUM_SANDBOX_BYPASS_ARGS, build_chromium_argv
+
+ argv = build_chromium_argv(exe, "/p/dir", packaged=False, headed=True, extra_args=browser.SHARED_PROFILE_ARGS)
+ return set(argv) & set(CHROMIUM_SANDBOX_BYPASS_ARGS)
+
+
def test_root_dock_browser_starts_with_the_same_sandbox_args_as_the_agents_browser(monkeypatch):
- """Chromium refuses to start as root without --no-sandbox; agent-browser gets that flag from one
+ """Chromium refuses to start as root without --no-sandbox; the agent's launch gets that flag from one
policy, and the dock icon (same binary, same profile) must get the very same flags or the human's
click dies while the agent's launch works."""
- from tools import browser_tool_session as session
-
- monkeypatch.setattr(session.os, "geteuid", lambda: 0)
- monkeypatch.setattr(browser.os, "geteuid", lambda: 0)
- agent_env: dict = {}
- session._apply_chromium_sandbox_args(agent_env)
- agent_flags = set(agent_env["AGENT_BROWSER_ARGS"].split(","))
- assert agent_flags, "root must inject sandbox flags for agent-browser"
+ from tools import browser_launcher as launcher
+
+ monkeypatch.setattr("tools.browser_session_cloud.chromium_args", list)
+ monkeypatch.setattr(launcher.os, "geteuid", lambda: 0)
+ agent_flags = _agent_sandbox_flags("/opt/chrome")
+ assert agent_flags, "root must inject sandbox flags for the agent's Chromium"
assert agent_flags <= set(browser.dock_argv("/opt/chrome", "/p/dir"))
# Same policy for the NON-root container case (the official image runs the gateway as uid 10000 in
- # Docker): agent-browser bypasses the sandbox there, and the dock icon must too or it dies on click.
- monkeypatch.setattr(session.os, "geteuid", lambda: 10000)
- monkeypatch.setattr(browser.os, "geteuid", lambda: 10000)
- monkeypatch.setattr(session._install, "_running_in_docker", lambda: True)
- docker_env: dict = {}
- session._apply_chromium_sandbox_args(docker_env)
- assert set(docker_env["AGENT_BROWSER_ARGS"].split(",")) <= set(browser.dock_argv("/opt/chrome", "/p/dir"))
- monkeypatch.setattr(session._install, "_running_in_docker", lambda: False)
- monkeypatch.setattr(session, "apparmor_restricts_unprivileged_userns", lambda: False)
+ # Docker): the agent's launch bypasses the sandbox there, and the dock icon must too or it dies on click.
+ monkeypatch.setattr(launcher.os, "geteuid", lambda: 10000)
+ monkeypatch.setattr(launcher, "running_in_docker", lambda: True)
+ docker_flags = _agent_sandbox_flags("/opt/chrome")
+ assert docker_flags and docker_flags <= set(browser.dock_argv("/opt/chrome", "/p/dir"))
+ monkeypatch.setattr(launcher, "running_in_docker", lambda: False)
+ monkeypatch.setattr(launcher, "apparmor_restricts_unprivileged_userns", lambda: False)
assert "--no-sandbox" not in browser.dock_argv("/opt/chrome", "/p/dir") # seated non-root host: sandboxed
@@ -229,7 +284,7 @@ def test_dock_exec_line_survives_spaces_in_the_executable_and_profile_paths():
def test_headless_shell_override_is_not_a_headed_browser(tmp_path, monkeypatch):
"""The official Docker image ships only Playwright's chrome-headless-shell and its boot hook exports it
- as AGENT_BROWSER_EXECUTABLE_PATH. That binary cannot open a window: taken at face value the dock's
+ as the browser override. That binary cannot open a window: taken at face value the dock's
Browser icon would point at it and status would claim a headed browser exists. Live in the image:
status.browser named the headless shell while the dock had no working Browser."""
shell = tmp_path / "shell" / "chromium_headless_shell-1243" / "chrome-headless-shell-linux64" / "chrome-headless-shell"
@@ -237,11 +292,11 @@ def test_headless_shell_override_is_not_a_headed_browser(tmp_path, monkeypatch):
shell.write_text("#!/bin/sh\n", encoding="utf-8")
shell.chmod(0o755)
_install_browsers(tmp_path, monkeypatch, playwright=False, system=False)
- monkeypatch.setenv("AGENT_BROWSER_EXECUTABLE_PATH", str(shell))
+ monkeypatch.setattr("tools.browser_session_cloud.executable_path", lambda: str(shell))
assert browser.executable() is None
_, sys_exe = _install_browsers(tmp_path / "with-sys", monkeypatch, playwright=False, system=True)
- monkeypatch.setenv("AGENT_BROWSER_EXECUTABLE_PATH", str(shell))
+ monkeypatch.setattr("tools.browser_session_cloud.executable_path", lambda: str(shell))
assert browser.executable() == sys_exe # a real headed browser elsewhere still wins over the override
@@ -262,85 +317,72 @@ def test_headless_override_does_not_hide_pm_headed_browser(tmp_path, monkeypatch
assert chromium_executable() == str(headless) # ordinary headless browsing keeps its override
dock = browser.dock_launch()
assert dock is not None and dock[0] == str(headed)
- assert browser.env_for_agent({})["AGENT_BROWSER_EXECUTABLE_PATH"] == str(headed)
+ assert _agent_launch(monkeypatch)["executable"] == str(headed)
@pytest.mark.parametrize("engine, headed, starts", [("chrome", True, 1), ("chrome", False, 0), ("lightpanda", True, 0)])
-def test_headed_chromium_spawn_asks_the_screen_to_start_but_the_env_builder_never_does(tmp_path, monkeypatch, engine, headed, starts):
- """Regression for #110050 at the right boundary: a real browser command that forks a headed Chromium daemon
- starts the profile's screen (bot_desktop.auto_start) like computer_use dispatch does; `_build_browser_env()`
- itself stays pure — it also serves the npx cache warmer, the Chromium auto-installer and the Lightpanda
- engine, none of which may block on Xvnc+Xfce coming up."""
- from tools import browser_tool as bt
- from tools import browser_tool_cloud as cloud
- from tools import browser_tool_session as session
+def test_headed_chromium_spawn_asks_the_screen_to_start_but_the_env_builder_never_does(monkeypatch, engine, headed, starts):
+ """Regression for #110050 at the right boundary: creating a local session that launches a headed Chromium
+ starts the profile's screen (bot_desktop.auto_start) like computer_use dispatch does; `build_browser_env()`
+ itself stays pure — it also serves the harness CLI, the Lightpanda engine and every launch, none of which
+ may block on Xvnc+Xfce coming up."""
+ from tools import browser_launcher, browser_lightpanda, browser_session, browser_session_cdp
+ from tools import browser_session_cloud, browser_session_lifecycle
calls: list = []
monkeypatch.setattr(runtime, "ensure_started_for_tool", lambda: calls.append(1))
monkeypatch.setattr(runtime, "published_env", dict)
- monkeypatch.setattr(cloud, "_is_headed_mode", lambda: headed)
- bt._build_browser_env()
+ monkeypatch.setattr(browser_session_cloud, "is_headed_mode", lambda: headed)
+ browser_session.build_browser_env()
assert calls == []
- class _Done:
- returncode = 0
- def wait(self, timeout=None): return 0
- def _fake_popen(argv, env, socket_dir, tag, stdin_payload=None):
- for slot in ("stdout", "stderr"):
- Path(socket_dir, f"_{slot}_{tag}").write_text("{}" if slot == "stdout" else "", encoding="utf-8")
- return _Done()
- monkeypatch.setattr(session, "_popen_agent_browser", _fake_popen)
- monkeypatch.setattr(session, "_prepare_session_socket_dir", lambda name: str(tmp_path))
- session._spawn_and_collect("t", {"session_name": "h_x"}, ["agent-browser"], "open", engine, 5)
+ for name in ("_active_sessions", "_session_last_activity", "_session_owner_homes", "_cleanup_failures"):
+ monkeypatch.setattr(browser_session, name, {})
+ monkeypatch.setattr(browser_session_lifecycle, "start_cleanup_thread", lambda: None)
+ monkeypatch.setattr(browser_session_cdp, "get_cdp_override", lambda: "")
+ monkeypatch.setattr(browser_session_cloud, "get_cloud_provider", lambda: None)
+ monkeypatch.setattr(browser_session, "browser_in_sandbox", lambda: False)
+ monkeypatch.setattr("tools.browser_session_real_profile.real_profile_cdp", lambda: (None, None))
+ monkeypatch.setattr(browser_session_cloud, "get_browser_engine", lambda: engine)
+ monkeypatch.setattr(browser_launcher, "launch_chromium", lambda key, **kw: (
+ SimpleNamespace(cdp_url="ws://127.0.0.1:41234/devtools/browser/abc", pid=4242), None))
+ monkeypatch.setattr(browser_lightpanda, "launch_lightpanda", lambda name, **kw: (
+ SimpleNamespace(cdp_url="ws://127.0.0.1:9333", port=9333), None))
+ browser_session.get_session_info("t")
assert len(calls) == starts
def test_janitor_keeps_the_shared_browser_alive_while_a_human_holds_the_lease(monkeypatch):
"""#110064: the agent goes idle BECAUSE the human took over to log in; the janitor must count the human's
lease as activity for the shared local browser, and reap it again once the lease is handed back."""
- from tools import browser_tool_lifecycle as lifecycle, browser_tool_session as session
+ from tools import browser_session as session, browser_session_lifecycle as lifecycle
from tools.bot_desktop import lease
monkeypatch.setattr(runtime, "published_env", lambda: {"DISPLAY": ":37"})
holder = {"human": True}
monkeypatch.setattr(lease, "human_holds", lambda *a, **k: holder["human"])
reaped: list = []
- monkeypatch.setattr(lifecycle, "cleanup_browser", lambda task_id: reaped.append(task_id))
- monkeypatch.setattr(lifecycle._bt, "BROWSER_SESSION_INACTIVITY_TIMEOUT", 1)
- monkeypatch.setattr(lifecycle._bt, "_active_sessions", {
+ monkeypatch.setattr(lifecycle, "cleanup_single_session", lambda cache_key: reaped.append(cache_key))
+ monkeypatch.setattr(session, "BROWSER_SESSION_INACTIVITY_TIMEOUT", 1)
+ monkeypatch.setattr(session, "_active_sessions", {
"bot": {"session_name": "h_bot", "features": {"local": True}},
"cloud": {"session_name": "c_1", "bb_session_id": "bb", "features": {}},
})
- monkeypatch.setattr(lifecycle._bt, "_session_last_activity", {"bot": 0.0, "cloud": 0.0})
- monkeypatch.setattr(lifecycle._bt, "_session_owner_homes", {})
+ monkeypatch.setattr(session, "_session_last_activity", {"bot": 0.0, "cloud": 0.0})
+ monkeypatch.setattr(session, "_session_owner_homes", {})
+ monkeypatch.setattr(session, "_cleanup_failures", {})
- lifecycle._cleanup_inactive_browser_sessions()
+ lifecycle.cleanup_inactive_sessions()
assert reaped == ["cloud"], "only the browser the human is not typing into may be reaped"
- assert lifecycle._bt._session_last_activity["bot"] > 0, "the human's lease refreshed the bot browser's activity"
+ assert session._session_last_activity["bot"] > 0, "the human's lease refreshed the bot browser's activity"
holder["human"] = False
- lifecycle._bt._session_last_activity["bot"] = 0.0
- lifecycle._cleanup_inactive_browser_sessions()
+ session._session_last_activity["bot"] = 0.0
+ lifecycle.cleanup_inactive_sessions()
assert reaped == ["cloud", "bot"]
assert session.human_holds_shared_browser({"features": {"local": True}}) is False
-def test_daemon_idle_timer_defers_to_the_janitor_only_for_the_shared_headed_browser(monkeypatch):
- """The agent-browser daemon cannot see the lease, so on the Bot Desktop its self-termination timer steps
- back and the lease-aware janitor owns the browser's lifetime; headless browsing keeps the mirror."""
- from tools import browser_tool_session as session
-
- monkeypatch.setattr(session._bt, "BROWSER_SESSION_INACTIVITY_TIMEOUT", 120)
- monkeypatch.setattr(runtime, "published_env", lambda: {"DISPLAY": ":37"})
- monkeypatch.setattr(session._cloud, "_is_headed_mode", lambda: True)
- assert session._daemon_idle_timeout_seconds() > 120
- monkeypatch.setattr(session._cloud, "_is_headed_mode", lambda: False)
- assert session._daemon_idle_timeout_seconds() == 120
- monkeypatch.setattr(session._cloud, "_is_headed_mode", lambda: True)
- monkeypatch.setattr(runtime, "published_env", dict)
- assert session._daemon_idle_timeout_seconds() == 120
-
-
def test_a_headless_shell_pin_is_replaced_while_a_screen_is_up(tmp_path, monkeypatch):
"""The boot hook exports a chrome-headless-shell path; leaving it would put the agent and the dock on
two binaries over one --user-data-dir, where the singleton swallows the dock's launch."""
@@ -352,14 +394,14 @@ def test_a_headless_shell_pin_is_replaced_while_a_screen_is_up(tmp_path, monkeyp
headed.chmod(0o755)
monkeypatch.setattr(runtime, "state_dir", lambda: tmp_path / "bot-desktop")
monkeypatch.setattr(browser, "_managed_executable", lambda: str(headed))
- monkeypatch.delenv("AGENT_BROWSER_PROFILE", raising=False)
+ monkeypatch.setattr("tools.browser_session_cloud.executable_path", lambda: str(shell))
# Unpinned, the ubuntu runner (non-root, userns-restricted) flips executable() to
# its own /usr/bin/google-chrome; host policy is not the subject here.
monkeypatch.setattr(browser, "_userns_restricted", lambda: False)
- agent_env = browser.env_for_agent({"AGENT_BROWSER_EXECUTABLE_PATH": str(shell)})
+ agent = _agent_launch(monkeypatch)
dock_exe, _ = browser.dock_launch()
- assert agent_env["AGENT_BROWSER_EXECUTABLE_PATH"] == dock_exe == str(headed), \
+ assert agent["executable"] == dock_exe == str(headed), \
"the agent and the dock must share one binary once a screen is up"
@@ -373,6 +415,6 @@ def test_a_real_user_pin_is_still_honoured(tmp_path, monkeypatch):
other.chmod(0o755)
monkeypatch.setattr(runtime, "state_dir", lambda: tmp_path / "bot-desktop")
monkeypatch.setattr(browser, "_managed_executable", lambda: str(other))
+ monkeypatch.setattr("tools.browser_session_cloud.executable_path", lambda: str(mine))
- env = browser.env_for_agent({"AGENT_BROWSER_EXECUTABLE_PATH": str(mine)})
- assert env["AGENT_BROWSER_EXECUTABLE_PATH"] == str(mine)
+ assert _agent_launch(monkeypatch)["executable"] == str(mine)
diff --git a/tests/tools/test_bot_desktop_browser_fence.py b/tests/tools/test_bot_desktop_browser_fence.py
index 184d3003fb8..e96efdd1f88 100644
--- a/tests/tools/test_bot_desktop_browser_fence.py
+++ b/tests/tools/test_bot_desktop_browser_fence.py
@@ -19,41 +19,20 @@ def _fresh(monkeypatch):
lease._reset_for_tests()
-def _wire(monkeypatch, commands):
- from tools import browser_tool as browser
- from tools import browser_tool_session as session
-
- monkeypatch.delenv("AGENT_BROWSER_PROFILE", raising=False)
- monkeypatch.setattr(browser, "_is_camofox_mode", lambda: False)
- monkeypatch.setattr(browser, "_blocked_private_page_action", lambda *a: None)
- monkeypatch.setattr(session, "_browser_command_preflight", lambda: {"browser_cmd": "agent-browser"})
- monkeypatch.setattr(session, "_get_session_info", lambda *a: {"session_name": "review", "cdp_url": None, "features": {"local": True}})
- monkeypatch.setattr(session._cloud, "_get_browser_engine", lambda: "chrome")
- monkeypatch.setattr(session._cloud, "_is_headed_mode", lambda: True)
-
- def spawn(*args):
- commands.append(args[2])
- return {"success": True, "data": {"secret": "WHAT-THE-HUMAN-TYPED"}}
-
- monkeypatch.setattr(session, "_spawn_and_collect", spawn)
- return browser, session
-
-
def _wire_browser_exec(monkeypatch, run_cli):
- """Route browser_exec through local Chromium without starting a real browser."""
- from tools import browser_tool_cloud as cloud
- from tools import browser_tool_session as session
+ """Route browser_exec through the local session layer without starting a real browser."""
+ from tools import browser_lightpanda, browser_session, browser_session_cdp, browser_session_cloud
from tools import browser_use_cli as browser_use
monkeypatch.setattr(browser_use, "_find_cli", lambda: ["browser-use"])
monkeypatch.setattr(browser_use, "_base_subprocess_env", dict)
monkeypatch.setattr(browser_use, "_real_profile_consented", lambda: False)
- monkeypatch.setattr(browser_use, "_resolve_lightpanda_cdp", lambda *a: None)
- monkeypatch.setattr("tools.browser_tool_cdp._get_cdp_override", lambda: "")
- monkeypatch.setattr("tools.browser_tool._get_open_command_timeout", lambda **_kw: 5)
- monkeypatch.setattr(cloud, "_get_cloud_provider", lambda: None)
- monkeypatch.setattr(session, "_run_browser_command", lambda *_a, **_kw: {
- "success": True, "data": {"cdpUrl": "http://127.0.0.1:9222"}})
+ monkeypatch.setattr(browser_lightpanda, "using_lightpanda_engine", lambda: False)
+ monkeypatch.setattr(browser_session_cdp, "get_cdp_override", lambda: "")
+ monkeypatch.setattr(browser_session_cdp, "get_cdp_override_raw", lambda: "")
+ monkeypatch.setattr(browser_session_cloud, "get_cloud_provider", lambda: None)
+ monkeypatch.setattr(browser_session, "get_session_info", lambda *_a, **_kw: {
+ "session_name": "review", "cdp_url": "http://127.0.0.1:9222", "features": {"local": True}})
monkeypatch.setattr(browser_use, "_attach_vault_supervisor", lambda *a: None)
monkeypatch.setattr(browser_use, "_run_cli_killing_process_group", run_cli)
return browser_use
@@ -90,27 +69,28 @@ def test_browser_exec_result_crossing_a_takeover_is_discarded(monkeypatch):
assert result.get("code") == "human_has_control"
-def test_browser_click_is_fenced_while_human_controls_shared_browser(monkeypatch):
- commands: list = []
- browser, _ = _wire(monkeypatch, commands)
+def test_run_fenced_refuses_a_local_session_while_human_controls_shared_browser():
+ from tools.browser_session import run_fenced
+
+ dispatched: list = []
lease.acquire("human-viewer")
- result = json.loads(browser.browser_click("e1", task_id="review"))
- assert commands == [], f"human holds the lease, yet a browser command was dispatched: {commands}"
+ result = run_fenced({"session_name": "review", "cdp_url": None, "features": {"local": True}},
+ lambda: dispatched.append("cmd") or {"success": True})
+ assert dispatched == [], f"human holds the lease, yet a browser command was dispatched: {dispatched}"
assert result.get("code") == "human_has_control"
-def test_browser_result_crossing_a_takeover_is_discarded(monkeypatch):
- commands: list = []
- browser, session = _wire(monkeypatch, commands)
+def test_run_fenced_discards_a_result_crossing_a_takeover():
+ from tools.browser_session import run_fenced
- def spawn_then_takeover(*args):
+ def run_then_takeover():
lease.acquire("human-viewer")
lease.release("human-viewer") # a full cycle, control is back — the frame is still theirs
return {"success": True, "data": {"secret": "WHAT-THE-HUMAN-TYPED"}}
- monkeypatch.setattr(session, "_spawn_and_collect", spawn_then_takeover)
- result = browser.browser_click("e1", task_id="review")
- assert "WHAT-THE-HUMAN-TYPED" not in result
+ result = run_fenced({"session_name": "review", "cdp_url": None, "features": {"local": True}},
+ run_then_takeover)
+ assert "WHAT-THE-HUMAN-TYPED" not in json.dumps(result)
def test_real_profile_local_browser_is_fenced_by_provenance_even_without_a_live_display(monkeypatch):
@@ -118,48 +98,15 @@ def test_real_profile_local_browser_is_fenced_by_provenance_even_without_a_live_
DISPLAY, so it IS the human's browser: the fence keys on the ``local`` feature, not on the
transport. And a stranded human lease with the screen already down must still fence (computer_use
does), not silently unfence the browser."""
- commands: list = []
- browser, session = _wire(monkeypatch, commands)
- monkeypatch.setattr(session, "_get_session_info", lambda *a: {
- "session_name": "rp_1", "cdp_url": "ws://127.0.0.1:9222/devtools/browser/x",
- "features": {"local": True, "real_profile": True}})
+ from tools.browser_session import run_fenced
+
+ dispatched: list = []
monkeypatch.setattr(runtime, "published_env", dict)
lease.acquire("human-viewer")
- result = json.loads(browser.browser_click("e1", task_id="review"))
- assert commands == [], f"human holds the lease, yet a real-profile browser command was dispatched: {commands}"
- assert result.get("code") == "human_has_control"
-
-
-def test_browser_console_supervisor_fast_path_is_fenced_while_human_controls_shared_browser(monkeypatch):
- """`browser_console(expression=...)` answers over the CDP supervisor's WebSocket without ever reaching
- `_run_browser_command`, so the fence must sit in front of that fast path too — otherwise the one
- command that reads arbitrary page state is the one command the human's takeover does not stop."""
- import tools.browser_supervisor as supervisor_mod
-
- commands: list = []
- browser, _ = _wire(monkeypatch, commands)
- browser._active_sessions["review"] = {"session_name": "review", "cdp_url": "ws://127.0.0.1:9222/devtools/browser/x",
- "features": {"local": True}}
- evaluated: list = []
-
- class FakeSupervisor:
- def evaluate_runtime(self, expression, **_kw):
- evaluated.append(expression)
- return {"ok": True, "result": "WHAT-THE-HUMAN-TYPED", "result_type": "string"}
-
- class FakeRegistry:
- def get(self, task_id):
- return FakeSupervisor()
-
- monkeypatch.setattr(supervisor_mod, "SUPERVISOR_REGISTRY", FakeRegistry())
- try:
- lease.acquire("human-viewer")
- raw = browser.browser_console(expression="document.title", task_id="review")
- finally:
- browser._active_sessions.pop("review", None)
- result = json.loads(raw)
- assert evaluated == [] and commands == [], "human holds the lease, yet the page was evaluated"
- assert "WHAT-THE-HUMAN-TYPED" not in raw
+ result = run_fenced({"session_name": "rp_1", "cdp_url": "ws://127.0.0.1:9222/devtools/browser/x",
+ "features": {"local": True, "real_profile": True}},
+ lambda: dispatched.append("cmd") or {"success": True})
+ assert dispatched == [], f"human holds the lease, yet a real-profile browser command was dispatched: {dispatched}"
assert result.get("code") == "human_has_control"
@@ -167,10 +114,11 @@ def test_vault_page_operations_respect_the_human_lease(monkeypatch):
"""The vault tools reach the page over the supervisor socket, outside `_run_browser_command`: while a
human holds the screen they must be refused like every other page access, and never focus, inspect or
write to the form the human is typing into."""
- from tools import browser_tool as browser
+ from tools import browser_session
from tools import browser_vault_tool as vault
- browser._active_sessions["default"] = {"session_name": "review", "cdp_url": None, "features": {"local": True}}
+ monkeypatch.setitem(browser_session._active_sessions, "default",
+ {"session_name": "review", "cdp_url": None, "features": {"local": True}})
touched = []
for name in ("browser_vault_fill", "browser_vault_enter_code", "browser_vault_save_login"):
monkeypatch.setattr(vault, name, lambda *a, **k: touched.append(name) or json.dumps({"success": True}))
@@ -187,10 +135,11 @@ def test_secret_write_re_admits_after_a_takeover_during_the_code_prompt(monkeypa
"""`enter_code` blocks on the user's code INSIDE the handler fence. A takeover during that wait must
refuse the write itself: the outer fence only discards the result afterwards, and by then the code is
already in the page the human is typing into."""
- from tools import browser_tool as browser
+ from tools import browser_session
from tools import browser_vault_tool as vault
- browser._active_sessions["default"] = {"session_name": "review", "cdp_url": None, "features": {"local": True}}
+ monkeypatch.setitem(browser_session._active_sessions, "default",
+ {"session_name": "review", "cdp_url": None, "features": {"local": True}})
evaluated = []
class Sup:
diff --git a/tests/tools/test_bot_desktop_placement.py b/tests/tools/test_bot_desktop_placement.py
index 06eadf003a5..3522a2eb899 100644
--- a/tests/tools/test_bot_desktop_placement.py
+++ b/tests/tools/test_bot_desktop_placement.py
@@ -153,13 +153,32 @@ def _placed(monkeypatch, setting, backend):
monkeypatch.setattr(placement, "_terminal_backend", lambda: backend)
+def _local_sessions(monkeypatch) -> list:
+ """The session layer on a local backend with an empty cache; returns the HOST Chromium launches."""
+ from tools import browser_launcher, browser_session, browser_session_cdp, browser_session_cloud
+ from tools import browser_session_lifecycle
+
+ for name in ("_active_sessions", "_session_last_activity", "_session_owner_homes", "_cleanup_failures"):
+ monkeypatch.setattr(browser_session, name, {})
+ monkeypatch.setattr(browser_session_lifecycle, "start_cleanup_thread", lambda: None)
+ monkeypatch.setattr(browser_session_cdp, "get_cdp_override", lambda: "")
+ monkeypatch.setattr(browser_session_cloud, "get_cloud_provider", lambda: None)
+ monkeypatch.setattr("tools.browser_session_real_profile.real_profile_cdp", lambda: (None, None))
+ monkeypatch.setattr("tools.browser_lightpanda.using_lightpanda_engine", lambda: False)
+ host_launches: list = []
+ monkeypatch.setattr(browser_launcher, "launch_chromium",
+ lambda key, **kw: host_launches.append(key) or (None, "host Chromium must not start"))
+ return host_launches
+
+
def test_terminal_placement_starts_the_sandbox_screen_instead_of_running_on_the_host(monkeypatch, isolated_home):
"""The placement boundary is policy, not liveness: with ``placement: terminal`` and the screen not yet
- up, the browser preflight and the CUA invocation bring the sandbox screen up (no ``auto_start`` opt-in
+ up, the browser session and the CUA invocation bring the sandbox screen up (no ``auto_start`` opt-in
needed inside the user's own sandbox) and route there. Neither hands the tool a host command."""
- from tools import browser_tool_session as bts
+ from tools import browser_session, browser_session_sandbox
from tools.computer_use import cua_backend as cb
+ host_launches = _local_sessions(monkeypatch)
_placed(monkeypatch, "terminal", "docker")
started: list[str] = []
monkeypatch.setattr(runtime, "sandbox_screen_running", lambda: bool(started))
@@ -167,9 +186,14 @@ def test_terminal_placement_starts_the_sandbox_screen_instead_of_running_on_the_
monkeypatch.setattr(runtime, "start", lambda **kw: started.append("started"))
monkeypatch.setattr(runtime, "_sandbox_env", lambda *, create: _FakeDocker())
monkeypatch.setattr(runtime, "touch_activity", lambda: None)
+ monkeypatch.setattr(browser_session_sandbox, "create_sandbox_session", lambda key: {
+ "session_name": "sb_1", "cdp_url": "ws://127.0.0.1:45004/devtools/browser/abc",
+ "features": {"local": True, "sandbox": True}, "screen_up": bool(started)})
- assert bts._browser_command_preflight() == {"browser_cmd": "agent-browser"}
+ info = browser_session.get_session_info("t")
assert started == ["started"]
+ assert info["features"].get("sandbox") and info["screen_up"], "the sandbox browser starts after its screen"
+ assert host_launches == []
from tools.bot_desktop import sandbox_host
monkeypatch.setattr(sandbox_host, "_user_for", lambda e: "pn")
@@ -181,28 +205,33 @@ def test_terminal_placement_starts_the_sandbox_screen_instead_of_running_on_the_
def test_refused_placement_never_falls_back_to_the_host(monkeypatch, isolated_home):
- from tools import browser_tool_session as bts
+ from tools import browser_session
from tools.computer_use import cua_backend as cb
+ host_launches = _local_sessions(monkeypatch)
_placed(monkeypatch, "auto", "modal")
- res = bts._browser_command_preflight()
- assert res["success"] is False and "placement: gateway" in res["error"]
+ with pytest.raises(RuntimeError, match="placement: gateway"):
+ browser_session.get_session_info("t")
+ assert host_launches == [], "a refused placement launched the agent's browser on the gateway host"
with pytest.raises(RuntimeError, match="placement: gateway"):
cb.sandbox_mcp_invocation()
def test_sandbox_screen_that_cannot_come_up_is_an_error_not_a_host_browser(monkeypatch, isolated_home):
- from tools import browser_tool_session as bts
+ from tools import browser_session
+ host_launches = _local_sessions(monkeypatch)
_placed(monkeypatch, "terminal", "docker")
monkeypatch.setattr(runtime, "sandbox_screen_running", lambda: False)
monkeypatch.setattr(runtime, "published_env", dict)
+ monkeypatch.setattr(runtime, "_sandbox_env", lambda *, create: _FakeDocker())
def _boom(**kw):
raise RuntimeError("Bot Desktop needs Xvnc inside the terminal backend's sandbox")
monkeypatch.setattr(runtime, "start", _boom)
- res = bts._browser_command_preflight()
- assert res["success"] is False and "Xvnc" in res["error"]
+ with pytest.raises(RuntimeError, match="Xvnc"):
+ browser_session.get_session_info("t")
+ assert host_launches == []
def test_start_adopting_a_screen_the_sandbox_kept_records_the_marker(monkeypatch, isolated_home):
@@ -322,15 +351,26 @@ def test_forward_port_carries_bytes_both_ways_through_the_exec_stream(monkeypatc
def test_sandbox_cdp_endpoint_is_rewritten_to_the_forwarded_local_port(monkeypatch):
- from tools import browser_use_cli as buc
- from tools import browser_tool_session as bts
+ """The sandbox Chromium's DevTools port is the sandbox's loopback: the session hands browser_exec the
+ forwarded LOCAL port, keeping Chromium's browser id path."""
+ from tools import browser_session
+ from tools.bot_desktop import sandbox_host
- monkeypatch.setattr(bts, "_browser_in_sandbox", lambda: True)
+ host_launches = _local_sessions(monkeypatch)
+ _placed(monkeypatch, "terminal", "docker")
+ monkeypatch.setattr(runtime, "sandbox_screen_running", lambda: True)
+ monkeypatch.setattr(runtime, "published_env", lambda: {"DISPLAY": ":20"})
monkeypatch.setattr(runtime, "_sandbox_env", lambda *, create: _FakeDocker())
- from tools.bot_desktop import sandbox_host
monkeypatch.setattr(sandbox_host, "_user_for", lambda e: "pn")
+ monkeypatch.setattr(sandbox_host, "browser_profile_dir", lambda e: "/home/pn/.hermes/bot-desktop/browser-profile")
+
+ def run_in(env, argv, **_kw):
+ out = b"9223\n/devtools/browser/abc\n" if argv[0] == "cat" else b""
+ return subprocess.CompletedProcess(argv, 0, out, b"")
+ monkeypatch.setattr(streams, "run_in", run_in)
monkeypatch.setattr(streams, "forward_port", lambda env, port, *, remote_host="127.0.0.1", user=None: 45000 + port % 7)
- assert buc._reach_sandbox_cdp("ws://127.0.0.1:9223/devtools/browser/abc") == "ws://127.0.0.1:45004/devtools/browser/abc"
- assert buc._reach_sandbox_cdp("wss://cloud.example/session/1") == "wss://cloud.example/session/1"
- monkeypatch.setattr(bts, "_browser_in_sandbox", lambda: False)
- assert buc._reach_sandbox_cdp("ws://127.0.0.1:9223/x") == "ws://127.0.0.1:9223/x"
+
+ info = browser_session.get_session_info("t")
+ assert info["cdp_url"] == "ws://127.0.0.1:45004/devtools/browser/abc"
+ assert info["features"] == {"local": True, "sandbox": True}
+ assert host_launches == []
diff --git a/tests/tools/test_browser_real_profile.py b/tests/tools/test_browser_real_profile.py
index 615859193f7..5e4c1ce6ed9 100644
--- a/tests/tools/test_browser_real_profile.py
+++ b/tests/tools/test_browser_real_profile.py
@@ -8,15 +8,34 @@ are limited to OS detection and process launch.
"""
import json
import os
+from types import SimpleNamespace
from unittest.mock import Mock, patch
import pytest
-from tools import browser_tool_cdp as bt_cdp
-from tools import browser_tool_cloud as bt_cloud
-from tools import browser_tool_lightpanda_fallback as bt_lightpanda_fallback
-from tools import browser_tool_real_profile as bt_real_profile
-from tools import browser_tool_session as bt_session
-from tools import browser_tool_install as bt_install
+from tools import browser_launcher as launcher
+from tools import browser_lightpanda
+from tools import browser_session as bs
+from tools import browser_session_cloud as bs_cloud
+from tools import browser_session_real_profile as rp
+
+
[email protected](autouse=True)
+def _no_running_real_profile_browser(monkeypatch):
+ """Each test starts with no launched/attached browser; whatever a test registers is dropped after it
+ (never stopped: the registered pids are fakes)."""
+ monkeypatch.setattr(launcher, "_browsers", {})
+ monkeypatch.setattr(launcher, "_procs", {})
+
+
+def _fresh_local_launch(monkeypatch) -> list:
+ """The session layer's fresh-browser path with the launcher stubbed; returns ``(key, kwargs)`` per launch."""
+ launches: list = []
+ monkeypatch.setattr(bs, "browser_in_sandbox", lambda: False)
+ monkeypatch.setattr(bs, "ensure_screen_for_headed_chromium", lambda: None)
+ monkeypatch.setattr(browser_lightpanda, "using_lightpanda_engine", lambda: False)
+ monkeypatch.setattr(launcher, "launch_chromium", lambda key, **kw: launches.append((key, kw)) or (
+ SimpleNamespace(cdp_url="ws://127.0.0.1:41999/devtools/browser/fresh", pid=4242), None))
+ return launches
def _auth_db(path, value=None):
@@ -160,32 +179,25 @@ class TestSnapshotRealProfile:
class TestRealProfileCdpLaunch:
- """The agent-browser-based launcher in browser_tool_real_profile._real_profile_cdp."""
-
- def _reset(self):
- import tools.browser_tool as bt
- bt._real_profile_cdp_cache.clear()
+ """The launcher-based real-profile browser in browser_session_real_profile.real_profile_cdp."""
def test_consent_off_is_noop(self):
- self._reset()
- with patch.object(bt_cloud, "_use_real_profile", return_value=False):
- cdp, err = bt_real_profile._real_profile_cdp()
+ with patch.object(bs_cloud, "use_real_profile", return_value=False):
+ cdp, err = rp.real_profile_cdp()
assert cdp is None and err is None
def test_non_chromium_default_fails_closed(self):
- self._reset()
- with patch.object(bt_cloud, "_use_real_profile", return_value=True), \
+ with patch.object(bs_cloud, "use_real_profile", return_value=True), \
patch("hermes_cli.browser_connect.detect_default_chromium", return_value=None):
- cdp, err = bt_real_profile._real_profile_cdp()
+ cdp, err = rp.real_profile_cdp()
assert cdp is None
assert err
def test_snapshot_failure_fails_closed(self):
- self._reset()
- with patch.object(bt_cloud, "_use_real_profile", return_value=True), \
+ 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.snapshot_real_profile", return_value=(None, "boom")):
- cdp, err = bt_real_profile._real_profile_cdp()
+ cdp, err = rp.real_profile_cdp()
assert cdp is None
assert err and "boom" in err
@@ -193,21 +205,18 @@ class TestRealProfileCdpLaunch:
"""A timed-out worker holding the launch lock must not wedge later calls."""
import threading
- import tools.browser_tool as bt
-
- self._reset()
- monkeypatch.setattr(bt, "_REAL_PROFILE_CDP_LOCK_TIMEOUT_S", 0.05, raising=False)
+ monkeypatch.setattr(rp, "_LOCK_TIMEOUT_S", 0.05)
result = {}
started = threading.Event()
def resolve():
started.set()
- result.setdefault("value", bt_real_profile._real_profile_cdp())
+ result.setdefault("value", rp.real_profile_cdp())
- with patch.object(bt_cloud, "_use_real_profile", return_value=True), \
- patch.object(bt_lightpanda_fallback, "_using_lightpanda_engine", return_value=False), \
+ with patch.object(bs_cloud, "use_real_profile", return_value=True), \
+ patch.object(browser_lightpanda, "using_lightpanda_engine", return_value=False), \
patch("hermes_cli.browser_connect.detect_default_chromium", return_value=None):
- bt._real_profile_cdp_lock.acquire()
+ rp._lock.acquire()
worker = threading.Thread(target=resolve, daemon=True)
try:
worker.start()
@@ -215,7 +224,7 @@ class TestRealProfileCdpLaunch:
worker.join(timeout=2.0)
stalled = worker.is_alive()
finally:
- bt._real_profile_cdp_lock.release()
+ rp._lock.release()
worker.join(timeout=2.0)
assert not stalled, "real-profile resolver waited indefinitely on a stale holder"
@@ -223,293 +232,137 @@ class TestRealProfileCdpLaunch:
assert cdp is None
assert err and "already being prepared" in err
+ def test_launch_is_headless_on_the_real_binary_and_keeps_the_keychain(self, tmp_path, monkeypatch):
+ """Real-profile browsing runs headless (no focus-stealing window) on the user's REAL binary, on the
+ profile COPY, through the launcher.
- def test_launch_is_headless_and_agent_browser_attaches(self, tmp_path):
- """Real-profile browsing runs headless (no focus-stealing window).
-
- Two argv paths are checked:
-
- 1. The REAL Chrome binary we launch ourselves (via Popen) MUST pass
- ``--headless=new``. Real-profile browsing is a background
- capability — a visible window that grabs focus every turn defeats
- the point. NEW headless shares the profile's normal cookie store
- (unlike legacy ``--headless``), and cookie decryption is unaffected
- by headless — the drop we avoid comes from ``--use-mock-keychain``,
- not from headless. We launch without mock-keychain switches, so the
- copied auth/login state still loads.
- 2. agent-browser ATTACHES to that running Chrome via ``--cdp``, so its
- argv must contain ``--cdp`` and must NOT contain launch-mode
- switches (``--headless`` / ``--profile``).
+ ``--headless=new`` shares the profile's normal cookie store (unlike legacy ``--headless``), and
+ cookie decryption is unaffected by headless — the drop we avoid comes from ``--use-mock-keychain`` /
+ ``--password-store=basic``, so neither may reach this launch: the copied auth/login state still
+ loads. The copy is persistent: the launch must never wipe it like an ephemeral profile.
"""
- import tools.browser_tool as bt
- self._reset()
+ copy_dir = tmp_path / "copy"
+ (copy_dir / "Default").mkdir(parents=True)
+ (copy_dir / "Default" / "Cookies").write_text("copied-cookies", encoding="utf-8")
+ records = tmp_path / "records"
+ records.mkdir()
+ monkeypatch.setattr(launcher, "_records_dir", lambda: records)
+ monkeypatch.setattr(launcher, "_start_time", lambda pid: None)
+ monkeypatch.setattr("tools.browser_session_cloud.chromium_args", list)
+ monkeypatch.setattr(launcher, "needs_chromium_sandbox_bypass", lambda: False)
captured = {}
- def fake_agent_browser_spawn(argv, env, socket_dir, tag):
- captured["argv"] = argv
- captured["env"] = env
- return Mock(wait=Mock(return_value=0), returncode=0)
-
class FakeChrome:
- def poll(self):
- return None
-
- def fake_popen(argv, **kw):
- captured["chrome_argv"] = argv
- (tmp_path / "DevToolsActivePort").write_text("41000\n/devtools/browser/x\n", encoding="utf-8")
- return FakeChrome()
+ pid = 2147483000
- with patch.object(bt_cloud, "_use_real_profile", return_value=True), \
- patch("hermes_cli.browser_connect.detect_default_chromium", return_value="chrome"), \
- patch("hermes_cli.browser_connect.snapshot_real_profile", return_value=(str(tmp_path), None)), \
- patch("hermes_cli.browser_connect.chromium_executable", return_value="/usr/bin/chrome"), \
- patch.object(bt.subprocess, "Popen", side_effect=fake_popen), \
- patch.object(bt_real_profile, "_agent_browser_get_cdp",
- side_effect=[None, "http://127.0.0.1:41000"]), \
- patch.object(bt_install, "_find_agent_browser", return_value="/usr/bin/agent-browser"), \
- patch.object(bt_session, "_popen_agent_browser", side_effect=fake_agent_browser_spawn), \
- patch.object(bt, "_socket_safe_tmpdir", return_value=str(tmp_path)), \
- patch.object(bt_cloud, "_is_headed_mode", return_value=False):
- bt_real_profile._real_profile_cdp()
- # The chrome launch itself is headless (no window, no focus steal).
- assert "--headless=new" in captured["chrome_argv"]
- # agent-browser attaches, it does not launch.
- assert "--headless" not in captured["argv"]
- assert "--profile" not in captured["argv"]
- assert "--cdp" in captured["argv"]
- # #100855: the attach daemon lives in a reaper-visible socket dir claimed by this
- # process, and never self-terminates (Chrome is ours, not the daemon's).
- socket_dir = captured["env"]["AGENT_BROWSER_SOCKET_DIR"]
- assert socket_dir == str(tmp_path / f"agent-browser-{bt._REAL_PROFILE_SESSION}")
- assert (tmp_path / f"agent-browser-{bt._REAL_PROFILE_SESSION}" / f"{bt._REAL_PROFILE_SESSION}.owner_pid").read_text(encoding="utf-8-sig") == str(os.getpid())
- assert "AGENT_BROWSER_IDLE_TIMEOUT_MS" not in captured["env"]
- self._reset()
-
- def test_reuses_only_session_on_our_copy_dir(self, tmp_path):
- """A live session on a DIFFERENT dir (stale/throwaway) is closed, not reused."""
- import tools.browser_tool as bt
- self._reset()
- proc = Mock(return_value=None, returncode=0, stdout="", stderr="")
- closed = {"n": 0}
-
- class FakeChrome:
def poll(self):
return None
- def fake_popen(argv, **kw):
- (tmp_path / "DevToolsActivePort").write_text("41000\n/devtools/browser/x\n", encoding="utf-8")
+ def wait(self, timeout=None):
+ return 0
+
+ def fake_spawn(argv, env, user_data_dir):
+ captured["argv"] = argv
+ (copy_dir / "DevToolsActivePort").write_text("41000\n/devtools/browser/x\n", encoding="utf-8")
return FakeChrome()
- with patch.object(bt_cloud, "_use_real_profile", return_value=True), \
+ 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.snapshot_real_profile", return_value=(str(tmp_path), None)), \
+ patch("hermes_cli.browser_connect.real_profile_copy_dir", return_value=str(copy_dir)), \
+ patch("hermes_cli.browser_connect.snapshot_real_profile", return_value=(str(copy_dir), None)), \
patch("hermes_cli.browser_connect.chromium_executable", return_value="/usr/bin/chrome"), \
- patch.object(bt.subprocess, "Popen", side_effect=fake_popen), \
- patch.object(bt_real_profile, "_agent_browser_get_cdp",
- side_effect=["http://127.0.0.1:5000", "http://127.0.0.1:41000"]), \
- patch.object(bt_real_profile, "_cdp_http_ready", return_value=True), \
- patch.object(bt_real_profile, "_cdp_on_data_dir", return_value=False), \
- patch.object(bt_real_profile, "_agent_browser_close_session",
- side_effect=lambda s: closed.__setitem__("n", closed["n"] + 1)), \
- patch.object(bt_install, "_find_agent_browser", return_value="/usr/bin/agent-browser"), \
- patch.object(bt_real_profile, "_capture_agent_browser_cli", return_value=proc), \
- patch.object(bt_cloud, "_is_headed_mode", return_value=False):
- cdp, _err = bt_real_profile._real_profile_cdp()
- assert closed["n"] == 1 # stale wrong-dir session was closed
- assert cdp == "http://127.0.0.1:41000"
- self._reset()
+ patch.object(launcher, "_spawn", side_effect=fake_spawn), \
+ patch.object(bs_cloud, "is_headed_mode", return_value=False):
+ cdp, err = rp.real_profile_cdp()
+ assert (cdp, err) == ("ws://127.0.0.1:41000/devtools/browser/x", None)
+ argv = captured["argv"]
+ assert argv[0] == "/usr/bin/chrome" # the user's real binary, not the packaged Chromium
+ assert f"--user-data-dir={copy_dir}" in argv
+ # The chrome launch itself is headless (no window, no focus steal).
+ assert "--headless=new" in argv
+ assert "--password-store=basic" not in argv and "--use-mock-keychain" not in argv
+ assert (copy_dir / "Default" / "Cookies").read_text(encoding="utf-8") == "copied-cookies"
+ running = launcher.get_browser(rp.REAL_PROFILE_KEY)
+ assert running is not None and running.owned and not running.ephemeral
+ @pytest.mark.platforms("posix")
@pytest.mark.parametrize("live_browser_id", ["/devtools/browser/x", "/devtools/browser/other"])
def test_reattaches_to_surviving_chrome_instead_of_overlaying_its_profile(self, tmp_path, live_browser_id):
- """The attach daemon of a crashed owner gets reaped, but its Chrome (Hermes-launched,
- own session) survives holding the copy dir: re-attach, never re-run the snapshot.
- A DevToolsActivePort left by a crash whose port was recycled by ANOTHER CDP server
- (browser id mismatch) must not be attached to; the normal launch path runs."""
- self._reset()
+ """A Chrome from an earlier Hermes process can survive holding the copy dir: attach to it (never
+ owned, so never killed), never re-run the snapshot over its open databases. A DevToolsActivePort left
+ by a crash whose port was recycled by ANOTHER CDP server (browser id mismatch) must not be attached
+ to; the normal launch path runs."""
(tmp_path / "DevToolsActivePort").write_text("41000\n/devtools/browser/x\n", encoding="utf-8")
+ os.symlink(f"host-{os.getpid()}", tmp_path / "SingletonLock")
version = Mock()
version.json.return_value = {"webSocketDebuggerUrl": f"ws://127.0.0.1:41000{live_browser_id}"}
- with patch.object(bt_cloud, "_use_real_profile", return_value=True), \
+ 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="/usr/bin/chrome"), \
patch("hermes_cli.browser_connect.snapshot_real_profile", return_value=(None, "boom")) as snapshot, \
- patch("requests.get", return_value=version), \
- patch.object(bt_real_profile, "_agent_browser_get_cdp", return_value=None), \
- patch.object(bt_real_profile, "_attach_agent_browser_to_real_profile",
- return_value=("http://127.0.0.1:41000", None)) as attach:
- cdp, err = bt_real_profile._real_profile_cdp()
+ patch("requests.get", return_value=version):
+ cdp, err = rp.real_profile_cdp()
if live_browser_id == "/devtools/browser/x":
- assert (cdp, err) == ("http://127.0.0.1:41000", None)
- attach.assert_called_once_with(41000, str(tmp_path))
+ 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
else:
- attach.assert_not_called()
snapshot.assert_called_once()
- self._reset()
-
- def test_cdp_on_data_dir_matches_devtoolsactiveport(self, tmp_path):
- (tmp_path / "DevToolsActivePort").write_text("41000\n/devtools/browser/x\n", encoding="utf-8")
- assert bt_real_profile._cdp_on_data_dir("http://127.0.0.1:41000", str(tmp_path))
- assert not bt_real_profile._cdp_on_data_dir("http://127.0.0.1:9999", str(tmp_path))
-
-
-class TestAgentBrowserCliCapture:
- """#96731: agent-browser's resident daemon inherits the caller's stdio and
- outlives the CLI, so pipe-based capture never sees EOF after the CLI
- exits. Capture must go through temp files and wait only for the CLI."""
-
- STUB_GRANDCHILD = (
- "import subprocess, sys\n"
- # A grandchild that inherits stdout and outlives the CLI — exactly
- # what agent-browser's first-use daemon spawn does.
- "subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)'])\n"
- "sys.stdout.write('ws://127.0.0.1:41022/devtools/browser/stub\\n')\n"
- "sys.stderr.write('daemon warm\\n')\n"
- )
-
- def test_get_cdp_returns_despite_grandchild_holding_stdio(self, tmp_path):
- """The blocking frame from the #96731 py-spy capture: get cdp-url."""
- import sys
- import time
-
- stub = tmp_path / "agent_browser_daemon_stub.py"
- stub.write_text(self.STUB_GRANDCHILD, encoding="utf-8")
- with patch.object(bt_install, "_find_agent_browser", return_value=str(stub)), \
- patch.object(bt_session, "_agent_browser_argv", return_value=[sys.executable, str(stub)]), \
- patch.object(bt_real_profile, "_real_profile_daemon_env", return_value=({}, str(tmp_path))):
- start = time.monotonic()
- cdp = bt_real_profile._agent_browser_get_cdp("hermes-real-profile")
- elapsed = time.monotonic() - start
-
- assert cdp == "http://127.0.0.1:41022"
- # Pipe capture would stall here for the full 15s timeout on POSIX and
- # hang past the outer tool deadline on Windows.
- assert elapsed < 10, f"get cdp-url stalled {elapsed:.1f}s behind a grandchild"
-
- @pytest.mark.platforms("linux")
- def test_get_cdp_cleans_capture_files_despite_grandchild(self, tmp_path):
- """POSIX: the capture files are unlinked even while the daemon
- grandchild still holds them open. On Windows the inherited handles
- keep the files until the daemon exits and the unlink is best-effort
- by design (_unlink_command_output_files swallows OSError), so this
- assertion is a linux_only test rather than a bare sys.platform check
- — the contract stays visible in both CI lanes."""
- import sys
-
- stub = tmp_path / "agent_browser_daemon_stub.py"
- stub.write_text(self.STUB_GRANDCHILD, encoding="utf-8")
- with patch.object(bt_install, "_find_agent_browser", return_value=str(stub)), \
- patch.object(bt_session, "_agent_browser_argv", return_value=[sys.executable, str(stub)]), \
- patch.object(bt_real_profile, "_real_profile_daemon_env", return_value=({}, str(tmp_path))):
- cdp = bt_real_profile._agent_browser_get_cdp("hermes-real-profile")
-
- assert cdp == "http://127.0.0.1:41022"
- assert not list(tmp_path.glob("_std*_rp-*"))
-
- def test_capture_cli_surfaces_stdout_stderr_and_exit_code(self, tmp_path):
- import sys
-
- stub = tmp_path / "agent_browser_echo_stub.py"
- stub.write_text(
- "import sys\n"
- "sys.stdout.write('out-42\\n')\n"
- "sys.stderr.write('err-7\\n')\n"
- "sys.exit(3)\n"
- )
- with patch.object(bt_real_profile, "_real_profile_daemon_env", return_value=({}, str(tmp_path))):
- proc = bt_real_profile._capture_agent_browser_cli(
- [sys.executable, str(stub)], timeout=15, tag="rp-test",
- )
- assert proc.returncode == 3
- assert proc.stdout == "out-42"
- assert proc.stderr == "err-7"
-
- def test_capture_cli_timeout_kills_cli_without_stall(self, tmp_path):
- import subprocess
- import sys
- import time
-
- stub = tmp_path / "agent_browser_sleep_stub.py"
- stub.write_text("import time; time.sleep(30)\n", encoding="utf-8")
- with patch.object(bt_real_profile, "_real_profile_daemon_env", return_value=({}, str(tmp_path))):
- start = time.monotonic()
- with pytest.raises(subprocess.TimeoutExpired):
- bt_real_profile._capture_agent_browser_cli(
- [sys.executable, str(stub)], timeout=2, tag="rp-timeout",
- )
- elapsed = time.monotonic() - start
-
- # The CLI itself is killed at the deadline instead of draining pipes
- # behind a daemon grandchild forever.
- assert elapsed < 10, f"timeout path stalled {elapsed:.1f}s"
-
- @pytest.mark.platforms("linux")
- def test_capture_cli_timeout_cleans_capture_files(self, tmp_path):
- """POSIX: the capture files are unlinked after the timeout kill. On
- Windows the killed CLI's handles can outlive the kill() return, so
- the best-effort unlink may hit a still-open file and leave the
- fixed-name pair behind (bounded: reused and truncated by the next
- call with the same tag) — hence linux_only, not an inline
- sys.platform guard."""
- import subprocess
- import sys
-
- stub = tmp_path / "agent_browser_sleep_stub.py"
- stub.write_text("import time; time.sleep(30)\n", encoding="utf-8")
- with patch.object(bt_real_profile, "_real_profile_daemon_env", return_value=({}, str(tmp_path))):
- with pytest.raises(subprocess.TimeoutExpired):
- bt_real_profile._capture_agent_browser_cli(
- [sys.executable, str(stub)], timeout=2, tag="rp-timeout",
- )
-
- assert not (tmp_path / "_stdout_rp-timeout").exists()
- assert not (tmp_path / "_stderr_rp-timeout").exists()
+ assert cdp is None and "boom" in err
class TestConsentConfigRead:
- """Unmocked config read: _use_real_profile against a real config.yaml."""
+ """Unmocked config read: use_real_profile against a real config.yaml."""
def test_consent_default_off(self):
with patch("hermes_cli.config.read_raw_config", return_value={}):
- assert bt_cloud._use_real_profile() is False
+ assert bs_cloud.use_real_profile() is False
def test_consent_revocation_takes_effect_immediately(self):
"""No process-lifetime caching: consent is a per-use read."""
with patch("hermes_cli.config.read_raw_config",
return_value={"browser": {"use_real_profile": True}}):
- assert bt_cloud._use_real_profile() is True
+ assert bs_cloud.use_real_profile() is True
with patch("hermes_cli.config.read_raw_config",
return_value={"browser": {"use_real_profile": False}}):
- assert bt_cloud._use_real_profile() is False
+ assert bs_cloud.use_real_profile() is False
class TestLocalSessionRealProfile:
- def test_local_session_attaches_to_real_profile_cdp(self):
- with patch.object(bt_real_profile, "_real_profile_cdp",
- return_value=("http://127.0.0.1:9251", None)), \
- patch.object(bt_cdp, "_resolve_cdp_override", side_effect=lambda u: u):
- info = bt_session._create_local_session("t1")
- assert info["cdp_url"] == "http://127.0.0.1:9251"
+ def test_local_session_attaches_to_real_profile_cdp(self, monkeypatch):
+ launches = _fresh_local_launch(monkeypatch)
+ with patch.object(rp, "real_profile_cdp", return_value=("ws://127.0.0.1:9251/devtools/browser/rp", None)):
+ info = bs._create_local_session("t1")
+ assert info["cdp_url"] == "ws://127.0.0.1:9251/devtools/browser/rp"
assert info["features"]["real_profile"] is True
assert info["session_name"].startswith("rp_")
+ assert launches == []
- def test_local_session_falls_back_to_a_fresh_browser_on_error(self):
+ def test_local_session_falls_back_to_a_fresh_browser_on_error(self, monkeypatch):
"""A real profile that can't load (Chrome holding its cookies, non-Chromium default) must
not leave the user with no browser: a fresh one serves and carries the reason."""
- with patch.object(bt_real_profile, "_real_profile_cdp", return_value=(None, "no chromium")):
- info = bt_session._create_local_session("t1")
- assert info["cdp_url"] is None and info["session_name"].startswith("h_")
+ launches = _fresh_local_launch(monkeypatch)
+ with patch.object(rp, "real_profile_cdp", return_value=(None, "no chromium")):
+ info = bs._create_local_session("t1")
+ assert info["cdp_url"] == "ws://127.0.0.1:41999/devtools/browser/fresh"
+ assert info["session_name"].startswith("h_")
assert "real_profile" not in info["features"]
assert "no chromium" in info["real_profile_unavailable"]
assert "without the user's logins" in info["real_profile_unavailable"]
+ assert [key for key, _kw in launches] == ["t1"]
- def test_local_session_without_consent_is_throwaway(self):
- with patch.object(bt_real_profile, "_real_profile_cdp", return_value=(None, None)):
- info = bt_session._create_local_session("t1")
- assert info["cdp_url"] is None
+ def test_local_session_without_consent_is_throwaway(self, monkeypatch):
+ launches = _fresh_local_launch(monkeypatch)
+ with patch.object(rp, "real_profile_cdp", return_value=(None, None)):
+ info = bs._create_local_session("t1")
+ assert info["cdp_url"] == "ws://127.0.0.1:41999/devtools/browser/fresh"
assert "real_profile" not in info["features"]
assert info["session_name"].startswith("h_")
+ assert "real_profile_unavailable" not in info
+ assert [key for key, _kw in launches] == ["t1"]
class TestBrowserExecLocalArg:
@@ -520,9 +373,9 @@ class TestBrowserExecLocalArg:
import tools.browser_use_cli as bu
env = self._env()
with patch.object(bu, "_real_profile_consented", return_value=True), \
- patch("tools.browser_tool_cdp._get_cdp_override_raw", return_value=""), \
- patch("tools.browser_tool_cloud._get_cloud_provider", return_value=Mock()), \
- patch("tools.browser_tool_real_profile._real_profile_cdp",
+ patch("tools.browser_session_cdp.get_cdp_override_raw", return_value=""), \
+ patch("tools.browser_session_cloud.get_cloud_provider", return_value=Mock()), \
+ patch("tools.browser_session_real_profile.real_profile_cdp",
return_value=("http://127.0.0.1:9251", None)):
err = bu._resolve_real_profile_cdp(env, force_local=True)
assert err is None
@@ -532,8 +385,8 @@ class TestBrowserExecLocalArg:
import tools.browser_use_cli as bu
env = self._env()
with patch.object(bu, "_real_profile_consented", return_value=True), \
- patch("tools.browser_tool_cdp._get_cdp_override_raw", return_value=""), \
- patch("tools.browser_tool_cloud._get_cloud_provider", return_value=Mock()):
+ patch("tools.browser_session_cdp.get_cdp_override_raw", return_value=""), \
+ patch("tools.browser_session_cloud.get_cloud_provider", return_value=Mock()):
err = bu._resolve_real_profile_cdp(env, force_local=False)
assert err is None
assert "BU_CDP_URL" not in env and "BU_CDP_WS" not in env
@@ -543,9 +396,9 @@ class TestBrowserExecLocalArg:
env = self._env()
with patch.object(bu, "_real_profile_consented", return_value=True), \
patch.object(bu, "_read_browser_cfg", return_value={}), \
- patch("tools.browser_tool_cdp._get_cdp_override_raw", return_value=""), \
- patch("tools.browser_tool_cloud._get_cloud_provider", return_value=None), \
- patch("tools.browser_tool_real_profile._real_profile_cdp",
+ patch("tools.browser_session_cdp.get_cdp_override_raw", return_value=""), \
+ patch("tools.browser_session_cloud.get_cloud_provider", return_value=None), \
+ patch("tools.browser_session_real_profile.real_profile_cdp",
return_value=("http://127.0.0.1:9251", None)):
err = bu._resolve_real_profile_cdp(env, force_local=False)
assert err is None
@@ -562,8 +415,8 @@ class TestBrowserExecLocalArg:
import tools.browser_use_cli as bu
env = self._env()
with patch.object(bu, "_real_profile_consented", return_value=True), \
- patch("tools.browser_tool_cdp._get_cdp_override_raw", return_value=""), \
- patch("tools.browser_tool_real_profile._real_profile_cdp",
+ patch("tools.browser_session_cdp.get_cdp_override_raw", return_value=""), \
+ patch("tools.browser_session_real_profile.real_profile_cdp",
return_value=(None, "chrome exited")):
err = bu._resolve_real_profile_cdp(env, force_local=True)
assert err == "chrome exited"
@@ -576,9 +429,9 @@ class TestBrowserExecLocalArg:
env = self._env()
rp = Mock(return_value=(None, "chrome holds the Cookies"))
with patch.object(bu, "_real_profile_consented", return_value=True), \
- patch("tools.browser_tool_cdp._get_cdp_override_raw", return_value=""), \
- patch("tools.browser_tool_cloud._get_cloud_provider", return_value=Mock()), \
- patch("tools.browser_tool_real_profile._real_profile_cdp", rp), \
+ patch("tools.browser_session_cdp.get_cdp_override_raw", return_value=""), \
+ patch("tools.browser_session_cloud.get_cloud_provider", return_value=Mock()), \
+ patch("tools.browser_session_real_profile.real_profile_cdp", rp), \
patch.object(bu, "_resolve_backend_cdp", return_value=None) as backend:
assert bu._route_backend(env, "", "t1", True) is None
assert "chrome holds the Cookies" in env[bu._REAL_PROFILE_FALLBACK_SENTINEL]
@@ -600,7 +453,7 @@ class TestBrowserExecLocalArg:
import tools.browser_use_cli as bu
env = self._env()
with patch.object(bu, "_real_profile_consented", return_value=True), \
- patch("tools.browser_tool_cdp._get_cdp_override_raw", return_value="ws://connect"):
+ patch("tools.browser_session_cdp.get_cdp_override_raw", return_value="ws://connect"):
err = bu._resolve_real_profile_cdp(env, force_local=True)
assert err is None and env == {}
@@ -674,19 +527,18 @@ class TestChannelIdentity:
assert not any(chan.startswith(p) for p, _ in bc._WINDOWS_PROGID_MAP)
def test_channel_sentinel_fails_closed_in_cdp(self):
- """A channel default → _real_profile_cdp fails closed, never launches."""
- import tools.browser_tool as bt
+ """A channel default → real_profile_cdp fails closed, never launches."""
import hermes_cli.browser_connect as bc
- bt._real_profile_cdp_cache.clear()
- with patch.object(bt_cloud, "_use_real_profile", return_value=True), \
+ with patch.object(bs_cloud, "use_real_profile", return_value=True), \
patch("hermes_cli.browser_connect.detect_default_chromium",
return_value=bc.UNSUPPORTED_CHANNEL), \
- patch("hermes_cli.browser_connect.snapshot_real_profile") as snap:
- cdp, err = bt_real_profile._real_profile_cdp()
+ patch("hermes_cli.browser_connect.snapshot_real_profile") as snap, \
+ patch.object(launcher, "launch_chromium") as launch:
+ cdp, err = rp.real_profile_cdp()
assert cdp is None
assert err
snap.assert_not_called() # never even snapshotted a stable profile
- bt._real_profile_cdp_cache.clear()
+ launch.assert_not_called()
def test_data_dir_rejects_sentinel(self):
import hermes_cli.browser_connect as bc
@@ -780,15 +632,17 @@ class TestReviewBugFixes:
assert _auth_db(home / "browser-profile" / "chrome" / "Default" / "Cookies") == "PROFILE6-REFRESHED"
# ── Bug 3: private-URL sidecar must NOT carry the real profile ──
- def test_sidecar_never_uses_real_profile(self):
+ def test_sidecar_never_uses_real_profile(self, monkeypatch):
# Even with consent resolving a real-profile CDP, the sidecar path
# (allow_real_profile=False) must return a throwaway session.
- with patch.object(bt_real_profile, "_real_profile_cdp",
- return_value=("http://127.0.0.1:9251", None)):
- info = bt_session._create_local_session("t::local", allow_real_profile=False)
- assert info["cdp_url"] is None
+ launches = _fresh_local_launch(monkeypatch)
+ with patch.object(rp, "real_profile_cdp",
+ return_value=("ws://127.0.0.1:9251/devtools/browser/rp", None)):
+ info = bs._create_local_session("t::local", allow_real_profile=False)
+ assert info["cdp_url"] == "ws://127.0.0.1:41999/devtools/browser/fresh"
assert "real_profile" not in info["features"]
assert info["session_name"].startswith("h_")
+ assert [key for key, _kw in launches] == ["t::local"]
@@ -807,16 +661,13 @@ class TestReviewBugFixes:
# ── Bug 5: lightpanda engine + consent fails with an actionable message ──
def test_lightpanda_engine_fails_actionably(self):
- import tools.browser_tool as bt
- bt._real_profile_cdp_cache.clear()
- with patch.object(bt_cloud, "_use_real_profile", return_value=True), \
- patch.object(bt_lightpanda_fallback, "_using_lightpanda_engine", return_value=True), \
+ with patch.object(bs_cloud, "use_real_profile", return_value=True), \
+ patch.object(browser_lightpanda, "using_lightpanda_engine", return_value=True), \
patch("hermes_cli.browser_connect.detect_default_chromium") as det:
- cdp, err = bt_real_profile._real_profile_cdp()
+ cdp, err = rp.real_profile_cdp()
assert cdp is None
assert err and "lightpanda" in err.lower() and "browser.engine" in err.lower()
det.assert_not_called() # guard fires before detection
- bt._real_profile_cdp_cache.clear()
class TestReviewRound3:
@@ -1033,33 +884,30 @@ class TestReviewRound3:
def test_consent_off_triggers_cleanup(self, tmp_path, monkeypatch):
called = {"n": 0}
- with patch.object(bt_cloud, "_use_real_profile", return_value=False), \
+ with patch.object(bs_cloud, "use_real_profile", return_value=False), \
patch("hermes_cli.browser_connect.cleanup_real_profile_snapshots",
side_effect=lambda: called.__setitem__("n", called["n"] + 1)):
- cdp, err = bt_real_profile._real_profile_cdp()
+ cdp, err = rp.real_profile_cdp()
assert cdp is None and err is None
assert called["n"] == 1
# ── ① overlay must not run before the reuse check (live-browser safety) ──
def test_reuse_skips_snapshot_overlay(self, tmp_path):
- """When a live session on our copy dir is reused, snapshot_real_profile
+ """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."""
- import tools.browser_tool as bt
- bt._real_profile_cdp_cache.clear()
- with patch.object(bt_cloud, "_use_real_profile", return_value=True), \
- patch.object(bt_lightpanda_fallback, "_using_lightpanda_engine", return_value=False), \
+ 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), \
+ patch.object(browser_lightpanda, "using_lightpanda_engine", return_value=False), \
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.object(bt_real_profile, "_agent_browser_get_cdp", return_value="http://127.0.0.1:9251"), \
- patch.object(bt_real_profile, "_cdp_http_ready", return_value=True), \
- patch.object(bt_real_profile, "_cdp_on_data_dir", return_value=True), \
patch("hermes_cli.browser_connect.snapshot_real_profile") as snap:
- cdp, err = bt_real_profile._real_profile_cdp()
- assert cdp == "http://127.0.0.1:9251" and err is None
+ cdp, err = rp.real_profile_cdp()
+ assert cdp == "ws://127.0.0.1:9251/devtools/browser/rp" and err is None
snap.assert_not_called() # ← the fix: no overlay while a live browser owns the dir
- bt._real_profile_cdp_cache.clear()
-
class TestWindowsLockedProfileCopy:
diff --git a/tests/tools/test_hermes_subprocess_env.py b/tests/tools/test_hermes_subprocess_env.py
index 569a7f67856..07b2caac0e2 100644
--- a/tests/tools/test_hermes_subprocess_env.py
+++ b/tests/tools/test_hermes_subprocess_env.py
@@ -139,25 +139,25 @@ class TestTierInvariants:
class TestBrowserPassthroughPattern:
def test_browser_keys_recoverable_after_strip(self):
- """Browser tool pattern: strip everything, then re-add the browser
- backend keys agent-browser actually needs."""
- from tools.browser_tool import _BROWSER_PASSTHROUGH_KEYS
+ """browser_exec pattern: strip everything, then re-add only the key
+ the browser harness itself reads."""
+ from tools.browser_use_cli import _HARNESS_PASSTHROUGH_KEYS
leaked = {
+ "BROWSER_USE_API_KEY": "bu-key",
"BROWSERBASE_API_KEY": "bb-key",
- "BROWSERBASE_PROJECT_ID": "bb-proj",
- "FIRECRAWL_API_KEY": "fc-key",
"ANTHROPIC_API_KEY": "ant-should-go",
"TELEGRAM_BOT_TOKEN": "bot-should-go",
}
with patch.dict(os.environ, {**_SAFE_SAMPLE, **leaked}, clear=True):
env = hermes_subprocess_env(inherit_credentials=False)
- for key in _BROWSER_PASSTHROUGH_KEYS:
+ for key in _HARNESS_PASSTHROUGH_KEYS:
if key in os.environ:
env[key] = os.environ[key]
- assert env["BROWSERBASE_API_KEY"] == "bb-key"
- assert env["FIRECRAWL_API_KEY"] == "fc-key"
+ assert env["BROWSER_USE_API_KEY"] == "bu-key"
+ # Cloud-provider keys stay in-process (sessions are created over HTTP), never in the child.
+ assert "BROWSERBASE_API_KEY" not in env
# Provider + gateway secrets must NOT come back.
assert "ANTHROPIC_API_KEY" not in env
assert "TELEGRAM_BOT_TOKEN" not in env
diff --git a/tests/tools/test_model_tools.py b/tests/tools/test_model_tools.py
index 348fbe03602..23017f40021 100644
--- a/tests/tools/test_model_tools.py
+++ b/tests/tools/test_model_tools.py
@@ -413,7 +413,7 @@ class TestDisabledToolsetsPlatformBundle:
"is what lets `disabled_toolsets: [browser]` strip it (#64503)"
)
# browser still owns its own tools, and web/search still own web_search.
- assert "browser_navigate" in browser_tools
+ assert "browser_exec" in browser_tools
assert "web_search" in set(resolve_toolset("web"))
assert "web_search" in set(resolve_toolset("search"))
@@ -527,10 +527,9 @@ class TestBrowserRetrievalHints:
# Real static schemas + rewriters: the rewritten browser descriptions must not mention absent web tools.
from model_tools import _apply_dynamic_schemas
from tools.browser_cdp_tool import BROWSER_CDP_SCHEMA
- from tools.browser_tool import BROWSER_TOOL_SCHEMAS
+ from tools.browser_use_cli import BROWSER_EXEC_SCHEMA
- navigate = next(s for s in BROWSER_TOOL_SCHEMAS if s["name"] == "browser_navigate")
- defs = [{"type": "function", "function": navigate}, {"type": "function", "function": BROWSER_CDP_SCHEMA}]
+ defs = [{"type": "function", "function": BROWSER_EXEC_SCHEMA}, {"type": "function", "function": BROWSER_CDP_SCHEMA}]
rendered = " ".join(d["function"]["description"] for d in _apply_dynamic_schemas(defs + self._defs("terminal")))
assert "web_search" not in rendered
assert "web_extract" not in rendered
diff --git a/tests/tools/test_multiplex_tool_cache_scope.py b/tests/tools/test_multiplex_tool_cache_scope.py
index dcb08e279cd..17b2c24ee87 100644
--- a/tests/tools/test_multiplex_tool_cache_scope.py
+++ b/tests/tools/test_multiplex_tool_cache_scope.py
@@ -37,37 +37,12 @@ class _scoped:
@pytest.fixture
def two_homes(tmp_path, monkeypatch):
- a = _make_home(tmp_path / "A", {}, "CAMOFOX_URL=http://camofox-a:9377\n")
- b = _make_home(tmp_path / "A" / "profiles" / "B", {}, "CAMOFOX_URL=http://camofox-b:9377\n")
+ a = _make_home(tmp_path / "A", {})
+ b = _make_home(tmp_path / "A" / "profiles" / "B", {})
monkeypatch.setenv("HERMES_HOME", str(a))
- monkeypatch.delenv("CAMOFOX_URL", raising=False)
return a, b
-def test_camofox_vnc_memo_is_keyed_by_the_profiles_server_url(two_homes, monkeypatch):
- """The one-shot VNC probe must not answer B (own CAMOFOX_URL) with A's server address."""
- import tools.browser_camofox as cam
-
- class _Resp:
- status_code = 200
-
- def __init__(self, url):
- self._port = 6001 if "camofox-a" in url else 6002
-
- def json(self):
- return {"ok": True, "vncPort": self._port}
-
- monkeypatch.setattr(cam.requests, "get", lambda url, *a, **k: _Resp(url))
- a, b = two_homes
- with _scoped(a):
- assert cam.check_camofox_available() is True
- assert cam.get_vnc_url() == "http://camofox-a:6001"
- with _scoped(b):
- assert cam.get_vnc_url() == "http://camofox-b:6002"
- with _scoped(a):
- assert cam.get_vnc_url() == "http://camofox-a:6001"
-
-
def test_home_keyed_caches_serve_each_profile_its_own_config(tmp_path, monkeypatch):
"""One mechanism (dict keyed by home / override bypass) across the sites that read per-profile
config or per-home files: aux-vision routing, learned image cost table, aux
diff --git a/tests/tools/test_multiplex_tool_memo_scope.py b/tests/tools/test_multiplex_tool_memo_scope.py
index 7b78ca33262..b8402747653 100644
--- a/tests/tools/test_multiplex_tool_memo_scope.py
+++ b/tests/tools/test_multiplex_tool_memo_scope.py
@@ -16,12 +16,12 @@ from hermes_constants import reset_hermes_home_override, set_hermes_home_overrid
@pytest.fixture
def two_profiles(tmp_path, monkeypatch):
prof_a, prof_b = tmp_path / "profA", tmp_path / "profB"
- for home, limits in ((prof_a, (222, 33, 3300)), (prof_b, (888, 77, 7700))):
+ for home, limits in ((prof_a, (222, 33)), (prof_b, (888, 77))):
home.mkdir()
- max_bytes, timeout, threshold = limits
+ max_bytes, timeout = limits
(home / "config.yaml").write_text(
f"file_read_max_chars: {max_bytes}\ntool_output:\n max_bytes: {max_bytes}\n"
- f"browser:\n command_timeout: {timeout}\n snapshot_threshold: {threshold}\n",
+ f"browser:\n command_timeout: {timeout}\n",
encoding="utf-8")
monkeypatch.setenv("HERMES_HOME", str(prof_a))
return prof_a, prof_b
@@ -47,25 +47,23 @@ def test_checkpoint_and_snapshot_paths_follow_active_profile(two_profiles):
def test_config_caches_are_keyed_by_profile(two_profiles):
- import tools.browser_camofox as cam
- import tools.browser_tool as bt
+ import tools.browser_session_cloud as bsc
import tools.file_tools as ft
import tools.tool_output_limits as tol
- from tools.browser_tool_lifecycle import cleanup_all_browsers
+ from tools.browser_session_lifecycle import cleanup_all_browsers
prof_a, prof_b = two_profiles
tol._reset_tool_output_limits_cache()
cleanup_all_browsers()
- cam._cmd_timeout_resolved, cam._cached_cmd_timeout = False, None
+ bsc.reset_caches()
def read_all():
- return (tol.get_tool_output_limits()["max_bytes"], ft._get_max_read_chars(),
- bt._get_command_timeout(), bt.get_browser_snapshot_threshold(), cam._get_command_timeout())
+ return (tol.get_tool_output_limits()["max_bytes"], ft._get_max_read_chars(), bsc.command_timeout())
- assert _under(prof_a, read_all) == (222, 222, 33, 3300, 33)
- assert _under(prof_b, read_all) == (888, 888, 77, 7700, 77)
+ assert _under(prof_a, read_all) == (222, 222, 33)
+ assert _under(prof_b, read_all) == (888, 888, 77)
# Per-profile slots stay hot — switching back is not a single-slot ping-pong.
- assert _under(prof_a, read_all) == (222, 222, 33, 3300, 33)
+ assert _under(prof_a, read_all) == (222, 222, 33)
def test_skill_manage_schema_stable_but_creation_follows_active_profile(two_profiles):
diff --git a/tests/tools/test_multiplex_turn_parity.py b/tests/tools/test_multiplex_turn_parity.py
index 1d75f7ac0d6..abbccf81d01 100644
--- a/tests/tools/test_multiplex_turn_parity.py
+++ b/tests/tools/test_multiplex_turn_parity.py
@@ -129,8 +129,8 @@ def test_profile_scoped_process_caches_follow_routed_home(two_homes, monkeypatch
"""Config-derived singletons (redaction switch, aux unhealthy marks, LSP service, browser
engine/headed flags, MCP stderr log path) are keyed by the routed profile home."""
from agent import auxiliary_client, lsp, redact
- from tools import browser_tool_cloud, mcp_tool_config
- from tools.browser_tool_lifecycle import cleanup_all_browsers
+ from tools import browser_session_cloud, mcp_tool_config
+ from tools.browser_session_lifecycle import cleanup_all_browsers
a, b = two_homes
monkeypatch.setattr(redact, "_REDACT_ENABLED", False) # launch profile opted out
@@ -152,10 +152,10 @@ def test_profile_scoped_process_caches_follow_routed_home(two_homes, monkeypatch
lsp.shutdown_service()
cleanup_all_browsers()
- assert _under(a, browser_tool_cloud._get_browser_engine) == "chrome"
- assert _under(b, browser_tool_cloud._get_browser_engine) == "lightpanda"
- assert _under(a, browser_tool_cloud._is_headed_mode) is False
- assert _under(b, browser_tool_cloud._is_headed_mode) is True
+ assert _under(a, browser_session_cloud.get_browser_engine) == "auto" # "chrome" is an alias of auto
+ assert _under(b, browser_session_cloud.get_browser_engine) == "lightpanda"
+ assert _under(a, browser_session_cloud.is_headed_mode) is False
+ assert _under(b, browser_session_cloud.is_headed_mode) is True
mcp_tool_config._mcp_stderr_log_fh.clear()
try:
diff --git a/tests/tools/test_refresh_agent_mcp_tools.py b/tests/tools/test_refresh_agent_mcp_tools.py
index b2101d2f351..1b586aed0f0 100644
--- a/tests/tools/test_refresh_agent_mcp_tools.py
+++ b/tests/tools/test_refresh_agent_mcp_tools.py
@@ -384,18 +384,18 @@ def test_eviction_rebuild_restores_the_sessions_saved_tool_order(monkeypatch):
"""A fresh AIAgent for an EXISTING session must keep the saved tools[] pin.
Gateway agent-cache eviction rebuilds the agent; ``agent_init`` re-probes
- every ``check_fn`` and ``browser_navigate``'s flips false. The persisted
+ every ``check_fn`` and ``browser_exec``'s flips false. The persisted
name list stands in for the missing predecessor: the tool is carried
forward from the registry schema, byte-for-byte in its old slot.
"""
from tools import registry as registry_mod
- saved = ["read_file", "browser_navigate", "terminal"]
+ saved = ["read_file", "browser_exec", "terminal"]
entries = {n: types.SimpleNamespace(name=n, schema=_tool(n)["function"]) for n in saved}
monkeypatch.setattr(registry_mod.registry, "get_all_entries", lambda: list(entries.values()), raising=False)
monkeypatch.setattr(registry_mod.registry, "get_entry", lambda name, **kw: entries.get(name), raising=False)
- rebuilt = _agent(["read_file", "terminal"]) # probe flipped: browser_navigate gone
+ rebuilt = _agent(["read_file", "terminal"]) # probe flipped: browser_exec gone
changed = _mcp_agent.restore_agent_tool_prefix(rebuilt, saved)
assert changed is True
diff --git a/tests/tools/test_terminal_scope_multiplex.py b/tests/tools/test_terminal_scope_multiplex.py
index 502103d22e0..bc2b44c7577 100644
--- a/tests/tools/test_terminal_scope_multiplex.py
+++ b/tests/tools/test_terminal_scope_multiplex.py
@@ -24,7 +24,7 @@ from tools.terminal_scope import (
set_terminal_scope,
terminal_env,
)
-from tools import browser_tool_cloud as bt_cloud
+from tools import browser_session_cloud as bs_cloud
_LAUNCH_CWD = "/home/launch-user/private"
_LAUNCH_VOLUMES = '["/host/secret:/data:rw"]'
@@ -95,7 +95,7 @@ def test_routed_turn_reads_every_terminal_consumer_from_profile(
import tools.terminal_tool as tt
from agent import runtime_cwd
from gateway.platforms import base as gbase
- from tools import browser_tool, env_probe, file_tools_paths
+ from tools import env_probe, file_tools_paths
b_cwd = tmp_path / "b-work"
b_cwd.mkdir()
@@ -119,7 +119,7 @@ def test_routed_turn_reads_every_terminal_consumer_from_profile(
)
assert file_tools_paths._configured_terminal_cwd() == str(b_cwd)
assert runtime_cwd.resolve_agent_cwd() == b_cwd
- assert bt_cloud._is_local_backend() is True
+ assert bs_cloud.is_local_backend() is True
# env_probe bails out with "" for remote backends; a local profile
# must not be treated as remote just because the launch env is docker.
assert env_probe._resolve_terminal_backend() == "local"
diff --git a/tests/tools/test_zombie_process_cleanup.py b/tests/tools/test_zombie_process_cleanup.py
index 1207e18bdd7..625c72c1d3e 100644
--- a/tests/tools/test_zombie_process_cleanup.py
+++ b/tests/tools/test_zombie_process_cleanup.py
@@ -242,7 +242,7 @@ class TestGatewayCleanupWiring:
with patch("gateway.status.remove_pid_file"), \
patch("gateway.status.write_runtime_status"), \
patch("tools.terminal_tool.cleanup_all_environments"), \
- patch("tools.browser_tool_lifecycle.cleanup_all_browsers"):
+ patch("tools.browser_session_lifecycle.cleanup_all_browsers"):
loop.run_until_complete(GatewayRunner.stop(runner))
finally:
loop.close()