The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(browser): take the direct-API shortcut only when BROWSER_USE_API_KEY is set
kshitijk4poor9f3a5345bf2a
diff --git a/tests/tools/test_browser_use_cli.py b/tests/tools/test_browser_use_cli.pyindex 54854304c0e..4112c1cd11d 100644--- a/tests/tools/test_browser_use_cli.py+++ b/tests/tools/test_browser_use_cli.py@@ -564,30 +564,24 @@ class TestBackendCdpResolution:assert bu_cli._resolve_backend_cdp(env, "t1", session_name="r7k2") is Noneassert "BU_CDP_WS" not in env and "BU_CDP_URL" not in env- def test_direct_api_without_key_errors_instead_of_dropping_cdp(self, monkeypatch):- """cloud_provider browser-use with no API key must not return None.-- None is the autospawn signal, and autospawn only runs when the key is- set. Without the key the harness used to hunt an installed Chrome for- DevToolsActivePort and never started the bundled Chromium.- """+ def test_direct_api_without_key_uses_session_path_not_chrome_hunt(self, monkeypatch, _fake_managed_chromium):+ """cloud_provider browser-use with no API key must not take the autospawn shortcut: the CLI+ only autospawns with the key, so None left the harness hunting an installed Chrome+ (DevToolsActivePort). The session path's local-Chromium fallback drives the packaged one."""class _BUProvider:name = "browser-use"monkeypatch.setattr("tools.browser_tool_cdp._get_cdp_override", lambda: "")monkeypatch.setattr(bt_cloud, "_get_cloud_provider", lambda: _BUProvider())- monkeypatch.setattr(- bt_session, "_get_session_info",- lambda key: (_ for _ in ()).throw(AssertionError("must skip provider")),- )+ monkeypatch.setattr(bt_session, "_get_session_info", lambda key: {+ "cdp_url": None, "features": {"local": True}, "fallback_from_cloud": True,+ "fallback_reason": "BROWSER_USE_API_KEY is not set"})monkeypatch.setattr(bu_cli, "_read_browser_cfg", lambda: {"cloud_provider": "browser-use"})monkeypatch.delenv("BROWSER_USE_API_KEY", raising=False)- env = {}- err = bu_cli._resolve_backend_cdp(env, "t1", session_name="r7k2")- assert isinstance(err, str) and "BROWSER_USE_API_KEY" in err- assert "hermes tools" in err- assert "BU_CDP_WS" not in env and "BU_CDP_URL" not in env+ env = self._env()+ assert bu_cli._resolve_backend_cdp(env, "t1") is None+ assert env["BU_CDP_WS"] == "ws://127.0.0.1:47000/devtools/browser/t1"def test_picker_managed_selection_resolves_gateway_provider(self, monkeypatch):"""``cloud_provider: nous`` (the `hermes tools` managed row) must resolve through the@@ -619,9 +613,6 @@ class TestBackendCdpResolution:class _BUProvider:name = "browser-use"- def _get_config_or_none(self, refresh_token=True):- return {"api_key": "tok", "base_url": "https://gateway", "managed_mode": True}-monkeypatch.setattr("tools.browser_tool_cdp._get_cdp_override", lambda: "")monkeypatch.setattr(bt_cloud, "_get_cloud_provider", lambda: _BUProvider())monkeypatch.setattr(@@ -630,53 +621,11 @@ class TestBackendCdpResolution:)# Never-configured: browser section present but no selection at all.monkeypatch.setattr(bu_cli, "_read_browser_cfg", lambda: {"backend": "browser-use"})+ monkeypatch.delenv("BROWSER_USE_API_KEY", raising=False)env = {}assert bu_cli._resolve_backend_cdp(env, "t1") is Noneassert env["BU_CDP_WS"] == "wss://gateway.example/cdp/autodetect"- def test_direct_api_provider_still_takes_native_shortcut(self, monkeypatch):- """The managed-vs-direct split must not regress the direct-API path: with a real- BROWSER_USE_API_KEY and no gateway, the CLI still talks to BU cloud natively instead of- double-sessioning through the provider."""- class _BUProvider:- name = "browser-use"-- def _get_config_or_none(self, refresh_token=True):- return {"api_key": "bu-key", "base_url": "https://api.browser-use.com", "managed_mode": False}-- monkeypatch.setattr("tools.browser_tool_cdp._get_cdp_override", lambda: "")- monkeypatch.setattr(bt_cloud, "_get_cloud_provider", lambda: _BUProvider())- monkeypatch.setattr(- bt_session, "_get_session_info",- lambda key: (_ for _ in ()).throw(AssertionError("must skip provider")),- )- monkeypatch.setattr(bu_cli, "_read_browser_cfg", lambda: {"cloud_provider": "browser-use"})- env = {}- assert bu_cli._resolve_backend_cdp(env, "t1") is None- assert "BU_CDP_WS" not in env and "BU_CDP_URL" not in env-- def test_never_configured_managed_provider_failure_errors_never_silently_unset(self, monkeypatch):- """A managed provider that cannot produce a session must surface that failure, NOT fall- through with BU_CDP_* unset — the harness's own discovery then fails with a misleading- chrome-not-running instead of naming the real problem."""- class _BUProvider:- name = "browser-use"-- def _get_config_or_none(self, refresh_token=True):- return {"api_key": "tok", "base_url": "https://gateway", "managed_mode": True}-- monkeypatch.setattr("tools.browser_tool_cdp._get_cdp_override", lambda: "")- monkeypatch.setattr(bt_cloud, "_get_cloud_provider", lambda: _BUProvider())- monkeypatch.setattr(- bt_session, "_get_session_info",- lambda task_id: (_ for _ in ()).throw(RuntimeError("no managed session")),- )- monkeypatch.setattr(bu_cli, "_read_browser_cfg", lambda: {"backend": "browser-use"})- env = {}- err = bu_cli._resolve_backend_cdp(env, "t1")- assert err and "no managed session" in err- assert "BU_CDP_WS" not in env and "BU_CDP_URL" not in env-def test_legacy_use_gateway_flag_still_resolves_gateway_provider(self, monkeypatch):"""Regression guard for the pre-picker shape of the same selection."""class _BUProvider:diff --git a/tools/browser_use_cli.py b/tools/browser_use_cli.pyindex 84b74e285c0..23bc0e43cf7 100644--- a/tools/browser_use_cli.py+++ b/tools/browser_use_cli.py@@ -216,25 +216,6 @@ def _use_gateway(browser_cfg: dict) -> bool:return str(browser_cfg.get("cloud_provider") or "").strip().lower() == NOUS_MANAGED_PROVIDER-def _is_managed_browser_use(provider: Any) -> bool:- """True when a resolved ``browser-use`` provider is backed by the managed Nous Tool Gateway- rather than a direct ``BROWSER_USE_API_KEY`` config.-- Autodetect hands back a managed provider on installs that never configured a cloud browser- (the gateway token needs no API key), and that provider reports the same ``name`` as the- direct-API one. The direct-API shortcut below then skipped session resolution for a provider- that CAN provide one, leaving BU_CDP_* unset so the harness fell back to hunting the user's- profile dirs — ``chrome-not-running`` on a host with no ~/.config/chromium."""- resolver = getattr(provider, "_get_config_or_none", None)- if not callable(resolver):- return False- try:- config = resolver(refresh_token=False)- except Exception:- return False- return bool(isinstance(config, dict) and config.get("managed_mode"))--def get_browser_backend() -> str:"""Configured browser backend key ("" = unset → default). YAML 1.1 parses anunquoted ``off`` as False — that must mean BACKEND_DISABLED, not "unset"."""@@ -514,20 +495,14 @@ def _resolve_backend_cdp(env: dict, task_id: Optional[str], session_name: str =# Browser Use direct-API configs: the CLI talks to BU cloud natively (BU_AUTOSPAWN / auth login) — the# legacy provider would create a second, redundant session. Nous-gateway configs (cloud_provider: nous# from the picker, or the pre-picker use_gateway: true) DO resolve through the provider: the gateway- # provisions the browser server-side and returns its CDP URL.+ # provisions the browser server-side and returns its CDP URL. Without BROWSER_USE_API_KEY the CLI cannot+ # autospawn, and the provider is either the managed gateway (autodetect on a never-configured install) or+ # a selection missing its key; both go through the session path (gateway CDP, or the session layer's+ # local-Chromium fallback) instead of leaving the harness to hunt for an installed Chrome.provider_key = str(getattr(provider, "name", "") or "").strip().lower()+ from agent.secret_scope import get_secretif (provider_key == _BACKEND_KEY and not _use_gateway(_read_browser_cfg())- and not _is_managed_browser_use(provider)):- # Direct-API returns no CDP on purpose so the CLI can autospawn. Autospawn only- # happens when BROWSER_USE_API_KEY is set. With the key missing, None used to- # leave the harness to discover an installed Chrome (DevToolsActivePort).- from agent.secret_scope import get_secret- if not get_secret("BROWSER_USE_API_KEY", ""):- from tools.tool_backend_helpers import selection_error- return selection_error(- "browser", "'browser-use'",- "BROWSER_USE_API_KEY is not set, so browser_exec cannot start a Browser Use cloud browser",- )+ and get_secret("BROWSER_USE_API_KEY", "")):env[_PRIVATE_BROWSER_SENTINEL] = "1" # named BU cloud browsers are exclusive to their daemonreturn None