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: address cubic-dev-ai code review concerns from PR #4078
ShawnPana35271ed80206
diff --git a/browser_use/skill_cli/commands/agent.py b/browser_use/skill_cli/commands/agent.pyindex 6b8f1abb4..fc7ea3899 100644--- a/browser_use/skill_cli/commands/agent.py+++ b/browser_use/skill_cli/commands/agent.py@@ -24,14 +24,13 @@ async def handle(session: SessionInfo, params: dict[str, Any]) -> Any:if not task:return {'success': False, 'error': 'No task provided'}- # Check API key for LLM/Cloud access- try:- require_api_key('Agent tasks')- except APIKeyRequired as e:- return {'success': False, 'error': str(e)}-# Route based on browser modeif session.browser_mode == 'remote':+ # Remote mode requires Browser-Use API key+ try:+ require_api_key('Cloud agent tasks')+ except APIKeyRequired as e:+ return {'success': False, 'error': str(e)}return await _handle_cloud_task(params)else:# Check if user tried to use cloud-only flags in local modediff --git a/browser_use/skill_cli/commands/profile.py b/browser_use/skill_cli/commands/profile.pyindex bf453f447..06771fe2c 100644--- a/browser_use/skill_cli/commands/profile.py+++ b/browser_use/skill_cli/commands/profile.py@@ -542,13 +542,20 @@ def _handle_sync(args: argparse.Namespace) -> int:else:cloud_name = f'Chrome - {profile_name}'+ # Use stderr for progress when JSON output is requested+ json_output = getattr(args, 'json', False)+ out = sys.stderr if json_output else sys.stdout++ def log(msg: str) -> None:+ print(msg, file=out)+if domain_filter:- print(f'Syncing: {profile_name} → {domain_filter} cookies only')+ log(f'Syncing: {profile_name} → {domain_filter} cookies only')else:- print(f'Syncing: {profile_name} ({selected_profile["email"]})')+ log(f'Syncing: {profile_name} ({selected_profile["email"]})')# Step 1: Create cloud profile- print(' Creating cloud profile...')+ log(' Creating cloud profile...')from browser_use.skill_cli.main import cloud_api_requestresult = cloud_api_request('POST', '/profiles', {'name': cloud_name})@@ -557,11 +564,18 @@ def _handle_sync(args: argparse.Namespace) -> int:return 1cloud_profile_id = result['data']['id']- print(f' ✓ Created: {cloud_profile_id}')+ log(f' ✓ Created: {cloud_profile_id}')++ def cleanup_cloud_profile() -> None:+ """Delete the cloud profile on failure."""+ try:+ cloud_api_request('DELETE', f'/profiles/{cloud_profile_id}')+ except Exception:+ pass# Step 2: Export cookies from local profileasync def sync_cookies():- print(' Exporting cookies from local profile...')+ log(' Exporting cookies from local profile...')local_session = await create_browser_session('real', headed=False, profile=profile_id)await local_session.start()try:@@ -576,7 +590,7 @@ def _handle_sync(args: argparse.Namespace) -> int:if not cookies:return 0, f'No cookies found for domain: {domain_filter}'- print(f' ✓ Found {len(cookies)} cookies')+ log(f' ✓ Found {len(cookies)} cookies')# Save to temp file - convert Cookie objects to dicts for JSON serializationcookies_file = Path(tempfile.gettempdir()) / f'browser-use-sync-{cloud_profile_id}.json'@@ -600,12 +614,13 @@ def _handle_sync(args: argparse.Namespace) -> int:cookie_count, cookies_file = asyncio.run(sync_cookies())if cookie_count == 0:- print(f' ⚠ {cookies_file}') # cookies_file contains error message+ log(f' ⚠ {cookies_file}') # cookies_file contains error message+ cleanup_cloud_profile()return 1# Step 3: Import cookies to cloud profileasync def import_to_cloud():- print(' Importing cookies to cloud profile...')+ log(' Importing cookies to cloud profile...')remote_session = await create_browser_session('remote', headed=False, profile=cloud_profile_id)await remote_session.start()try:@@ -626,6 +641,10 @@ def _handle_sync(args: argparse.Namespace) -> int:loop.run_until_complete(import_to_cloud())except RuntimeError:asyncio.run(import_to_cloud())+ except Exception as e:+ log(f' ⚠ Failed to import cookies: {e}')+ cleanup_cloud_profile()+ return 1# Cleanup temp filetry:@@ -633,13 +652,13 @@ def _handle_sync(args: argparse.Namespace) -> int:except Exception:pass- print('✓ Profile synced successfully!')- print(f' Cloud profile ID: {cloud_profile_id}')- print()- print('To use this profile:')- print(f' browser-use -b remote --profile {cloud_profile_id} open <url>')+ log('✓ Profile synced successfully!')+ log(f' Cloud profile ID: {cloud_profile_id}')+ log('')+ log('To use this profile:')+ log(f' browser-use -b remote --profile {cloud_profile_id} open <url>')- if getattr(args, 'json', False):+ if json_output:print(json.dumps({diff --git a/browser_use/skill_cli/tunnel_manager.py b/browser_use/skill_cli/tunnel_manager.pyindex 4c5d15c8d..06eeb44b3 100644--- a/browser_use/skill_cli/tunnel_manager.py+++ b/browser_use/skill_cli/tunnel_manager.py@@ -251,6 +251,9 @@ async def start_tunnel(port: int) -> dict[str, Any]:log_file.close()return {'error': 'Timed out waiting for cloudflare tunnel URL (15s)'}+ # Close log file handle to avoid leaking file descriptors+ log_file.close()+# Save tunnel info to disk so it persists across CLI invocations_save_tunnel_info(port, process.pid, url)logger.info(f'Tunnel started: localhost:{port} -> {url} (pid={process.pid})')diff --git a/install.sh b/install.shindex e49a39bb6..0ccb2a98f 100755--- a/install.sh+++ b/install.sh@@ -80,6 +80,10 @@ parse_args() {shift;;--api-key)+ if [ -z "$2" ] || [[ "$2" == --* ]]; then+ log_error "--api-key requires a value"+ exit 1+ fiAPI_KEY="$2"shift 2;;@@ -99,6 +103,7 @@ parse_args() {exit 0;;*)+ log_warn "Unknown argument: $1 (ignored)"shift;;esac@@ -642,7 +647,7 @@ main() {# Step 2: Check/install Pythonif ! check_python; then- read -p "Python 3.11+ not found. Install now? [y/N] " -n 1 -r+ read -p "Python 3.11+ not found. Install now? [y/N] " -n 1 -r < /dev/ttyechoif [[ $REPLY =~ ^[Yy]$ ]]; theninstall_pythondiff --git a/tests/ci/test_setup_command.py b/tests/ci/test_setup_command.pyindex 248e1b1f2..6577450dc 100644--- a/tests/ci/test_setup_command.py+++ b/tests/ci/test_setup_command.py@@ -1,94 +1,87 @@-"""Tests for setup command."""+"""Tests for setup command.-import json-from unittest.mock import MagicMock, patch+These tests call real functions without mocking. They verify the+structure and logic of the setup command against actual system state.+"""import pytestfrom browser_use.skill_cli.commands import setup-async def test_setup_local_profile():- """Test setup with local profile."""- with patch('browser_use.skill_cli.commands.setup.run_checks') as mock_checks:- mock_checks.return_value = {- 'browser_use_package': {'status': 'ok', 'message': 'browser-use installed'},- 'browser': {'status': 'ok', 'message': 'Browser available'},- }-- with patch('browser_use.skill_cli.commands.setup.plan_actions', return_value=[]):- with patch('browser_use.skill_cli.commands.setup.execute_actions'):- with patch('browser_use.skill_cli.commands.setup.validate_setup') as mock_validate:- mock_validate.return_value = {- 'browser_use_import': 'ok',- 'browser_profile': 'ok',- }-- result = await setup.handle(- 'setup',- {- 'profile': 'local',- 'api_key': None,- 'yes': False,- 'json': False,- },- )-- assert result['status'] == 'success'- assert result['profile'] == 'local'- assert 'checks' in result- assert 'validation' in result---async def test_setup_remote_profile():- """Test setup with remote profile."""- with patch('browser_use.skill_cli.commands.setup.run_checks') as mock_checks:- mock_checks.return_value = {- 'browser_use_package': {'status': 'ok', 'message': 'browser-use installed'},- 'api_key': {'status': 'missing', 'message': 'Not configured'},- 'cloudflared': {'status': 'ok', 'message': 'Will auto-install'},- }-- with patch('browser_use.skill_cli.commands.setup.plan_actions') as mock_plan:- mock_plan.return_value = [- {- 'type': 'configure_api_key',- 'description': 'Configure API key',- 'api_key': 'test_key',- }- ]-- with patch('browser_use.skill_cli.commands.setup.execute_actions'):- with patch('browser_use.skill_cli.commands.setup.validate_setup') as mock_validate:- mock_validate.return_value = {- 'browser_use_import': 'ok',- 'api_key_available': True,- 'cloudflared_available': True,- }-- result = await setup.handle(- 'setup',- {- 'profile': 'remote',- 'api_key': 'test_key',- 'yes': True,- 'json': False,- },- )-- assert result['status'] == 'success'- assert result['profile'] == 'remote'---async def test_setup_invalid_profile():- """Test setup with invalid profile."""+async def test_setup_local_mode():+ """Test setup with local mode runs without error."""result = await setup.handle('setup',{- 'profile': 'invalid',+ 'mode': 'local',+ 'api_key': None,+ 'yes': True,+ 'json': True,+ },+ )++ # Should return a dict with expected structure+ assert isinstance(result, dict)+ # Either success or error, but should have a response+ assert 'status' in result or 'error' in result++ if 'status' in result:+ assert result['status'] == 'success'+ assert result['mode'] == 'local'+ assert 'checks' in result+ assert 'validation' in result+++async def test_setup_remote_mode():+ """Test setup with remote mode runs without error."""+ result = await setup.handle(+ 'setup',+ {+ 'mode': 'remote',+ 'api_key': None,+ 'yes': True,+ 'json': True,+ },+ )++ # Should return a dict with expected structure+ assert isinstance(result, dict)+ assert 'status' in result or 'error' in result++ if 'status' in result:+ assert result['status'] == 'success'+ assert result['mode'] == 'remote'+ assert 'checks' in result+ assert 'validation' in result+++async def test_setup_full_mode():+ """Test setup with full mode runs without error."""+ result = await setup.handle(+ 'setup',+ {+ 'mode': 'full',+ 'api_key': None,+ 'yes': True,+ 'json': True,+ },+ )++ assert isinstance(result, dict)+ assert 'status' in result or 'error' in result++ if 'status' in result:+ assert result['status'] == 'success'+ assert result['mode'] == 'full'+++async def test_setup_invalid_mode():+ """Test setup with invalid mode returns error."""+ result = await setup.handle(+ 'setup',+ {+ 'mode': 'invalid','api_key': None,'yes': False,'json': False,@@ -96,10 +89,57 @@ async def test_setup_invalid_profile():)assert 'error' in result+ assert 'Invalid mode' in result['error']+++async def test_run_checks_local():+ """Test run_checks returns expected structure for local mode."""+ checks = await setup.run_checks('local')++ assert isinstance(checks, dict)+ assert 'browser_use_package' in checks+ assert checks['browser_use_package']['status'] in ('ok', 'error')++ # Local mode should check browser+ assert 'browser' in checks+ assert checks['browser']['status'] in ('ok', 'error')++ # Local mode should NOT check api_key or cloudflared+ assert 'api_key' not in checks+ assert 'cloudflared' not in checks+++async def test_run_checks_remote():+ """Test run_checks returns expected structure for remote mode."""+ checks = await setup.run_checks('remote')++ assert isinstance(checks, dict)+ assert 'browser_use_package' in checks++ # Remote mode should check api_key and cloudflared+ assert 'api_key' in checks+ assert checks['api_key']['status'] in ('ok', 'missing')+ assert 'cloudflared' in checks+ assert checks['cloudflared']['status'] in ('ok', 'missing')++ # Remote mode should NOT check browser+ assert 'browser' not in checks+++async def test_run_checks_full():+ """Test run_checks returns expected structure for full mode."""+ checks = await setup.run_checks('full')++ assert isinstance(checks, dict)+ # Full mode should check everything+ assert 'browser_use_package' in checks+ assert 'browser' in checks+ assert 'api_key' in checks+ assert 'cloudflared' in checksdef test_plan_actions_no_actions_needed():- """Test plan_actions when nothing is needed."""+ """Test plan_actions when everything is ok."""checks = {'browser_use_package': {'status': 'ok'},'browser': {'status': 'ok'},@@ -132,17 +172,54 @@ def test_plan_actions_configure_api_key():assert any(a['type'] == 'configure_api_key' for a in actions)-async def test_check_browser_available():- """Test _check_browser when browser is available."""- with patch('browser_use.browser.profile.BrowserProfile'):- result = await setup._check_browser()- assert result['status'] == 'ok'+def test_plan_actions_prompt_api_key():+ """Test plan_actions prompts for API key when missing and not --yes."""+ checks = {+ 'api_key': {'status': 'missing'},+ }++ actions = setup.plan_actions(checks, 'remote', yes=False, api_key=None)+ assert any(a['type'] == 'prompt_api_key' for a in actions)+++def test_plan_actions_install_cloudflared():+ """Test plan_actions when cloudflared is missing."""+ checks = {+ 'cloudflared': {'status': 'missing'},+ }++ actions = setup.plan_actions(checks, 'remote', yes=True, api_key=None)+ assert any(a['type'] == 'install_cloudflared' for a in actions)+++async def test_check_browser():+ """Test _check_browser returns valid structure."""+ result = await setup._check_browser()++ assert isinstance(result, dict)+ assert 'status' in result+ assert result['status'] in ('ok', 'error')+ assert 'message' in result+++async def test_validate_setup_local():+ """Test validate_setup returns expected structure for local mode."""+ results = await setup.validate_setup('local')++ assert isinstance(results, dict)+ assert 'browser_use_import' in results+ assert 'browser_available' in results+ # Should not have remote-only checks+ assert 'api_key_available' not in results++async def test_validate_setup_remote():+ """Test validate_setup returns expected structure for remote mode."""+ results = await setup.validate_setup('remote')-async def test_check_browser_unavailable():- """Test _check_browser when browser is not available."""- with patch('browser_use.browser.profile.BrowserProfile', side_effect=Exception('Not available')):- result = await setup._check_browser()- assert result['status'] == 'error'+ assert isinstance(results, dict)+ assert 'browser_use_import' in results+ assert 'api_key_available' in results+ assert 'cloudflared_available' in results+ # Should not have local-only checks+ assert 'browser_available' not in results