Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
Fix browser use CLI review issues
Laith Weinberger53c3ba2e72be
diff --git a/browser_use/browser/chrome.py b/browser_use/browser/chrome.pyindex 6df6d6929..f8ee497c5 100644--- a/browser_use/browser/chrome.py+++ b/browser_use/browser/chrome.py@@ -7,6 +7,34 @@ import subprocessfrom pathlib import Path+def _chrome_user_data_dir_for_executable(executable_path: str | None) -> Path | None:+ if executable_path is None:+ return None++ system = platform.system()+ path = Path(executable_path)+ if system == 'Darwin':+ app_path = str(path)+ base = Path.home() / 'Library' / 'Application Support'+ if 'Chromium.app' in app_path:+ return base / 'Chromium'+ if 'Google Chrome Canary.app' in app_path:+ return base / 'Google' / 'Chrome Canary'+ if 'Google Chrome.app' in app_path:+ return base / 'Google' / 'Chrome'+ if system == 'Linux':+ name = path.name+ base = Path.home() / '.config'+ if name in {'chromium', 'chromium-browser'}:+ return base / 'chromium'+ if name in {'google-chrome', 'google-chrome-stable'}:+ return base / 'google-chrome'+ if system == 'Windows' and path.name.lower() == 'chrome.exe':+ return Path(os.path.expandvars(r'%LocalAppData%\Google\Chrome\User Data'))++ return None++def find_chrome_executable() -> str | None:"""Find Chrome/Chromium executable on the system."""system = platform.system()@@ -41,11 +69,14 @@ def find_chrome_executable() -> str | None:return None-def get_chrome_profile_path(profile: str | None) -> str | None:+def get_chrome_profile_path(profile: str | None, executable_path: str | None = None) -> str | None:"""Get Chrome user data directory, or return a specific profile directory name."""if profile is not None:return profile+ if browser_user_data_dir := _chrome_user_data_dir_for_executable(executable_path):+ return str(browser_user_data_dir)+system = platform.system()if system == 'Darwin':return str(Path.home() / 'Library' / 'Application Support' / 'Google' / 'Chrome')@@ -63,7 +94,7 @@ def get_chrome_profile_path(profile: str | None) -> str | None:def list_chrome_profiles() -> list[dict[str, str]]:"""List available Chrome profiles with their display names."""- user_data_dir = get_chrome_profile_path(None)+ user_data_dir = get_chrome_profile_path(None, executable_path=find_chrome_executable())if user_data_dir is None:return []@@ -75,7 +106,11 @@ def list_chrome_profiles() -> list[dict[str, str]]:with open(local_state_path, encoding='utf-8') as f:local_state = json.load(f)+ if not isinstance(local_state, dict):+ return []info_cache = local_state.get('profile', {}).get('info_cache', {})+ if not isinstance(info_cache, dict):+ return []return sorted([{@@ -83,8 +118,9 @@ def list_chrome_profiles() -> list[dict[str, str]]:'name': info.get('name', directory),}for directory, info in info_cache.items()+ if isinstance(info, dict)],key=lambda profile: profile['directory'],)- except (json.JSONDecodeError, KeyError, OSError):+ except (json.JSONDecodeError, KeyError, OSError, TypeError):return []diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex a10c672e9..72d5a2045 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -450,7 +450,7 @@ class BrowserSession(BaseModel):' Windows: C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe')- user_data_dir = get_chrome_profile_path(None)+ user_data_dir = get_chrome_profile_path(None, executable_path=executable_path)if user_data_dir is None:raise RuntimeError('Could not detect Chrome profile directory for your platform.\n'diff --git a/browser_use/cli.py b/browser_use/cli.pyindex 66b718475..4d8e4ef65 100644--- a/browser_use/cli.py+++ b/browser_use/cli.py@@ -30,7 +30,10 @@ def _normalize_captured_cli_output(func, argv: list[str]) -> int:return 0if isinstance(result, int):return result- return int(result)+ if isinstance(result, str):+ print(_as_browser_use_cli_text(result), file=sys.stderr)+ return 1+ return 1def _patch_browser_harness_cli_text() -> None:@@ -61,13 +64,22 @@ def _run_browser_harness() -> int | None:_patch_browser_harness_cli_text()args = sys.argv[1:]- if args and args[0] == 'doctor' and args[1:] and args[1:] != ['--fix-snap']:- print('usage: browser-use doctor [--fix-snap]', file=sys.stderr)- sys.exit(2)+ if args and args[0] == 'doctor' and args[1:]:+ if args[1:] in (['--help'], ['-h']):+ print('usage: browser-use doctor [--fix-snap]')+ return 0+ if args[1:] != ['--fix-snap']:+ print('usage: browser-use doctor [--fix-snap]', file=sys.stderr)+ sys.exit(2)run.main()return None+def browser_use_tui_main() -> int | None:+ print('browser-use-tui is deprecated; use browser-use instead.', file=sys.stderr)+ return main()++def main() -> int | None:args = sys.argv[1:]if args and args[0] == 'skill':diff --git a/pyproject.toml b/pyproject.tomlindex 5e77aa47f..ec661f8b9 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -56,10 +56,9 @@ dependencies = [# openai: datalib,voice-helpers are actually NOT NEEDED but openai produces noisy errors on exit without them TODO: fix# rich: used for terminal formatting and styling in CLI# click: used for command-line argument parsing-# textual: used for terminal UI[project.optional-dependencies]-cli = ["textual==7.4.0"]+cli = []core = ["browser-use-core==0.13.2; sys_platform == 'darwin' and platform_machine == 'arm64'","browser-use-core==0.13.2; sys_platform == 'darwin' and platform_machine == 'x86_64'",@@ -106,6 +105,7 @@ browser-use = "browser_use.cli:main" # Browser Use CLI for agentsbrowseruse = "browser_use.cli:main" # Alias for browser-usebu = "browser_use.cli:main" # Alias for browser-usebrowser = "browser_use.cli:main" # Alias for browser-use+browser-use-tui = "browser_use.cli:browser_use_tui_main" # Deprecated alias for browser-use[build-system]requires = ["hatchling"]diff --git a/tests/ci/test_browser_use_cli.py b/tests/ci/test_browser_use_cli.pynew file mode 100644index 000000000..dac622757--- /dev/null+++ b/tests/ci/test_browser_use_cli.py@@ -0,0 +1,48 @@+import os+import subprocess+import sys+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+++def _run_browser_use_cli(*args: str) -> subprocess.CompletedProcess[str]:+ env = os.environ.copy()+ env['PYTHONPATH'] = os.pathsep.join(part for part in (str(ROOT), env.get('PYTHONPATH', '')) if part)+ return subprocess.run(+ [sys.executable, '-m', 'browser_use.cli', *args],+ cwd=ROOT,+ env=env,+ capture_output=True,+ text=True,+ timeout=20,+ )+++def test_browser_use_doctor_help_prints_browser_use_usage():+ result = _run_browser_use_cli('doctor', '--help')++ assert result.returncode == 0+ assert result.stdout == 'usage: browser-use doctor [--fix-snap]\n'+ assert result.stderr == ''+++def test_normalize_captured_cli_output_handles_string_system_exit(capsys):+ from browser_use.cli import _normalize_captured_cli_output++ def exits_with_string(_argv):+ raise SystemExit('browser-harness failed')++ assert _normalize_captured_cli_output(exits_with_string, []) == 1+ captured = capsys.readouterr()+ assert captured.out == ''+ assert captured.err == 'browser-use failed\n'+++def test_browser_use_tui_is_deprecated_alias(monkeypatch, capsys):+ import browser_use.cli as browser_use_cli++ monkeypatch.setattr(browser_use_cli, 'main', lambda: 0)++ assert browser_use_cli.browser_use_tui_main() == 0+ assert capsys.readouterr().err == 'browser-use-tui is deprecated; use browser-use instead.\n'diff --git a/tests/ci/test_chrome_profile_helpers.py b/tests/ci/test_chrome_profile_helpers.pynew file mode 100644index 000000000..845d979d3--- /dev/null+++ b/tests/ci/test_chrome_profile_helpers.py@@ -0,0 +1,54 @@+import json+from pathlib import Path++from browser_use.browser import chrome+++def test_macos_profile_path_matches_detected_browser_variant(monkeypatch, tmp_path):+ monkeypatch.setattr(chrome.platform, 'system', lambda: 'Darwin')+ monkeypatch.setattr(Path, 'home', lambda: tmp_path)++ assert chrome.get_chrome_profile_path(+ None,+ executable_path='/Applications/Chromium.app/Contents/MacOS/Chromium',+ ) == str(tmp_path / 'Library' / 'Application Support' / 'Chromium')+ assert chrome.get_chrome_profile_path(+ None,+ executable_path='/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary',+ ) == str(tmp_path / 'Library' / 'Application Support' / 'Google' / 'Chrome Canary')+ assert chrome.get_chrome_profile_path(+ None,+ executable_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',+ ) == str(tmp_path / 'Library' / 'Application Support' / 'Google' / 'Chrome')+++def test_list_chrome_profiles_uses_detected_browser_variant(monkeypatch, tmp_path):+ monkeypatch.setattr(chrome.platform, 'system', lambda: 'Darwin')+ monkeypatch.setattr(Path, 'home', lambda: tmp_path)+ monkeypatch.setattr(chrome, 'find_chrome_executable', lambda: '/Applications/Chromium.app/Contents/MacOS/Chromium')++ user_data_dir = tmp_path / 'Library' / 'Application Support' / 'Chromium'+ user_data_dir.mkdir(parents=True)+ (user_data_dir / 'Local State').write_text(+ json.dumps({'profile': {'info_cache': {'Profile 1': {'name': 'Work'}}}}),+ encoding='utf-8',+ )++ assert chrome.list_chrome_profiles() == [{'directory': 'Profile 1', 'name': 'Work'}]+++def test_list_chrome_profiles_returns_empty_for_unexpected_json_shapes(monkeypatch, tmp_path):+ monkeypatch.setattr(chrome.platform, 'system', lambda: 'Darwin')+ monkeypatch.setattr(Path, 'home', lambda: tmp_path)+ monkeypatch.setattr(chrome, 'find_chrome_executable', lambda: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome')++ user_data_dir = tmp_path / 'Library' / 'Application Support' / 'Google' / 'Chrome'+ user_data_dir.mkdir(parents=True)++ for payload in (+ [],+ {'profile': {'info_cache': []}},+ {'profile': {'info_cache': {'Default': []}}},+ ):+ (user_data_dir / 'Local State').write_text(json.dumps(payload), encoding='utf-8')+ assert chrome.list_chrome_profiles() == []