The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(bot-screen): dock Browser picks a browser that can start, and status says when there is none
teknium1dff8929194f8
diff --git a/tests/tools/test_bot_desktop_browser.py b/tests/tools/test_bot_desktop_browser.pyindex 451702e2c4f..be1bc8adf33 100644--- a/tests/tools/test_bot_desktop_browser.py+++ b/tests/tools/test_bot_desktop_browser.py@@ -89,3 +89,71 @@ def test_agent_attaches_to_human_started_browser(monkeypatch):monkeypatch.setattr(browser, "running_instance_cdp_port", lambda d, **kw: None)session._run_browser_command_unfenced("t", "open", ["https://x"], 10, None, "agent-browser", info)assert "--cdp" not in argvs[-1] and argvs[-1][:3] == ["agent-browser", "--session", "h_abc"]+++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)+ roots = tmp_path / "pw"+ roots.mkdir(parents=True)+ monkeypatch.setenv("PLAYWRIGHT_BROWSERS_PATH", str(roots))+ monkeypatch.setattr("tools.browser_tool_install._chromium_search_roots", lambda: [str(roots)])+ pw_exe = roots / "chromium-1200" / "chrome-linux" / "chrome"+ if playwright:+ pw_exe.parent.mkdir(parents=True)+ pw_exe.write_text("#!/bin/sh\n", encoding="utf-8")+ pw_exe.chmod(0o755)+ sys_exe = tmp_path / "bin" / "chromium"+ if system:+ sys_exe.parent.mkdir(parents=True)+ sys_exe.write_text("#!/bin/sh\n", encoding="utf-8")+ sys_exe.chmod(0o755)+ monkeypatch.setattr("shutil.which", lambda name, *a, **k: str(sys_exe) if system and name == "chromium" else None)+ return str(pw_exe), str(sys_exe)+++def test_unprivileged_user_under_apparmor_userns_restriction_gets_the_system_browser(tmp_path, monkeypatch):+ """Playwright's bundled Chromium has no setuid chrome_sandbox; with+ 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 (no --no-sandbox for non-root)."""+ 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)+ assert browser.executable() == sys_exe++ monkeypatch.setattr(browser, "_userns_restricted", lambda: False)+ assert browser.executable() == pw_exe # unrestricted host: Playwright's build as before++ _install_browsers(tmp_path / "only-pw", monkeypatch, playwright=True, system=False)+ monkeypatch.setattr(browser, "_userns_restricted", lambda: True)+ exe = browser.executable()+ assert exe and exe.endswith("chrome-linux/chrome")+ assert "--no-sandbox" not in browser.dock_command(exe, "/p/dir")+++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+ 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"+ assert agent_flags <= set(browser.dock_command("/opt/chrome", "/p/dir").split())+++def test_status_reports_the_headed_browser_or_its_absence(monkeypatch):+ """The official image ships only chromium_headless_shell: executable() is None and the dock silently+ has no Browser icon. Status must say so instead of leaving the pane to guess."""+ monkeypatch.setattr(runtime, "_launcher_pid", lambda: None)+ monkeypatch.setattr(runtime, "published_env", lambda: {})+ monkeypatch.setattr(runtime, "geometry", lambda: "1440x900")+ monkeypatch.setattr(browser, "executable", lambda: None)+ assert runtime.status().as_dict()["browser"] is None+ monkeypatch.setattr(browser, "executable", lambda: "/usr/bin/chromium")+ assert runtime.status().browser == "/usr/bin/chromium"diff --git a/tools/bot_desktop/browser.py b/tools/bot_desktop/browser.pyindex 1c4db251b2f..c20b90a0e77 100644--- a/tools/bot_desktop/browser.py+++ b/tools/bot_desktop/browser.py@@ -33,20 +33,43 @@ def profile_dir() -> Path:def executable() -> Optional[str]:"""The Chromium agent-browser launches: an explicit ``AGENT_BROWSER_EXECUTABLE_PATH``, else the newest- Playwright Chromium it bundles, else a system Chrome/Chromium. ``None`` when there is none."""+ Playwright Chromium it bundles, else a system Chrome/Chromium. ``None`` when there is none.++ Non-root under ``kernel.apparmor_restrict_unprivileged_userns=1`` (Ubuntu 23.10+) flips the order:+ Playwright's bundle has no setuid ``chrome_sandbox`` and dies 'FATAL: No usable sandbox!' there, while+ a distro chromium ships the helper. The bundle stays the answer when it is the only browser — a dock+ icon that fails loudly beats a non-root ``--no-sandbox``.+ """explicit = os.environ.get("AGENT_BROWSER_EXECUTABLE_PATH", "").strip()if explicit and os.access(explicit, os.X_OK):return explicit+ finders = [_playwright_executable, _system_executable]+ if not _is_root() and _userns_restricted():+ finders.reverse()+ return next((exe for find in finders if (exe := find())), None)+++def _playwright_executable() -> Optional[str]:from tools.browser_tool_install import _chromium_search_rootscandidates = sorted((p for root in _chromium_search_roots() for p in glob.glob(os.path.join(root, "chromium-*", "chrome-linux*", "chrome"))),key=os.path.getmtime, reverse=True)- for exe in candidates:- if os.access(exe, os.X_OK):- return exe+ return next((exe for exe in candidates if os.access(exe, os.X_OK)), None)+++def _system_executable() -> Optional[str]:return next((shutil.which(name) for name in _SYSTEM_BROWSERS if shutil.which(name)), None)+def _is_root() -> bool:+ return hasattr(os, "geteuid") and os.geteuid() == 0+++def _userns_restricted() -> bool:+ from tools.browser_tool_session import apparmor_restricts_unprivileged_userns+ return apparmor_restricts_unprivileged_userns()++def dock_launch() -> Optional[Tuple[str, str]]:"""``(executable, user_data_dir)`` for the dock's Browser icon, or ``None`` when no Chromium exists."""exe = executable()@@ -59,8 +82,11 @@ def dock_command(exe: str, user_data_dir: str) -> str:first-run / default-browser dialogs would sit between the human and the bot's tabs."""# --test-type hides the "Chrome for Testing is only for automated testing" and unsupported-flag# (--no-sandbox as root) infobars, which otherwise sit at the top of the human's takeover view.+ # Root gets the same sandbox-bypass flags agent-browser starts this binary with (one policy).+ from tools.browser_tool_session import CHROMIUM_SANDBOX_BYPASS_ARGS+ root_args = " ".join(("", *CHROMIUM_SANDBOX_BYPASS_ARGS)) if _is_root() else ""return (f"{exe} --user-data-dir={user_data_dir} --remote-debugging-port=0 --no-first-run "- f"--no-default-browser-check --test-type")+ f"--no-default-browser-check --test-type{root_args}")def running_instance_cdp_port(user_data_dir: str, *, exclude_session: Optional[str] = None) -> Optional[int]:diff --git a/tools/bot_desktop/runtime.py b/tools/bot_desktop/runtime.pyindex eb307695da9..ea78591ba04 100644--- a/tools/bot_desktop/runtime.py+++ b/tools/bot_desktop/runtime.py@@ -120,6 +120,7 @@ class DesktopStatus:socket: Optional[str]geometry: strinstall_command: Optional[str]+ browser: Optional[str] # headed Chromium the dock's Browser icon and agent-browser share; None = no headed browserdef as_dict(self) -> Dict[str, object]:return dict(self.__dict__)@@ -270,6 +271,7 @@ def geometry() -> str:def status(profile: Optional[str] = None) -> DesktopStatus:+ from tools.bot_desktop import browser as _bd_browsermissing: list[str] = missing_binaries() if is_supported_host() else list(REQUIRED_BINARIES)pid = _launcher_pid()env = published_env()@@ -284,6 +286,7 @@ def status(profile: Optional[str] = None) -> DesktopStatus:socket=str(rfb_socket_path()) if rfb_socket_path() else None,geometry=geometry(),install_command=install_command() if missing else None,+ browser=_bd_browser.executable() if is_supported_host() else None,)diff --git a/tools/browser_tool_session.py b/tools/browser_tool_session.pyindex c818dfb70b9..9532fe81dd0 100644--- a/tools/browser_tool_session.py+++ b/tools/browser_tool_session.py@@ -30,17 +30,29 @@ _CHROMIUM_MISSING_DOCKER_HINT = ("Chromium browser is missing. You're running in_CHROMIUM_MISSING_HINT = f"Chromium browser is missing. Install it with: {_CHROMIUM_INSTALL}"+# THE Chromium startup flags for a host where its sandbox cannot work; agent-browser gets them through+# AGENT_BROWSER_ARGS and the Bot Desktop dock's Browser icon (same binary, same profile) through+# ``tools.bot_desktop.browser.dock_command`` — one list, or the human's click dies while the agent's works.+CHROMIUM_SANDBOX_BYPASS_ARGS = ("--no-sandbox", "--disable-dev-shm-usage")+++def apparmor_restricts_unprivileged_userns() -> bool:+ """Ubuntu 23.10+ default: unprivileged user namespaces are denied, so a Chromium whose+ ``chrome_sandbox`` helper is not setuid (Playwright's bundle) dies with 'No usable sandbox'."""+ try:+ with open("/proc/sys/kernel/apparmor_restrict_unprivileged_userns", encoding="utf-8") as f:+ return f.read().strip() == "1"+ except OSError:+ return False++def _needs_chromium_sandbox_bypass() -> bool:"""True when Chromium needs --no-sandbox to start reliably (root, Docker, AppArmor userns)."""if hasattr(os, "geteuid") and os.geteuid() == 0:return Trueif _install._running_in_docker():return True- try:- with open("/proc/sys/kernel/apparmor_restrict_unprivileged_userns", encoding="utf-8") as f:- return f.read().strip() == "1"- except OSError:- return False+ return apparmor_restricts_unprivileged_userns()def _apply_chromium_sandbox_args(browser_env: Dict[str, str]) -> None:@@ -48,7 +60,7 @@ def _apply_chromium_sandbox_args(browser_env: Dict[str, str]) -> None:if ("AGENT_BROWSER_ARGS" not in browser_env and "AGENT_BROWSER_CHROME_FLAGS" not in browser_envand _needs_chromium_sandbox_bypass()):_bt.logger.debug("browser: sandbox bypass needed (root/docker/AppArmor userns) — injecting --no-sandbox")- browser_env["AGENT_BROWSER_ARGS"] = "--no-sandbox,--disable-dev-shm-usage"+ browser_env["AGENT_BROWSER_ARGS"] = ",".join(CHROMIUM_SANDBOX_BYPASS_ARGS)def _read_command_output_files(stdout_path: str, stderr_path: str) -> tuple[str, str]: