The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(browser): isolate Lightpanda and Chrome fallback flags
Simone Marzolae3553948398e
diff --git a/tests/tools/test_browser_lightpanda.py b/tests/tools/test_browser_lightpanda.pyindex b13c1da2bf8..d736edb47c3 100644--- a/tests/tools/test_browser_lightpanda.py+++ b/tests/tools/test_browser_lightpanda.py@@ -194,6 +194,60 @@ class TestCleanupResetsEngineCache:assert bt._browser_engine_resolved is False+# ---------------------------------------------------------------------------+# Chrome fallback behavior+# ---------------------------------------------------------------------------++class TestChromeFallback:+ """Chrome fallback must hand off from Lightpanda without leaking engine policy."""++ def test_uses_non_recursive_lightpanda_get_url(self):+ import tools.browser_tool as bt++ with patch("tools.browser_tool._run_browser_command", return_value={+ "success": True, "data": {"url": "https://example.com/"}+ }) as run_command, \+ patch("tools.browser_tool._find_agent_browser", side_effect=FileNotFoundError("stop")):+ result = bt._run_chrome_fallback_command(+ "task1", "screenshot", [], timeout=30+ )++ run_command.assert_called_once_with(+ "task1", "get", ["url"], timeout=10, _engine_override="lightpanda"+ )+ assert result == {"success": False, "error": "stop"}++ def test_chrome_fallback_injects_required_sandbox_args(self):+ import tools.browser_tool as bt++ captured_envs = []+ mock_proc = MagicMock()+ mock_proc.wait.return_value = None+ mock_proc.returncode = 1++ def capture_popen(_cmd, **kwargs):+ captured_envs.append(kwargs["env"])+ return mock_proc++ with patch("tools.browser_tool._run_browser_command", return_value={+ "success": True, "data": {"url": "https://example.com/"}+ }), \+ patch("tools.browser_tool._find_agent_browser", return_value="/usr/bin/agent-browser"), \+ patch("tools.browser_tool._chromium_installed", return_value=True), \+ patch("tools.browser_tool._needs_chromium_sandbox_bypass", return_value=True), \+ patch("subprocess.Popen", side_effect=capture_popen):+ result = bt._run_chrome_fallback_command(+ "task1", "screenshot", [], timeout=30+ )++ assert result["success"] is False+ assert captured_envs+ assert all(+ env.get("AGENT_BROWSER_ARGS") == "--no-sandbox,--disable-dev-shm-usage"+ for env in captured_envs+ )++# ---------------------------------------------------------------------------# fallback warning annotation# ---------------------------------------------------------------------------@@ -346,7 +400,7 @@ class TestEngineOverride:def test_no_override_uses_cached_engine(self, _camofox, _cdp, _cloud, _chromium, _local, _find, _session):- """Without _engine_override, the cached engine is used."""+ """Lightpanda gets neither auto-injected nor inherited Chrome arguments."""import tools.browser_tool as btbt._cached_browser_engine = "lightpanda"@@ -355,12 +409,14 @@ class TestEngineOverride:_session.return_value = {"session_name": "test-sess"}captured_cmds = []+ captured_envs = []mock_proc = MagicMock()mock_proc.wait.return_value = Nonemock_proc.returncode = 0def capture_popen(cmd, **kwargs):captured_cmds.append(cmd)+ captured_envs.append(kwargs["env"])return mock_proc# Return a substantive snapshot so the LP fallback does NOT trigger.@@ -375,14 +431,26 @@ class TestEngineOverride:__exit__=MagicMock(return_value=False),))), \patch("tools.interrupt.is_interrupted", return_value=False), \- patch("tools.browser_tool._write_owner_pid"):+ patch("tools.browser_tool._needs_chromium_sandbox_bypass", return_value=True), \+ patch("tools.browser_tool._write_owner_pid"), \+ patch.dict(os.environ, {}, clear=True):+ # AppArmor/root detection would normally auto-inject Chromium args.bt._run_browser_command("task1", "snapshot", [])- # SHOULD contain "--engine lightpanda"- assert len(captured_cmds) == 1- assert "--engine" in captured_cmds[0]- engine_idx = captured_cmds[0].index("--engine")- assert captured_cmds[0][engine_idx + 1] == "lightpanda"+ # User-supplied current and legacy Chromium knobs must also be removed.+ with patch.dict(os.environ, {+ "AGENT_BROWSER_ARGS": "--no-sandbox",+ "AGENT_BROWSER_CHROME_FLAGS": "--disable-dev-shm-usage",+ }):+ bt._run_browser_command("task1", "snapshot", [])++ assert len(captured_cmds) == 2+ for command, environment in zip(captured_cmds, captured_envs):+ assert "--engine" in command+ engine_idx = command.index("--engine")+ assert command[engine_idx + 1] == "lightpanda"+ assert "AGENT_BROWSER_ARGS" not in environment+ assert "AGENT_BROWSER_CHROME_FLAGS" not in environmentdef test_hybrid_local_sidecar_injects_engine_even_with_cloud_provider(self):"""A task::local sidecar is local even when global cloud config exists."""diff --git a/tools/browser_tool.py b/tools/browser_tool.pyindex 866f8bb78dd..7a7a81b1f37 100644--- a/tools/browser_tool.py+++ b/tools/browser_tool.py@@ -411,6 +411,20 @@ def _needs_chromium_sandbox_bypass() -> bool:return False+def _apply_chromium_sandbox_args(browser_env: Dict[str, str]) -> None:+ """Add required Chromium sandbox flags without overriding user settings."""+ if (+ "AGENT_BROWSER_ARGS" not in browser_env+ and "AGENT_BROWSER_CHROME_FLAGS" not in browser_env+ and _needs_chromium_sandbox_bypass()+ ):+ logger.debug(+ "browser: sandbox bypass needed (root/docker/AppArmor userns) — "+ "injecting --no-sandbox"+ )+ browser_env["AGENT_BROWSER_ARGS"] = "--no-sandbox,--disable-dev-shm-usage"++def _read_command_output_files(stdout_path: str, stderr_path: str) -> tuple[str, str]:"""Best-effort read of agent-browser stdout/stderr temp files."""stdout = stderr = ""@@ -1235,15 +1249,16 @@ def _run_chrome_fallback_command("""import uuid- # 1. Grab the current URL from the Lightpanda session. Use- # ``_engine_override=\"auto\"`` so this helper does not recursively trigger- # Lightpanda→Chrome fallback if the eval call itself fails.+ # 1. Grab the current URL from the Lightpanda session. ``get url`` is not+ # fallback-eligible, so an error cannot recursively trigger this helper.+ # Keep the explicit Lightpanda override so Chromium-only environment flags+ # are stripped while querying the already-running Lightpanda daemon.url_result = _run_browser_command(- task_id, "eval", ["window.location.href"], timeout=10, _engine_override="auto"+ task_id, "get", ["url"], timeout=10, _engine_override="lightpanda")current_url = Noneif url_result.get("success"):- current_url = url_result.get("data", {}).get("result", "").strip().strip('"').strip("'")+ current_url = str(url_result.get("data", {}).get("url", "")).strip()if not current_url:logger.warning("Chrome fallback: could not determine current URL from LP session")return {"success": False, "error": "Chrome fallback failed: could not determine current URL"}@@ -1296,6 +1311,10 @@ def _run_chrome_fallback_command(if "AGENT_BROWSER_IDLE_TIMEOUT_MS" not in browser_env:browser_env["AGENT_BROWSER_IDLE_TIMEOUT_MS"] = str(BROWSER_SESSION_INACTIVITY_TIMEOUT * 1000)+ # This helper bypasses _run_browser_command, so apply the same Chromium+ # sandbox policy explicitly.+ _apply_chromium_sandbox_args(browser_env)+def _run_tmp(cmd: str, cmd_args: List[str]) -> Dict[str, Any]:full = base_args + [cmd] + cmd_args# Use temp-file stdout/stderr pattern (same as _run_browser_command)@@ -3688,26 +3707,14 @@ def _run_browser_command(idle_ms = str(BROWSER_SESSION_INACTIVITY_TIMEOUT * 1000)browser_env["AGENT_BROWSER_IDLE_TIMEOUT_MS"] = idle_ms- # Inject --no-sandbox when needed (issue #15765):- # - Running as root: Chromium always refuses to start without it- # - Ubuntu 23.10+ / AppArmor systems: unprivileged user namespaces- # are restricted, causing Chromium to exit with "No usable sandbox"- # even for non-root users running under systemd or containers.- # Honour either the legacy AGENT_BROWSER_CHROME_FLAGS (never consumed by- # agent-browser itself, but documented in older notes) or the real- # AGENT_BROWSER_ARGS — if the user pre-sets either, don't overwrite it.- if (- "AGENT_BROWSER_ARGS" not in browser_env- and "AGENT_BROWSER_CHROME_FLAGS" not in browser_env- ):- if _needs_chromium_sandbox_bypass():- logger.debug(- "browser: sandbox bypass needed (root/docker/AppArmor userns) — "- "injecting --no-sandbox"- )- browser_env["AGENT_BROWSER_ARGS"] = (- "--no-sandbox,--disable-dev-shm-usage"- )+ # Chromium-only launch flags are rejected by Lightpanda. Strip both+ # the current and legacy variables for Lightpanda commands; explicit+ # Chrome commands and fallback use the shared Chromium policy.+ if engine == "lightpanda":+ browser_env.pop("AGENT_BROWSER_ARGS", None)+ browser_env.pop("AGENT_BROWSER_CHROME_FLAGS", None)+ else:+ _apply_chromium_sandbox_args(browser_env)# Use temp files for stdout/stderr instead of pipes.# agent-browser starts a background daemon that inherits file