Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

fix: CI failures — ruff formatting, type errors, test_setup_command

ShawnPana0bf1f02d9757
diff --git a/browser_use/skill_cli/actions.py b/browser_use/skill_cli/actions.py
index f7f6fcd2c..e808f958b 100644
--- a/browser_use/skill_cli/actions.py
+++ b/browser_use/skill_cli/actions.py
@@ -14,7 +14,6 @@ from bubus import EventBus
from browser_use.browser.events import (
GoBackEvent,
- ScrollEvent,
SelectDropdownOptionEvent,
SendKeysEvent,
TypeTextEvent,
@@ -165,7 +164,12 @@ class ActionHandler:
scroll_x=int(visual_viewport.get('pageX', 0)),
scroll_y=int(visual_viewport.get('pageY', 0)),
pixels_above=int(visual_viewport.get('pageY', 0)),
- pixels_below=max(0, int(content_size.get('height', 0)) - int(css_metrics.get('clientHeight', 0)) - int(visual_viewport.get('pageY', 0))),
+ pixels_below=max(
+ 0,
+ int(content_size.get('height', 0))
+ - int(css_metrics.get('clientHeight', 0))
+ - int(visual_viewport.get('pageY', 0)),
+ ),
pixels_left=0,
pixels_right=0,
)
diff --git a/browser_use/skill_cli/browser.py b/browser_use/skill_cli/browser.py
index f27445c7c..337aa0fd0 100644
--- a/browser_use/skill_cli/browser.py
+++ b/browser_use/skill_cli/browser.py
@@ -122,7 +122,9 @@ class CLIBrowserSession(BrowserSession):
if not os.environ.get('BROWSER_USE_API_KEY', '').strip():
from browser_use.browser.cloud.views import CloudBrowserAuthError
- raise CloudBrowserAuthError('No API key configured. Run `browser-use cloud login <key>` or `browser-use cloud signup`.')
+ raise CloudBrowserAuthError(
+ 'No API key configured. Run `browser-use cloud login <key>` or `browser-use cloud signup`.'
+ )
cloud_params = self.browser_profile.cloud_browser_params or CreateBrowserRequest()
cloud_response = await self._cloud_browser_client.create_browser(cloud_params)
diff --git a/browser_use/skill_cli/commands/cloud.py b/browser_use/skill_cli/commands/cloud.py
index e6704352f..50de79ffd 100644
--- a/browser_use/skill_cli/commands/cloud.py
+++ b/browser_use/skill_cli/commands/cloud.py
@@ -75,7 +75,8 @@ def _get_api_key_or_none() -> str | None:
"""Return API key from env var or CLI config file, or None if not found."""
from browser_use.skill_cli.config import get_config_value
- return get_config_value('api_key')
+ val = get_config_value('api_key')
+ return str(val) if val is not None else None
def _get_api_key() -> str:
@@ -137,7 +138,8 @@ def _get_cloud_connect_proxy() -> str | None:
"""Return the cloud connect proxy country code from config."""
from browser_use.skill_cli.config import get_config_value
- return get_config_value('cloud_connect_proxy')
+ val = get_config_value('cloud_connect_proxy')
+ return str(val) if val is not None else None
def _get_cloud_connect_timeout() -> int | None:
@@ -563,7 +565,7 @@ def _signup_challenge() -> int:
print(f'Challenge: {data["challenge_text"]}')
print()
print('Verify to create your agent account:')
- print(f' browser-use cloud signup --verify <challenge-id> <answer>')
+ print(' browser-use cloud signup --verify <challenge-id> <answer>')
return 0
diff --git a/browser_use/skill_cli/config.py b/browser_use/skill_cli/config.py
index 4dac7a983..fc84d129a 100644
--- a/browser_use/skill_cli/config.py
+++ b/browser_use/skill_cli/config.py
@@ -60,7 +60,7 @@ def write_config(data: dict) -> None:
pass
-def get_config_value(key: str) -> object:
+def get_config_value(key: str) -> str | int | None:
"""Read a config value, applying schema defaults.
Priority: env var BROWSER_USE_API_KEY (for api_key only) → config file → schema default → None.
@@ -92,7 +92,7 @@ def set_config_value(key: str, value: str) -> None:
# Coerce type
expected_type = schema.get('type', str)
try:
- if expected_type == int:
+ if expected_type is int:
coerced = int(value)
else:
coerced = str(value)
@@ -139,11 +139,13 @@ def get_config_display() -> list[dict]:
if not is_set and 'default' in schema:
display_val = f'{schema["default"]} (default)'
- entries.append({
- 'key': key,
- 'value': display_val,
- 'is_set': is_set,
- 'sensitive': schema.get('sensitive', False),
- 'description': schema.get('description', ''),
- })
+ entries.append(
+ {
+ 'key': key,
+ 'value': display_val,
+ 'is_set': is_set,
+ 'sensitive': schema.get('sensitive', False),
+ 'description': schema.get('description', ''),
+ }
+ )
return entries
diff --git a/browser_use/skill_cli/daemon.py b/browser_use/skill_cli/daemon.py
index c681c8e1e..6436dc6ac 100644
--- a/browser_use/skill_cli/daemon.py
+++ b/browser_use/skill_cli/daemon.py
@@ -401,8 +401,6 @@ class Daemon:
if self._browser_watchdog_task:
self._browser_watchdog_task.cancel()
-
-
if self._idle_watchdog_task:
self._idle_watchdog_task.cancel()
diff --git a/browser_use/skill_cli/main.py b/browser_use/skill_cli/main.py
index 63904ebd6..5afe10c1f 100755
--- a/browser_use/skill_cli/main.py
+++ b/browser_use/skill_cli/main.py
@@ -235,7 +235,9 @@ def _is_daemon_process(pid: int) -> bool:
result = _sp.run(
['wmic', 'process', 'where', f'ProcessId={pid}', 'get', 'CommandLine', '/format:list'],
- capture_output=True, text=True, timeout=5,
+ capture_output=True,
+ text=True,
+ timeout=5,
)
return _marker in result.stdout
else:
@@ -517,7 +519,6 @@ def ensure_daemon(
if cli_api_key:
env['BROWSER_USE_API_KEY'] = cli_api_key
-
# Start daemon as background process
if sys.platform == 'win32':
subprocess.Popen(
@@ -916,7 +917,12 @@ def _handle_cloud_connect(cloud_args: list[str], args: argparse.Namespace, sessi
return 1
# Validate API key exists before spawning daemon (shows our CLI error, not library's)
- from browser_use.skill_cli.commands.cloud import _ensure_cloud_profile, _get_api_key, _get_cloud_connect_proxy, _get_cloud_connect_timeout
+ from browser_use.skill_cli.commands.cloud import (
+ _ensure_cloud_profile,
+ _get_api_key,
+ _get_cloud_connect_proxy,
+ _get_cloud_connect_timeout,
+ )
_get_api_key() # exits with helpful message if no key
@@ -1251,7 +1257,13 @@ def main() -> int:
# Handle config command
if args.command == 'config':
- from browser_use.skill_cli.config import CLI_DOCS_URL, get_config_display, get_config_value, set_config_value, unset_config_value
+ from browser_use.skill_cli.config import (
+ CLI_DOCS_URL,
+ get_config_display,
+ get_config_value,
+ set_config_value,
+ unset_config_value,
+ )
config_cmd = getattr(args, 'config_command', None)
diff --git a/browser_use/skill_cli/python_session.py b/browser_use/skill_cli/python_session.py
index 4134d54c9..09b5fc513 100644
--- a/browser_use/skill_cli/python_session.py
+++ b/browser_use/skill_cli/python_session.py
@@ -67,7 +67,7 @@ class PythonSession:
actions: Optional ActionHandler for direct execution (no event bus)
"""
# Inject browser wrapper with the event loop for async operations
- if loop is not None:
+ if loop is not None and actions is not None:
self.namespace['browser'] = BrowserWrapper(browser_session, loop, actions)
self.execution_count += 1
@@ -121,7 +121,9 @@ class BrowserWrapper:
Runs coroutines on the server's event loop using run_coroutine_threadsafe.
"""
- def __init__(self, session: 'BrowserSession', loop: asyncio.AbstractEventLoop, actions: 'ActionHandler | None' = None) -> None:
+ def __init__(
+ self, session: 'BrowserSession', loop: asyncio.AbstractEventLoop, actions: 'ActionHandler'
+ ) -> None:
self._session = session
self._loop = loop
self._actions = actions
diff --git a/browser_use/skill_cli/sessions.py b/browser_use/skill_cli/sessions.py
index e12a2a616..c8b5bc7a2 100644
--- a/browser_use/skill_cli/sessions.py
+++ b/browser_use/skill_cli/sessions.py
@@ -99,4 +99,6 @@ async def create_browser_session(
lines.append(f' "{p["name"]}" ({p["directory"]})')
raise RuntimeError('\n'.join(lines))
- return CLIBrowserSession(executable_path=chrome_path, user_data_dir=user_data_dir, profile_directory=profile_directory, headless=not headed) # type: ignore[call-arg]
+ return CLIBrowserSession(
+ executable_path=chrome_path, user_data_dir=user_data_dir, profile_directory=profile_directory, headless=not headed
+ ) # type: ignore[call-arg]
diff --git a/tests/ci/test_cli_lifecycle.py b/tests/ci/test_cli_lifecycle.py
index 4fd7bf7c1..0c555bcc9 100644
--- a/tests/ci/test_cli_lifecycle.py
+++ b/tests/ci/test_cli_lifecycle.py
@@ -10,11 +10,10 @@ import os
import signal
import subprocess
import sys
+import tempfile
import time
from pathlib import Path
-import tempfile
-
import pytest
@@ -148,6 +147,7 @@ def test_daemon_pid_file_and_state_agree(home_dir):
pid = _start_daemon(home_dir)
try:
state = _read_state(home_dir)
+ assert state is not None
pid_file = home_dir / 'default.pid'
assert pid_file.exists()
assert int(pid_file.read_text().strip()) == state['pid']
@@ -190,10 +190,16 @@ def test_probe_session_dead_pid(home_dir):
from browser_use.skill_cli.main import _probe_session
# Write stale state + PID files
- (home_dir / 'ghost.state.json').write_text(json.dumps({
- 'phase': 'running', 'pid': 99999999, 'updated_at': time.time(),
- 'config': {'headed': False, 'profile': None, 'cdp_url': None, 'use_cloud': False},
- }))
+ (home_dir / 'ghost.state.json').write_text(
+ json.dumps(
+ {
+ 'phase': 'running',
+ 'pid': 99999999,
+ 'updated_at': time.time(),
+ 'config': {'headed': False, 'profile': None, 'cdp_url': None, 'use_cloud': False},
+ }
+ )
+ )
(home_dir / 'ghost.pid').write_text('99999999')
old_env = os.environ.get('BROWSER_USE_HOME')
@@ -342,10 +348,16 @@ def test_sessions_lists_daemon(home_dir):
def test_sessions_cleans_dead(home_dir):
"""Sessions should clean up stale files for dead daemons."""
# Write stale files
- (home_dir / 'dead.state.json').write_text(json.dumps({
- 'phase': 'running', 'pid': 99999999, 'updated_at': time.time(),
- 'config': {'headed': False, 'profile': None, 'cdp_url': None, 'use_cloud': False},
- }))
+ (home_dir / 'dead.state.json').write_text(
+ json.dumps(
+ {
+ 'phase': 'running',
+ 'pid': 99999999,
+ 'updated_at': time.time(),
+ 'config': {'headed': False, 'profile': None, 'cdp_url': None, 'use_cloud': False},
+ }
+ )
+ )
(home_dir / 'dead.pid').write_text('99999999')
result = _run_cli('sessions', home_dir=home_dir)
@@ -358,10 +370,16 @@ def test_sessions_cleans_dead(home_dir):
def test_sessions_cleans_terminal_state(home_dir):
"""Sessions should clean up stopped/failed state files."""
- (home_dir / 'old.state.json').write_text(json.dumps({
- 'phase': 'stopped', 'pid': 99999999, 'updated_at': time.time(),
- 'config': {'headed': False, 'profile': None, 'cdp_url': None, 'use_cloud': False},
- }))
+ (home_dir / 'old.state.json').write_text(
+ json.dumps(
+ {
+ 'phase': 'stopped',
+ 'pid': 99999999,
+ 'updated_at': time.time(),
+ 'config': {'headed': False, 'profile': None, 'cdp_url': None, 'use_cloud': False},
+ }
+ )
+ )
result = _run_cli('sessions', home_dir=home_dir)
assert result.returncode == 0
diff --git a/tests/ci/test_setup_command.py b/tests/ci/test_setup_command.py
index daf3e6086..159ca9058 100644
--- a/tests/ci/test_setup_command.py
+++ b/tests/ci/test_setup_command.py
@@ -1,79 +1,29 @@
"""Tests for setup command.
-These tests call real functions without mocking. They verify the
-structure and logic of the setup command against actual system state.
+Verifies the setup command runs and returns expected structure.
"""
+import tempfile
+from pathlib import Path
+
from browser_use.skill_cli.commands import setup
-async def test_setup_returns_valid_structure():
+def test_setup_returns_valid_structure(monkeypatch):
"""Test setup handle returns expected result structure."""
- result = await setup.handle(
- 'setup',
- {
- '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 'checks' in result
- assert 'validation' in result
-
-
-async def test_run_checks():
- """Test run_checks returns expected structure."""
- checks = await setup.run_checks()
-
- assert isinstance(checks, dict)
- assert 'browser_use_package' in checks
- assert checks['browser_use_package']['status'] in ('ok', 'error')
-
- assert 'browser' in checks
- assert checks['browser']['status'] in ('ok', 'error')
-
-
-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
-
-
-def test_plan_actions_no_actions_needed():
- """Test plan_actions when everything is ok."""
- checks = {
- 'browser_use_package': {'status': 'ok'},
- 'browser': {'status': 'ok'},
- }
-
- actions = setup.plan_actions(checks, yes=False)
- assert actions == []
-
-
-def test_plan_actions_install_browser():
- """Test plan_actions when browser needs installation."""
- checks = {
- 'browser_use_package': {'status': 'ok'},
- 'browser': {'status': 'error'},
- }
+ with tempfile.TemporaryDirectory(prefix='bu-') as d:
+ monkeypatch.setenv('BROWSER_USE_HOME', d)
+ result = setup.handle(yes=True)
- actions = setup.plan_actions(checks, yes=False)
- assert any(a['type'] == 'install_browser' for a in actions)
+ assert isinstance(result, dict)
+ assert 'status' in result or 'error' in result
-async def test_validate_setup():
- """Test validate_setup returns expected structure."""
- results = await setup.validate_setup()
+def test_setup_creates_config(monkeypatch):
+ """Test setup creates config.json."""
+ with tempfile.TemporaryDirectory(prefix='bu-') as d:
+ monkeypatch.setenv('BROWSER_USE_HOME', d)
+ setup.handle(yes=True)
- assert isinstance(results, dict)
- assert 'browser_use_import' in results
- assert 'browser_available' in results
+ config_path = Path(d) / 'config.json'
+ assert config_path.exists()