Skip to content

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

add `browser-use cloud` command: generic REST passthrough to Cloud API

ShawnPana91e987acdce7
diff --git a/browser_use/skill_cli/README.md b/browser_use/skill_cli/README.md
index c7490a322..f491c8e75 100644
--- a/browser_use/skill_cli/README.md
+++ b/browser_use/skill_cli/README.md
@@ -204,6 +204,40 @@ browser-use run "task" --llm gpt-4o # Specify LLM model
Requires an LLM API key (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, etc.).
+## Cloud API
+
+Generic REST passthrough to the Browser-Use Cloud API.
+
+| Command | Description |
+|---------|-------------|
+| `cloud login <api-key>` | Save API key |
+| `cloud logout` | Remove API key |
+| `cloud v2 GET <path>` | GET request to API v2 |
+| `cloud v2 POST <path> '<json>'` | POST request to API v2 |
+| `cloud v3 POST <path> '<json>'` | POST request to API v3 |
+| `cloud v2 poll <task-id>` | Poll task until done |
+| `cloud v2 --help` | Show API v2 endpoints (from OpenAPI spec) |
+| `cloud v3 --help` | Show API v3 endpoints |
+
+```bash
+# Save API key (or set BROWSER_USE_API_KEY env var)
+browser-use cloud login sk-abc123...
+
+# List browsers
+browser-use cloud v2 GET /browsers
+
+# Create a task
+browser-use cloud v2 POST /tasks '{"task":"Search for AI news","url":"https://google.com"}'
+
+# Poll until done
+browser-use cloud v2 poll <task-id>
+
+# Remove API key
+browser-use cloud logout
+```
+
+API key stored in `~/.config/browser-use/config.json` with `0600` permissions.
+
## Tunnels
Expose local dev servers to cloud browsers via Cloudflare tunnels.
diff --git a/browser_use/skill_cli/commands/cloud.py b/browser_use/skill_cli/commands/cloud.py
new file mode 100644
index 000000000..70cb64a35
--- /dev/null
+++ b/browser_use/skill_cli/commands/cloud.py
@@ -0,0 +1,518 @@
+"""Cloud API command — generic REST passthrough to Browser-Use Cloud.
+
+Stdlib only. No async, no SDK, no heavy imports.
+
+Usage:
+ browser-use cloud login <api-key>
+ browser-use cloud logout
+ browser-use cloud v2 GET /browsers
+ browser-use cloud v2 POST /tasks '{"task":"...","url":"https://..."}'
+ browser-use cloud v2 poll <task-id>
+ browser-use cloud v2 --help
+"""
+
+import json
+import os
+import sys
+import time
+import urllib.error
+import urllib.request
+from pathlib import Path
+
+# ---------------------------------------------------------------------------
+# Constants
+# ---------------------------------------------------------------------------
+
+_DEFAULT_BASE_URL = 'https://api.browser-use.com/api'
+_AUTH_HEADER = 'X-Browser-Use-API-Key'
+
+
+def _base_url(version: str) -> str:
+ env_key = f'BROWSER_USE_CLOUD_BASE_URL_{version.upper()}'
+ return os.environ.get(env_key, f'{_DEFAULT_BASE_URL}/{version}')
+
+
+def _spec_url(version: str) -> str:
+ env_key = f'BROWSER_USE_OPENAPI_SPEC_URL_{version.upper()}'
+ return os.environ.get(env_key, f'{_DEFAULT_BASE_URL}/{version}/openapi.json')
+
+
+# ---------------------------------------------------------------------------
+# API key persistence
+# ---------------------------------------------------------------------------
+
+
+def _get_config_path() -> Path:
+ from browser_use.skill_cli.utils import get_config_path
+
+ return get_config_path()
+
+
+def _read_config() -> dict:
+ path = _get_config_path()
+ if path.exists():
+ try:
+ return json.loads(path.read_text())
+ except (json.JSONDecodeError, OSError):
+ return {}
+ return {}
+
+
+def _write_config(data: dict) -> None:
+ path = _get_config_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(data, indent=2) + '\n')
+ try:
+ path.chmod(0o600)
+ except OSError:
+ pass
+
+
+def _get_api_key() -> str:
+ """Return API key from env var or config file. Exits with error if missing."""
+ key = os.environ.get('BROWSER_USE_API_KEY')
+ if key:
+ return key
+
+ config = _read_config()
+ key = config.get('api_key')
+ if key:
+ return key
+
+ print('Error: No API key found.', file=sys.stderr)
+ print('Set BROWSER_USE_API_KEY or run: browser-use cloud login <key>', file=sys.stderr)
+ sys.exit(1)
+
+
+def _save_api_key(key: str) -> None:
+ config = _read_config()
+ config['api_key'] = key
+ _write_config(config)
+
+
+def _remove_api_key() -> bool:
+ config = _read_config()
+ if 'api_key' not in config:
+ return False
+ del config['api_key']
+ path = _get_config_path()
+ if config:
+ _write_config(config)
+ else:
+ path.unlink(missing_ok=True)
+ return True
+
+
+# ---------------------------------------------------------------------------
+# HTTP helpers
+# ---------------------------------------------------------------------------
+
+
+def _http_request(method: str, url: str, body: bytes | None, api_key: str, timeout: float = 30.0) -> tuple[int, bytes]:
+ """Fire an HTTP request. Returns (status_code, response_body)."""
+ headers = {_AUTH_HEADER: api_key}
+ if body is not None:
+ headers['Content-Type'] = 'application/json'
+
+ req = urllib.request.Request(url, data=body, headers=headers, method=method.upper())
+ try:
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
+ return resp.status, resp.read()
+ except urllib.error.HTTPError as e:
+ return e.code, e.read()
+ except urllib.error.URLError as e:
+ print(f'Error: {e.reason}', file=sys.stderr)
+ sys.exit(1)
+
+
+def _print_json(data: bytes) -> None:
+ """Pretty-print JSON, raw fallback."""
+ try:
+ parsed = json.loads(data)
+ print(json.dumps(parsed, indent=2))
+ except (json.JSONDecodeError, ValueError):
+ sys.stdout.buffer.write(data)
+ sys.stdout.buffer.write(b'\n')
+ sys.stdout.buffer.flush()
+
+
+# ---------------------------------------------------------------------------
+# OpenAPI help
+# ---------------------------------------------------------------------------
+
+
+def _fetch_spec(version: str) -> bytes | None:
+ url = _spec_url(version)
+ try:
+ req = urllib.request.Request(url)
+ with urllib.request.urlopen(req, timeout=5) as resp:
+ return resp.read()
+ except Exception:
+ return None
+
+
+def _example_value(prop: dict, schemas: dict) -> object:
+ """Generate a placeholder value for an OpenAPI property."""
+ if '$ref' in prop:
+ ref_name = prop['$ref'].rsplit('/', 1)[-1]
+ if ref_name in schemas:
+ return _generate_body_example_dict(ref_name, schemas)
+ return {}
+
+ t = prop.get('type', 'string')
+ fmt = prop.get('format', '')
+ enum = prop.get('enum')
+
+ if enum:
+ return enum[0]
+ if t == 'string':
+ if fmt == 'uri' or fmt == 'url':
+ return 'https://example.com'
+ if fmt == 'date-time':
+ return '2025-01-01T00:00:00Z'
+ if 'email' in fmt:
+ return '...'
+ if t == 'integer':
+ return 0
+ if t == 'number':
+ return 0.0
+ if t == 'boolean':
+ return False
+ if t == 'array':
+ items = prop.get('items', {})
+ return [_example_value(items, schemas)]
+ if t == 'object':
+ props = prop.get('properties', {})
+ return {k: _example_value(v, schemas) for k, v in props.items()}
+ return '...'
+
+
+def _generate_body_example_dict(ref_name: str, schemas: dict) -> dict:
+ """Build a compact example dict from a $ref schema."""
+ schema = schemas.get(ref_name, {})
+ props = schema.get('properties', {})
+ required = set(schema.get('required', []))
+
+ result = {}
+ # Required fields first, then sorted optional
+ for key in sorted(props, key=lambda k: (k not in required, k)):
+ result[key] = _example_value(props[key], schemas)
+ return result
+
+
+def _generate_body_example(ref: str, schemas: dict) -> str:
+ """Return compact JSON string for a $ref."""
+ ref_name = ref.rsplit('/', 1)[-1]
+ obj = _generate_body_example_dict(ref_name, schemas)
+ return json.dumps(obj, separators=(',', ':'))
+
+
+def _find_body_ref(spec: dict, method: str, path: str) -> str | None:
+ """Find the $ref for request body of a given method+path in spec."""
+ paths = spec.get('paths', {})
+ path_obj = paths.get(path, {})
+ method_obj = path_obj.get(method.lower(), {})
+ body = method_obj.get('requestBody', {})
+ content = body.get('content', {})
+ json_media = content.get('application/json', {})
+ schema = json_media.get('schema', {})
+ return schema.get('$ref')
+
+
+def _match_path(spec_path: str, req_path: str) -> bool:
+ """Match an OpenAPI template path against a concrete path.
+
+ E.g. /tasks/{task_id} matches /tasks/abc123
+ """
+ spec_parts = spec_path.strip('/').split('/')
+ req_parts = req_path.strip('/').split('/')
+ if len(spec_parts) != len(req_parts):
+ return False
+ for sp, rp in zip(spec_parts, req_parts):
+ if sp.startswith('{') and sp.endswith('}'):
+ continue
+ if sp != rp:
+ return False
+ return True
+
+
+def _find_body_example(spec: dict, method: str, path: str) -> str | None:
+ """Find a body example for the given method+path, using template matching."""
+ schemas = spec.get('components', {}).get('schemas', {})
+ paths = spec.get('paths', {})
+
+ for spec_path in paths:
+ if _match_path(spec_path, path):
+ ref = _find_body_ref(spec, method, spec_path)
+ if ref:
+ return _generate_body_example(ref, schemas)
+ return None
+
+
+def _format_openapi_help(spec_data: bytes) -> str:
+ """Parse OpenAPI spec and render grouped endpoints."""
+ try:
+ spec = json.loads(spec_data)
+ except (json.JSONDecodeError, ValueError):
+ return ''
+
+ paths = spec.get('paths', {})
+ schemas = spec.get('components', {}).get('schemas', {})
+ info = spec.get('info', {})
+
+ lines: list[str] = []
+ title = info.get('title', 'API')
+ version = info.get('version', '')
+ lines.append(f'{title} {version}'.strip())
+ lines.append('')
+
+ # Group by tag
+ groups: dict[str, list[str]] = {}
+ for path, methods in sorted(paths.items()):
+ for method, details in sorted(methods.items()):
+ if method in ('parameters', 'summary', 'description'):
+ continue
+ tags = details.get('tags', ['Other'])
+ tag = tags[0] if tags else 'Other'
+ summary = details.get('summary', '')
+
+ # Build endpoint line
+ parts = [f' {method.upper():6s} {path}']
+ if summary:
+ parts.append(f' # {summary}')
+
+ # Parameters
+ params = details.get('parameters', [])
+ param_strs = []
+ for p in params:
+ name = p.get('name', '')
+ required = p.get('required', False)
+ marker = '*' if required else ''
+ param_strs.append(f'{name}{marker}')
+ if param_strs:
+ parts.append(f' params: {", ".join(param_strs)}')
+
+ # Body example
+ body_ref = _find_body_ref(spec, method, path)
+ if body_ref:
+ example = _generate_body_example(body_ref, schemas)
+ parts.append(f" body: '{example}'")
+
+ groups.setdefault(tag, []).append('\n'.join(parts) if len(parts) > 1 else parts[0])
+
+ for tag, endpoints in sorted(groups.items()):
+ lines.append(f'[{tag}]')
+ for ep in endpoints:
+ lines.append(ep)
+ lines.append('')
+
+ return '\n'.join(lines)
+
+
+def _static_help(version: str) -> str:
+ """Fallback help when OpenAPI spec is unavailable."""
+ return f"""Browser-Use Cloud API {version}
+
+Usage:
+ browser-use cloud {version} <METHOD> <path> [body]
+ browser-use cloud {version} poll <task-id>
+
+Examples:
+ browser-use cloud {version} GET /browsers
+ browser-use cloud {version} POST /tasks '{{"task":"Search for AI news","url":"https://google.com"}}'
+ browser-use cloud {version} GET /tasks/<task-id>
+ browser-use cloud {version} poll <task-id>
+
+(Could not fetch OpenAPI spec for live endpoint listing)
+"""
+
+
+# ---------------------------------------------------------------------------
+# Command handlers
+# ---------------------------------------------------------------------------
+
+
+def _cloud_login(argv: list[str]) -> int:
+ if not argv:
+ print('Usage: browser-use cloud login <api-key>', file=sys.stderr)
+ return 1
+
+ key = argv[0]
+ _save_api_key(key)
+ print('API key saved')
+ return 0
+
+
+def _cloud_logout() -> int:
+ if _remove_api_key():
+ print('API key removed')
+ else:
+ print('No API key to remove')
+ return 0
+
+
+def _cloud_rest(argv: list[str], version: str) -> int:
+ """Generic REST passthrough."""
+ if len(argv) < 2:
+ print(f'Usage: browser-use cloud {version} <METHOD> <path> [body]', file=sys.stderr)
+ return 1
+
+ method = argv[0].upper()
+ path = argv[1]
+ body_str = argv[2] if len(argv) > 2 else None
+
+ # Normalize path
+ if not path.startswith('/'):
+ path = '/' + path
+
+ url = f'{_base_url(version)}{path}'
+ api_key = _get_api_key()
+
+ body = body_str.encode() if body_str else None
+ status, resp_body = _http_request(method, url, body, api_key)
+
+ if 400 <= status < 500:
+ print(f'HTTP {status}', file=sys.stderr)
+ _print_json(resp_body)
+
+ # Try to suggest correct body from spec
+ spec_data = _fetch_spec(version)
+ if spec_data:
+ try:
+ spec = json.loads(spec_data)
+ example = _find_body_example(spec, method, path)
+ if example:
+ print(f"\nExpected body: '{example}'", file=sys.stderr)
+ except (json.JSONDecodeError, ValueError):
+ pass
+ return 2
+
+ if status >= 500:
+ print(f'HTTP {status}', file=sys.stderr)
+ _print_json(resp_body)
+ return 1
+
+ _print_json(resp_body)
+ return 0
+
+
+def _cloud_poll(argv: list[str], version: str) -> int:
+ """Poll GET /tasks/<id> until done."""
+ if not argv:
+ print(f'Usage: browser-use cloud {version} poll <task-id>', file=sys.stderr)
+ return 1
+
+ task_id = argv[0]
+ url = f'{_base_url(version)}/tasks/{task_id}'
+ api_key = _get_api_key()
+
+ while True:
+ status_code, resp_body = _http_request('GET', url, None, api_key)
+
+ if status_code >= 400:
+ print(f'\nHTTP {status_code}', file=sys.stderr)
+ _print_json(resp_body)
+ return 2
+
+ try:
+ data = json.loads(resp_body)
+ except (json.JSONDecodeError, ValueError):
+ print('\nError: invalid JSON response', file=sys.stderr)
+ return 1
+
+ task_status = data.get('status', 'unknown')
+ cost = data.get('cost', 0)
+ print(f'\rstatus: {task_status} cost: ${cost:.4f}', end='', file=sys.stderr, flush=True)
+
+ if task_status == 'finished':
+ print('', file=sys.stderr) # newline
+ _print_json(resp_body)
+ return 0
+
+ if task_status == 'failed':
+ print('', file=sys.stderr)
+ _print_json(resp_body)
+ return 2
+
+ time.sleep(2)
+
+
+def _cloud_help(version: str) -> int:
+ """Show OpenAPI-driven help for a version."""
+ spec_data = _fetch_spec(version)
+ if spec_data:
+ formatted = _format_openapi_help(spec_data)
+ if formatted:
+ print(formatted)
+ return 0
+
+ print(_static_help(version))
+ return 0
+
+
+def _cloud_versioned(argv: list[str], version: str) -> int:
+ """Route versioned subcommands: poll, help, or REST passthrough."""
+ if not argv:
+ return _cloud_help(version)
+
+ first = argv[0]
+
+ if first in ('--help', 'help', '-h'):
+ return _cloud_help(version)
+
+ if first == 'poll':
+ return _cloud_poll(argv[1:], version)
+
+ # REST passthrough: METHOD path [body]
+ return _cloud_rest(argv, version)
+
+
+# ---------------------------------------------------------------------------
+# Main dispatcher
+# ---------------------------------------------------------------------------
+
+
+def handle_cloud_command(argv: list[str]) -> int:
+ """Main dispatcher for `browser-use cloud ...`."""
+ if not argv:
+ _print_cloud_usage()
+ return 1
+
+ subcmd = argv[0]
+
+ if subcmd == 'login':
+ return _cloud_login(argv[1:])
+
+ if subcmd == 'logout':
+ return _cloud_logout()
+
+ if subcmd in ('v2', 'v3'):
+ return _cloud_versioned(argv[1:], subcmd)
+
+ if subcmd in ('--help', 'help', '-h'):
+ _print_cloud_usage()
+ return 0
+
+ print(f'Unknown cloud subcommand: {subcmd}', file=sys.stderr)
+ _print_cloud_usage()
+ return 1
+
+
+def _print_cloud_usage() -> None:
+ print('Usage: browser-use cloud <command>')
+ print()
+ print('Commands:')
+ print(' login <api-key> Save API key')
+ print(' logout Remove API key')
+ print(' v2 <METHOD> <path> [body] REST passthrough (API v2)')
+ print(' v3 <METHOD> <path> [body] REST passthrough (API v3)')
+ print(' v2 poll <task-id> Poll task until done')
+ print(' v2 --help Show API v2 endpoints')
+ print(' v3 --help Show API v3 endpoints')
+ print()
+ print('Examples:')
+ print(' browser-use cloud login sk-abc123...')
+ print(' browser-use cloud v2 GET /browsers')
+ print(' browser-use cloud v2 POST /tasks \'{"task":"...","url":"https://..."}\'')
+ print(' browser-use cloud v2 poll <task-id>')
diff --git a/browser_use/skill_cli/main.py b/browser_use/skill_cli/main.py
index ee87fbe34..fdbc487fe 100755
--- a/browser_use/skill_cli/main.py
+++ b/browser_use/skill_cli/main.py
@@ -288,6 +288,14 @@ def build_parser() -> argparse.ArgumentParser:
browser-use run "task" --llm gpt-4o # Specify model (requires API key)
browser-use open https://example.com""")
+ epilog_parts.append("""
+Cloud API:
+ browser-use cloud login <api-key> # Save API key
+ browser-use cloud v2 GET /browsers # List browsers
+ browser-use cloud v2 POST /tasks '{...}' # Create task
+ browser-use cloud v2 poll <task-id> # Poll task until done
+ browser-use cloud v2 --help # Show API endpoints""")
+
epilog_parts.append("""
Setup:
browser-use install # Install Chromium browser
@@ -535,6 +543,13 @@ Setup:
# close
subparsers.add_parser('close', help='Close browser and stop daemon')
+ # -------------------------------------------------------------------------
+ # Cloud API (Generic REST passthrough)
+ # -------------------------------------------------------------------------
+
+ cloud_p = subparsers.add_parser('cloud', help='Browser-Use Cloud API')
+ cloud_p.add_argument('cloud_args', nargs=argparse.REMAINDER, help='cloud subcommand args')
+
# -------------------------------------------------------------------------
# Profile Management
# -------------------------------------------------------------------------
@@ -565,6 +580,12 @@ def main() -> int:
parser.print_help()
return 0
+ # Handle cloud subcommands without starting daemon
+ if args.command == 'cloud':
+ from browser_use.skill_cli.commands.cloud import handle_cloud_command
+
+ return handle_cloud_command(getattr(args, 'cloud_args', []))
+
# Handle profile subcommands without starting daemon
if args.command == 'profile':
from browser_use.skill_cli.commands.profile import handle_profile_command
diff --git a/skills/browser-use/SKILL.md b/skills/browser-use/SKILL.md
index bc5619c0b..7cbba789c 100644
--- a/skills/browser-use/SKILL.md
+++ b/skills/browser-use/SKILL.md
@@ -173,6 +173,21 @@ browser-use run "task" --llm gpt-4o # Specify LLM model
browser-use run "task" --llm claude-sonnet-4-20250514
```
+### Cloud API
+```bash
+browser-use cloud login <api-key> # Save API key
+browser-use cloud logout # Remove API key
+browser-use cloud v2 GET /browsers # List browsers
+browser-use cloud v2 POST /tasks '{"task":"...","url":"https://..."}' # Create task
+browser-use cloud v3 POST /sessions '{"task":"...","model":"bu-mini"}' # Create session
+browser-use cloud v2 GET /tasks/<task-id> # Get task status
+browser-use cloud v2 poll <task-id> # Poll task until done
+browser-use cloud v2 --help # Show API v2 endpoints
+browser-use cloud v3 --help # Show API v3 endpoints
+```
+
+API key: env var `BROWSER_USE_API_KEY` or `browser-use cloud login`. Stored in `~/.config/browser-use/config.json`.
+
### Tunnels
```bash
browser-use tunnel <port> # Start tunnel (returns URL)
diff --git a/tests/ci/test_cli_cloud.py b/tests/ci/test_cli_cloud.py
new file mode 100644
index 000000000..9e8cc30ee
--- /dev/null
+++ b/tests/ci/test_cli_cloud.py
@@ -0,0 +1,282 @@
+"""Tests for browser-use cloud CLI command."""
+
+import json
+import subprocess
+import sys
+from pathlib import Path
+
+from pytest_httpserver import HTTPServer
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def run_cli(*args: str, env_override: dict | None = None) -> subprocess.CompletedProcess:
+ """Run the CLI as a subprocess, returning the result."""
+ import os
+
+ env = os.environ.copy()
+ # Prevent real API key from leaking into tests
+ env.pop('BROWSER_USE_API_KEY', None)
+ if env_override:
+ env.update(env_override)
+
+ return subprocess.run(
+ [sys.executable, '-m', 'browser_use.skill_cli.main', 'cloud', *args],
+ capture_output=True,
+ text=True,
+ env=env,
+ timeout=15,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Login / Logout
+# ---------------------------------------------------------------------------
+
+
+def test_cloud_no_args_shows_usage():
+ result = run_cli()
+ # No args → usage on stdout, exit 1
+ assert result.returncode == 1
+ assert 'Usage' in result.stdout
+ assert 'login' in result.stdout
+
+
+def test_cloud_login_saves_key(tmp_path: Path):
+ config_path = tmp_path / 'config.json'
+ result = run_cli(
+ 'login',
+ 'sk-test-key-123',
+ env_override={
+ 'XDG_CONFIG_HOME': str(tmp_path),
+ },
+ )
+ assert result.returncode == 0
+ assert 'saved' in result.stdout.lower()
+
+ # Verify file was written
+ real_config = tmp_path / 'browser-use' / 'config.json'
+ assert real_config.exists()
+ data = json.loads(real_config.read_text())
+ assert data['api_key'] == 'sk-test-key-123'
+
+
+def test_cloud_logout_removes_key(tmp_path: Path):
+ # First save a key
+ config_dir = tmp_path / 'browser-use'
+ config_dir.mkdir(parents=True)
+ config_file = config_dir / 'config.json'
+ config_file.write_text(json.dumps({'api_key': 'sk-remove-me'}))
+
+ result = run_cli(
+ 'logout',
+ env_override={'XDG_CONFIG_HOME': str(tmp_path)},
+ )
+ assert result.returncode == 0
+ assert 'removed' in result.stdout.lower()
+
+ # Config file should be deleted (was only key)
+ assert not config_file.exists()
+
+
+def test_cloud_logout_no_key(tmp_path: Path):
+ result = run_cli(
+ 'logout',
+ env_override={'XDG_CONFIG_HOME': str(tmp_path)},
+ )
+ assert result.returncode == 0
+ assert 'no api key' in result.stdout.lower()
+
+
+# ---------------------------------------------------------------------------
+# REST passthrough
+# ---------------------------------------------------------------------------
+
+
+def test_cloud_rest_get(httpserver: HTTPServer):
+ httpserver.expect_request('/api/v2/browsers', method='GET').respond_with_json(
+ {'browsers': [{'id': 'b1', 'status': 'running'}]}
+ )
+
+ result = run_cli(
+ 'v2',
+ 'GET',
+ '/browsers',
+ env_override={
+ 'BROWSER_USE_API_KEY': 'sk-test',
+ 'BROWSER_USE_CLOUD_BASE_URL_V2': httpserver.url_for('/api/v2'),
+ },
+ )
+ assert result.returncode == 0
+ data = json.loads(result.stdout)
+ assert data['browsers'][0]['id'] == 'b1'
+
+
+def test_cloud_rest_post_with_body(httpserver: HTTPServer):
+ body_to_send = {'task': 'Search for AI news', 'url': 'https://google.com'}
+
+ def handler(request):
+ assert request.content_type == 'application/json'
+ received = json.loads(request.data)
+ assert received == body_to_send
+ return json.dumps({'id': 'task-1', 'status': 'created'})
+
+ httpserver.expect_request('/api/v2/tasks', method='POST').respond_with_handler(handler)
+
+ result = run_cli(
+ 'v2',
+ 'POST',
+ '/tasks',
+ json.dumps(body_to_send),
+ env_override={
+ 'BROWSER_USE_API_KEY': 'sk-test',
+ 'BROWSER_USE_CLOUD_BASE_URL_V2': httpserver.url_for('/api/v2'),
+ },
+ )
+ assert result.returncode == 0
+ data = json.loads(result.stdout)
+ assert data['id'] == 'task-1'
+
+
+def test_cloud_rest_sends_auth_header(httpserver: HTTPServer):
+ def handler(request):
+ assert request.headers.get('X-Browser-Use-API-Key') == 'sk-secret-key'
+ return json.dumps({'ok': True})
+
+ httpserver.expect_request('/api/v2/test', method='GET').respond_with_handler(handler)
+
+ result = run_cli(
+ 'v2',
+ 'GET',
+ '/test',
+ env_override={
+ 'BROWSER_USE_API_KEY': 'sk-secret-key',
+ 'BROWSER_USE_CLOUD_BASE_URL_V2': httpserver.url_for('/api/v2'),
+ },
+ )
+ assert result.returncode == 0
+
+
+def test_cloud_rest_4xx_exits_2(httpserver: HTTPServer):
+ httpserver.expect_request('/api/v2/bad', method='GET').respond_with_json({'error': 'not found'}, status=404)
+
+ result = run_cli(
+ 'v2',
+ 'GET',
+ '/bad',
+ env_override={
+ 'BROWSER_USE_API_KEY': 'sk-test',
+ 'BROWSER_USE_CLOUD_BASE_URL_V2': httpserver.url_for('/api/v2'),
+ # Prevent spec fetch from hanging
+ 'BROWSER_USE_OPENAPI_SPEC_URL_V2': 'http://127.0.0.1:1/nope',
+ },
+ )
+ assert result.returncode == 2
+ assert 'HTTP 404' in result.stderr
+
+
+def test_cloud_rest_no_api_key_errors(tmp_path: Path):
+ result = run_cli(
+ 'v2',
+ 'GET',
+ '/browsers',
+ env_override={
+ 'XDG_CONFIG_HOME': str(tmp_path),
+ },
+ )
+ # _get_api_key calls sys.exit(1)
+ assert result.returncode == 1
+ assert 'no api key' in result.stderr.lower()
+
+
+# ---------------------------------------------------------------------------
+# Polling
+# ---------------------------------------------------------------------------
+
+
+def test_cloud_poll_finishes(httpserver: HTTPServer):
+ # First call: running, second call: finished
+ call_count = {'n': 0}
+
+ def handler(request):
+ call_count['n'] += 1
+ if call_count['n'] == 1:
+ return json.dumps({'status': 'running', 'cost': 0.0012})
+ return json.dumps({'status': 'finished', 'cost': 0.0050, 'result': 'done'})
+
+ httpserver.expect_request('/api/v2/tasks/t-123', method='GET').respond_with_handler(handler)
+
+ result = run_cli(
+ 'v2',
+ 'poll',
+ 't-123',
+ env_override={
+ 'BROWSER_USE_API_KEY': 'sk-test',
+ 'BROWSER_USE_CLOUD_BASE_URL_V2': httpserver.url_for('/api/v2'),
+ },
+ )
+ assert result.returncode == 0
+ data = json.loads(result.stdout)
+ assert data['status'] == 'finished'
+ assert 'status: finished' in result.stderr
+
+
+def test_cloud_poll_failed_exits_2(httpserver: HTTPServer):
+ httpserver.expect_request('/api/v2/tasks/t-fail', method='GET').respond_with_json(
+ {'status': 'failed', 'cost': 0.0001, 'error': 'timeout'}
+ )
+
+ result = run_cli(
+ 'v2',
+ 'poll',
+ 't-fail',
+ env_override={
+ 'BROWSER_USE_API_KEY': 'sk-test',
+ 'BROWSER_USE_CLOUD_BASE_URL_V2': httpserver.url_for('/api/v2'),
+ },
+ )
+ assert result.returncode == 2
+
+
+# ---------------------------------------------------------------------------
+# URL construction
+# ---------------------------------------------------------------------------
+
+
+def test_cloud_url_construction(httpserver: HTTPServer):
+ """Path without leading / should still work."""
+ httpserver.expect_request('/api/v2/browsers', method='GET').respond_with_json({'ok': True})
+
+ result = run_cli(
+ 'v2',
+ 'GET',
+ 'browsers', # no leading /
+ env_override={
+ 'BROWSER_USE_API_KEY': 'sk-test',
+ 'BROWSER_USE_CLOUD_BASE_URL_V2': httpserver.url_for('/api/v2'),
+ },
+ )
+ assert result.returncode == 0
+ data = json.loads(result.stdout)
+ assert data['ok'] is True
+
+
+# ---------------------------------------------------------------------------
+# Help
+# ---------------------------------------------------------------------------
+
+
+def test_cloud_help_flag():
+ """--help should show something useful even without spec."""
+ result = run_cli(
+ 'v2',
+ '--help',
+ env_override={
+ # Point to unreachable spec URL so static fallback is used
+ 'BROWSER_USE_OPENAPI_SPEC_URL_V2': 'http://127.0.0.1:1/nope',
+ },
+ )
+ assert result.returncode == 0
+ assert 'browser-use cloud v2' in result.stdout.lower()