Skip to content

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

consolidate CLI files under ~/.browser-use/, add profile-use integration and doctor checks

ShawnPanad3e18184960a
diff --git a/browser_use/skill_cli/README.md b/browser_use/skill_cli/README.md
index ed3d8af5f..0c905359f 100644
--- a/browser_use/skill_cli/README.md
+++ b/browser_use/skill_cli/README.md
@@ -237,7 +237,7 @@ browser-use cloud v2 poll <task-id>
browser-use cloud logout
```
-API key stored in `~/.config/browser-use/config.json` with `0600` permissions.
+API key stored in `~/.browser-use/config.json` with `0600` permissions.
## Tunnels
diff --git a/browser_use/skill_cli/commands/doctor.py b/browser_use/skill_cli/commands/doctor.py
index 1146e6698..77c15a212 100644
--- a/browser_use/skill_cli/commands/doctor.py
+++ b/browser_use/skill_cli/commands/doctor.py
@@ -25,6 +25,12 @@ async def handle() -> dict[str, Any]:
# 3. Network connectivity (basic check)
checks['network'] = await _check_network()
+ # 4. Optional: cloudflared (for browser-use tunnel)
+ checks['cloudflared'] = _check_cloudflared()
+
+ # 5. Optional: profile-use (for browser-use profile)
+ checks['profile_use'] = _check_profile_use()
+
# Determine overall status
all_ok = all(check.get('status') == 'ok' for check in checks.values())
@@ -95,6 +101,40 @@ async def _check_network() -> dict[str, Any]:
}
+def _check_cloudflared() -> dict[str, Any]:
+ """Check if cloudflared is available (needed for browser-use tunnel)."""
+ from browser_use.skill_cli.tunnel import get_tunnel_manager
+
+ status = get_tunnel_manager().get_status()
+ if status['available']:
+ return {
+ 'status': 'ok',
+ 'message': f'cloudflared installed ({status["path"]})',
+ }
+ return {
+ 'status': 'missing',
+ 'message': 'cloudflared not installed (needed for browser-use tunnel)',
+ 'fix': 'brew install cloudflared',
+ }
+
+
+def _check_profile_use() -> dict[str, Any]:
+ """Check if profile-use binary is available (needed for browser-use profile)."""
+ from browser_use.skill_cli.profile_use import get_profile_use_binary
+
+ binary = get_profile_use_binary()
+ if binary:
+ return {
+ 'status': 'ok',
+ 'message': f'profile-use installed ({binary})',
+ }
+ return {
+ 'status': 'missing',
+ 'message': 'profile-use not installed (needed for browser-use profile)',
+ 'fix': 'browser-use profile update',
+ }
+
+
def _summarize_checks(checks: dict[str, dict[str, Any]]) -> str:
"""Generate a summary of check results."""
ok = sum(1 for c in checks.values() if c.get('status') == 'ok')
diff --git a/browser_use/skill_cli/commands/profile.py b/browser_use/skill_cli/commands/profile.py
deleted file mode 100644
index 6823ca848..000000000
--- a/browser_use/skill_cli/commands/profile.py
+++ /dev/null
@@ -1,208 +0,0 @@
-"""Profile management command handlers.
-
-Local Chrome profile management for browser-use CLI.
-"""
-
-import argparse
-import json
-import logging
-import sys
-from typing import Any
-
-logger = logging.getLogger(__name__)
-
-
-def handle_profile_command(args: argparse.Namespace) -> int:
- """Handle profile subcommands.
-
- Routes to local profile implementation.
- """
- command = args.profile_command
-
- if command is None:
- _print_usage()
- return 1
-
- if command == 'list':
- return _list_local_profiles(args)
- elif command == 'get':
- return _get_local_profile(args)
- elif command == 'cookies':
- return _handle_cookies(args)
- else:
- _print_usage()
- return 1
-
-
-def _print_usage() -> None:
- """Print profile command usage."""
- print('Usage: browser-use profile <command>')
- print()
- print('Commands:')
- print(' list List local Chrome profiles')
- print(' get <id> Get profile details')
- print(' cookies <id> Show cookies by domain')
-
-
-# -----------------------------------------------------------------------------
-# List profiles
-# -----------------------------------------------------------------------------
-
-
-def _list_local_profiles(args: argparse.Namespace) -> int:
- """List local Chrome profiles."""
- profiles = list_local_chrome_profiles()
-
- if getattr(args, 'json', False):
- print(json.dumps({'profiles': profiles}))
- else:
- if profiles:
- print('Local Chrome profiles:')
- for p in profiles:
- print(f' {p["id"]}: {p["name"]} ({p["email"]})')
- else:
- print('No Chrome profiles found')
-
- return 0
-
-
-# -----------------------------------------------------------------------------
-# Get profile
-# -----------------------------------------------------------------------------
-
-
-def _get_local_profile(args: argparse.Namespace) -> int:
- """Get local Chrome profile details."""
- profiles = list_local_chrome_profiles()
- profile_id = args.id
-
- for p in profiles:
- if p['id'] == profile_id or p['name'] == profile_id:
- if getattr(args, 'json', False):
- print(json.dumps(p))
- else:
- print(f'Profile: {p["id"]}')
- print(f' Name: {p["name"]}')
- print(f' Email: {p["email"]}')
- return 0
-
- print(f'Error: Profile "{profile_id}" not found', file=sys.stderr)
- return 1
-
-
-# -----------------------------------------------------------------------------
-# Cookies
-# -----------------------------------------------------------------------------
-
-
-def _handle_cookies(args: argparse.Namespace) -> int:
- """Handle 'profile cookies <id>' command."""
- return _list_profile_cookies(args)
-
-
-def _list_profile_cookies(args: argparse.Namespace) -> int:
- """List cookies by domain in a local Chrome profile."""
- import asyncio
-
- from browser_use.skill_cli.sessions import create_browser_session
-
- # Get local profiles
- local_profiles = list_local_chrome_profiles()
- if not local_profiles:
- print('Error: No local Chrome profiles found', file=sys.stderr)
- return 1
-
- # Find the matching profile
- profile_arg = args.id
- selected_profile = None
- for p in local_profiles:
- if p['id'] == profile_arg or p['name'] == profile_arg:
- selected_profile = p
- break
-
- if not selected_profile:
- print(f'Error: Profile "{profile_arg}" not found', file=sys.stderr)
- print('Available profiles:')
- for p in local_profiles:
- print(f' {p["id"]}: {p["name"]}')
- return 1
-
- profile_id = selected_profile['id']
- print(f'Loading cookies from: {selected_profile["name"]} ({selected_profile["email"]})')
-
- async def get_cookies():
- local_session = await create_browser_session(headed=False, profile=profile_id)
- await local_session.start()
- try:
- cookies = await local_session._cdp_get_cookies()
- return cookies
- finally:
- await local_session.kill()
-
- try:
- cookies = asyncio.get_event_loop().run_until_complete(get_cookies())
- except RuntimeError:
- cookies = asyncio.run(get_cookies())
-
- # Group cookies by domain
- domains: dict[str, int] = {}
- for cookie in cookies:
- domain = cookie.get('domain', 'unknown')
- # Normalize domain (remove leading dot)
- if domain.startswith('.'):
- domain = domain[1:]
- domains[domain] = domains.get(domain, 0) + 1
-
- # Sort by count descending
- sorted_domains = sorted(domains.items(), key=lambda x: x[1], reverse=True)
-
- if getattr(args, 'json', False):
- print(json.dumps({'domains': dict(sorted_domains), 'total_cookies': len(cookies)}))
- else:
- print(f'\nCookies by domain ({len(cookies)} total):')
- for domain, count in sorted_domains[:20]: # Show top 20
- print(f' {domain}: {count}')
- if len(sorted_domains) > 20:
- print(f' ... and {len(sorted_domains) - 20} more domains')
-
- return 0
-
-
-# -----------------------------------------------------------------------------
-# Helpers
-# -----------------------------------------------------------------------------
-
-
-def list_local_chrome_profiles() -> list[dict[str, Any]]:
- """List local Chrome profiles from the Local State file."""
- import platform
- from pathlib import Path
-
- # Find Chrome Local State file
- system = platform.system()
- if system == 'Darwin':
- local_state = Path.home() / 'Library/Application Support/Google/Chrome/Local State'
- elif system == 'Windows':
- local_state = Path.home() / 'AppData/Local/Google/Chrome/User Data/Local State'
- else:
- local_state = Path.home() / '.config/google-chrome/Local State'
-
- if not local_state.exists():
- return []
-
- try:
- data = json.loads(local_state.read_text())
- profiles_info = data.get('profile', {}).get('info_cache', {})
-
- profiles = []
- for profile_id, info in profiles_info.items():
- profiles.append(
- {
- 'id': profile_id,
- 'name': info.get('name', profile_id),
- 'email': info.get('user_name', ''),
- }
- )
- return profiles
- except Exception:
- return []
diff --git a/browser_use/skill_cli/install.sh b/browser_use/skill_cli/install.sh
index d31181f10..38940523c 100755
--- a/browser_use/skill_cli/install.sh
+++ b/browser_use/skill_cli/install.sh
@@ -357,6 +357,19 @@ install_chromium() {
log_success "Chromium installed"
}
+install_profile_use() {
+ log_info "Installing profile-use..."
+
+ mkdir -p "$HOME/.browser-use/bin"
+ INSTALL_DIR="$HOME/.browser-use/bin" curl -fsSL https://browser-use.com/profile/cli/install.sh | sh
+
+ if [ -x "$HOME/.browser-use/bin/profile-use" ]; then
+ log_success "profile-use installed"
+ else
+ log_warn "profile-use installation failed (will auto-download on first use)"
+ fi
+}
+
# =============================================================================
# PATH configuration
# =============================================================================
@@ -511,13 +524,16 @@ main() {
# Step 5: Install Chromium
install_chromium
- # Step 6: Configure PATH
+ # Step 6: Install profile-use
+ install_profile_use
+
+ # Step 7: Configure PATH
configure_path
- # Step 7: Validate
+ # Step 8: Validate
validate
- # Step 8: Print next steps
+ # Step 9: Print next steps
print_next_steps
}
diff --git a/browser_use/skill_cli/main.py b/browser_use/skill_cli/main.py
index 32fef987c..ded0f6ce0 100755
--- a/browser_use/skill_cli/main.py
+++ b/browser_use/skill_cli/main.py
@@ -137,31 +137,16 @@ if '--template' in sys.argv:
# =============================================================================
-def _get_runtime_dir() -> Path:
- """Get runtime directory for daemon files.
+def _get_home_dir() -> Path:
+ """Get browser-use home directory.
- Must match utils.get_runtime_dir() — same env vars, same fallback chain.
+ Must match utils.get_home_dir().
"""
- env_dir = os.environ.get('BROWSER_USE_RUNTIME_DIR')
- if env_dir:
- d = Path(env_dir)
- d.mkdir(parents=True, exist_ok=True)
- return d
-
- xdg = os.environ.get('XDG_RUNTIME_DIR')
- if xdg:
- d = Path(xdg) / 'browser-use'
- d.mkdir(parents=True, exist_ok=True)
- return d
-
- home_dir = Path.home() / '.browser-use' / 'run'
- try:
- home_dir.mkdir(parents=True, exist_ok=True)
- return home_dir
- except OSError:
- pass
-
- d = Path(tempfile.gettempdir()) / 'browser-use'
+ env = os.environ.get('BROWSER_USE_HOME')
+ if env:
+ d = Path(env).expanduser()
+ else:
+ d = Path.home() / '.browser-use'
d.mkdir(parents=True, exist_ok=True)
return d
@@ -174,7 +159,7 @@ def _get_socket_path(session: str = 'default') -> str:
if sys.platform == 'win32':
port = 49152 + zlib.adler32(session.encode()) % 16383
return f'tcp://127.0.0.1:{port}'
- return str(_get_runtime_dir() / f'browser-use-{session}.sock')
+ return str(_get_home_dir() / f'{session}.sock')
def _get_pid_path(session: str = 'default') -> Path:
@@ -182,7 +167,7 @@ def _get_pid_path(session: str = 'default') -> Path:
Must match utils.get_pid_path().
"""
- return _get_runtime_dir() / f'browser-use-{session}.pid'
+ return _get_home_dir() / f'{session}.pid'
def _connect_to_daemon(timeout: float = 60.0, session: str = 'default') -> socket.socket:
@@ -621,19 +606,7 @@ Setup:
# Profile Management
# -------------------------------------------------------------------------
- profile_p = subparsers.add_parser('profile', help='Manage local browser profiles')
- profile_sub = profile_p.add_subparsers(dest='profile_command')
-
- # profile list
- profile_sub.add_parser('list', help='List local Chrome profiles')
-
- # profile get <id>
- p = profile_sub.add_parser('get', help='Get profile details')
- p.add_argument('id', help='Profile ID or name')
-
- # profile cookies <id>
- p = profile_sub.add_parser('cookies', help='List cookies by domain')
- p.add_argument('id', help='Profile ID or name (e.g. "Default", "Profile 1")')
+ subparsers.add_parser('profile', help='Manage browser profiles (profile-use)')
return parser
@@ -692,12 +665,11 @@ def _handle_cloud_connect(cloud_args: list[str], args: argparse.Namespace, sessi
def _handle_sessions(args: argparse.Namespace) -> int:
"""List active daemon sessions."""
- runtime_dir = _get_runtime_dir()
+ home_dir = _get_home_dir()
sessions: list[dict] = []
- for pid_file in sorted(runtime_dir.glob('browser-use-*.pid')):
- stem = pid_file.stem # browser-use-<session>
- name = stem[len('browser-use-') :]
+ for pid_file in sorted(home_dir.glob('*.pid')):
+ name = pid_file.stem
if not name:
continue
@@ -755,14 +727,13 @@ def _handle_sessions(args: argparse.Namespace) -> int:
def _handle_close_all(args: argparse.Namespace) -> int:
"""Close all active sessions."""
- runtime_dir = _get_runtime_dir()
+ home_dir = _get_home_dir()
# Snapshot the list first to avoid mutating during iteration
- pid_files = list(runtime_dir.glob('browser-use-*.pid'))
+ pid_files = list(home_dir.glob('*.pid'))
closed = 0
for pid_file in pid_files:
- stem = pid_file.stem
- name = stem[len('browser-use-') :]
+ name = pid_file.stem
if not name:
continue
@@ -784,16 +755,20 @@ def _handle_close_all(args: argparse.Namespace) -> int:
return 0
-def _migrate_legacy_socket() -> None:
- """One-time cleanup of old single-socket daemon (pre-multi-session)."""
+def _migrate_legacy_files() -> None:
+ """One-time cleanup of old daemon files and config migration."""
+ # Migrate config from old XDG location
+ from browser_use.skill_cli.utils import migrate_legacy_paths
+
+ migrate_legacy_paths()
+
+ # Clean up old single-socket daemon (pre-multi-session)
legacy_path = Path(tempfile.gettempdir()) / 'browser-use-cli.sock'
if sys.platform == 'win32':
- # Old Windows path was tcp://127.0.0.1:49200 — try to connect and shut down
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.5)
sock.connect(('127.0.0.1', 49200))
- # Send shutdown
req = json.dumps({'id': 'legacy', 'action': 'shutdown', 'params': {}}) + '\n'
sock.sendall(req.encode())
sock.close()
@@ -808,9 +783,19 @@ def _migrate_legacy_socket() -> None:
sock.sendall(req.encode())
sock.close()
except OSError:
- # Stale socket — just remove
legacy_path.unlink(missing_ok=True)
+ # Clean up old ~/.browser-use/run/ directory (stale PID/socket files)
+ old_run_dir = Path.home() / '.browser-use' / 'run'
+ if old_run_dir.is_dir():
+ for stale_file in old_run_dir.glob('browser-use-*'):
+ stale_file.unlink(missing_ok=True)
+ # Remove the directory if empty
+ try:
+ old_run_dir.rmdir()
+ except OSError:
+ pass
+
def main() -> int:
"""Main entry point."""
@@ -844,11 +829,17 @@ def main() -> int:
return handle_cloud_command(cloud_args)
- # Handle profile subcommands without starting daemon
+ # Handle profile subcommand — passthrough to profile-use Go binary
if args.command == 'profile':
- from browser_use.skill_cli.commands.profile import handle_profile_command
+ from browser_use.skill_cli.profile_use import run_profile_use
- return handle_profile_command(args)
+ # Everything after 'profile' is passed through to the Go binary
+ try:
+ profile_idx = sys.argv.index('profile')
+ except ValueError:
+ profile_idx = len(sys.argv)
+ profile_argv = sys.argv[profile_idx + 1:]
+ return run_profile_use(profile_argv)
# Handle setup command
if args.command == 'setup':
@@ -1015,7 +1006,7 @@ def main() -> int:
return 1
# One-time legacy migration
- _migrate_legacy_socket()
+ _migrate_legacy_files()
# Ensure daemon is running
# Only restart on config mismatch if the user explicitly passed config flags
diff --git a/browser_use/skill_cli/profile_use.py b/browser_use/skill_cli/profile_use.py
new file mode 100644
index 000000000..4eb669b1b
--- /dev/null
+++ b/browser_use/skill_cli/profile_use.py
@@ -0,0 +1,100 @@
+"""Profile-use Go binary management.
+
+Downloads, locates, and invokes the profile-use Go binary as a managed
+subcommand of `browser-use profile`. The binary is always managed at
+~/.browser-use/bin/profile-use — standalone installs on $PATH are independent.
+"""
+
+import os
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+
+def get_profile_use_binary() -> Path | None:
+ """Return path to managed profile-use binary, or None if not installed."""
+ from browser_use.skill_cli.utils import get_bin_dir
+
+ binary = get_bin_dir() / ('profile-use.exe' if sys.platform == 'win32' else 'profile-use')
+ if binary.is_file() and os.access(str(binary), os.X_OK):
+ return binary
+ return None
+
+
+def download_profile_use() -> Path:
+ """Download profile-use binary via the official install script.
+
+ Runs: curl -fsSL https://browser-use.com/profile/cli/install.sh | sh
+ with INSTALL_DIR set to ~/.browser-use/bin/
+
+ Raises RuntimeError if download fails.
+ """
+ from browser_use.skill_cli.utils import get_bin_dir
+
+ if not shutil.which('curl'):
+ raise RuntimeError(
+ 'curl is required to download profile-use.\n'
+ 'Install curl and try again, or install profile-use manually:\n'
+ ' curl -fsSL https://browser-use.com/profile/cli/install.sh | sh'
+ )
+
+ bin_dir = get_bin_dir()
+ env = {**os.environ, 'INSTALL_DIR': str(bin_dir)}
+
+ result = subprocess.run(
+ ['sh', '-c', 'curl -fsSL https://browser-use.com/profile/cli/install.sh | sh'],
+ env=env,
+ )
+
+ if result.returncode != 0:
+ raise RuntimeError('Failed to download profile-use. Try installing manually:\n curl -fsSL https://browser-use.com/profile/cli/install.sh | sh')
+
+ binary = get_profile_use_binary()
+ if binary is None:
+ raise RuntimeError('Download appeared to succeed but binary not found at expected location.')
+
+ return binary
+
+
+def ensure_profile_use() -> Path:
+ """Return path to profile-use binary, downloading if not present."""
+ binary = get_profile_use_binary()
+ if binary is not None:
+ return binary
+
+ print('profile-use not found, downloading...', file=sys.stderr)
+ return download_profile_use()
+
+
+def run_profile_use(args: list[str]) -> int:
+ """Execute profile-use with the given arguments.
+
+ Handles the 'update' subcommand specially by re-running the install script.
+ Passes BROWSER_USE_CONFIG_DIR so profile-use shares config with browser-use.
+ """
+ # Handle 'update' subcommand — re-download latest binary
+ if args and args[0] == 'update':
+ try:
+ download_profile_use()
+ print('profile-use updated successfully')
+ return 0
+ except RuntimeError as e:
+ print(f'Error: {e}', file=sys.stderr)
+ return 1
+
+ try:
+ binary = ensure_profile_use()
+ except RuntimeError as e:
+ print(f'Error: {e}', file=sys.stderr)
+ return 1
+
+ from browser_use.skill_cli.utils import get_home_dir
+
+ env = {**os.environ, 'BROWSER_USE_CONFIG_DIR': str(get_home_dir())}
+ # Forward BROWSER_USE_API_KEY if set
+ api_key = os.environ.get('BROWSER_USE_API_KEY')
+ if api_key:
+ env['BROWSER_USE_API_KEY'] = api_key
+
+ return subprocess.call([str(binary)] + args, env=env)
diff --git a/browser_use/skill_cli/tunnel.py b/browser_use/skill_cli/tunnel.py
index 53fd55f55..b42d15539 100644
--- a/browser_use/skill_cli/tunnel.py
+++ b/browser_use/skill_cli/tunnel.py
@@ -26,8 +26,11 @@ logger = logging.getLogger(__name__)
# Pattern to extract tunnel URL from cloudflared output
_URL_PATTERN = re.compile(r'(https://\S+\.trycloudflare\.com)')
-# Directory for tunnel PID files
-_TUNNELS_DIR = Path.home() / '.browser-use' / 'tunnels'
+def _tunnels_dir() -> Path:
+ """Get tunnel metadata directory (lazy to respect BROWSER_USE_HOME)."""
+ from browser_use.skill_cli.utils import get_tunnel_dir
+
+ return get_tunnel_dir()
class TunnelManager:
@@ -111,12 +114,12 @@ def get_tunnel_manager() -> TunnelManager:
def _get_tunnel_file(port: int) -> Path:
"""Get the path to a tunnel's info file."""
- return _TUNNELS_DIR / f'{port}.json'
+ return _tunnels_dir() / f'{port}.json'
def _save_tunnel_info(port: int, pid: int, url: str) -> None:
"""Save tunnel info to disk."""
- _TUNNELS_DIR.mkdir(parents=True, exist_ok=True)
+ _tunnels_dir().mkdir(parents=True, exist_ok=True)
_get_tunnel_file(port).write_text(json.dumps({'port': port, 'pid': pid, 'url': url}))
@@ -200,8 +203,8 @@ async def start_tunnel(port: int) -> dict[str, Any]:
return {'error': str(e)}
# Create log file for cloudflared stderr (avoids SIGPIPE when parent exits)
- _TUNNELS_DIR.mkdir(parents=True, exist_ok=True)
- log_file_path = _TUNNELS_DIR / f'{port}.log'
+ _tunnels_dir().mkdir(parents=True, exist_ok=True)
+ log_file_path = _tunnels_dir() / f'{port}.log'
log_file = open(log_file_path, 'w') # noqa: ASYNC230
# Spawn cloudflared as a daemon
@@ -268,8 +271,8 @@ def list_tunnels() -> dict[str, Any]:
Dict with 'tunnels' list and 'count'
"""
tunnels = []
- if _TUNNELS_DIR.exists():
- for tunnel_file in _TUNNELS_DIR.glob('*.json'):
+ if _tunnels_dir().exists():
+ for tunnel_file in _tunnels_dir().glob('*.json'):
try:
port = int(tunnel_file.stem)
info = _load_tunnel_info(port)
@@ -298,7 +301,7 @@ async def stop_tunnel(port: int) -> dict[str, Any]:
_kill_process(pid)
_delete_tunnel_info(port)
# Clean up log file
- log_file = _TUNNELS_DIR / f'{port}.log'
+ log_file = _tunnels_dir() / f'{port}.log'
log_file.unlink(missing_ok=True)
logger.info(f'Tunnel stopped: localhost:{port}')
@@ -312,8 +315,8 @@ async def stop_all_tunnels() -> dict[str, Any]:
Dict with 'stopped' list of ports
"""
stopped = []
- if _TUNNELS_DIR.exists():
- for tunnel_file in _TUNNELS_DIR.glob('*.json'):
+ if _tunnels_dir().exists():
+ for tunnel_file in _tunnels_dir().glob('*.json'):
try:
port = int(tunnel_file.stem)
result = await stop_tunnel(port)
diff --git a/browser_use/skill_cli/utils.py b/browser_use/skill_cli/utils.py
index 4b4738b40..80c0a1da5 100644
--- a/browser_use/skill_cli/utils.py
+++ b/browser_use/skill_cli/utils.py
@@ -6,7 +6,6 @@ import platform
import re
import subprocess
import sys
-import tempfile
import urllib.request
import zlib
from pathlib import Path
@@ -21,31 +20,17 @@ def validate_session_name(session: str) -> None:
raise ValueError(f'Invalid session name {session!r}: only letters, digits, hyphens, and underscores allowed')
-def get_runtime_dir() -> Path:
- """Get runtime directory for daemon socket/PID files.
+def get_home_dir() -> Path:
+ """Get the browser-use home directory (~/.browser-use/).
- Priority: BROWSER_USE_RUNTIME_DIR > XDG_RUNTIME_DIR/browser-use > ~/.browser-use/run > tempdir/browser-use
+ All CLI-managed files live here: config, sockets, PIDs, binaries, tunnels.
+ Override with BROWSER_USE_HOME env var.
"""
- env_dir = os.environ.get('BROWSER_USE_RUNTIME_DIR')
- if env_dir:
- d = Path(env_dir)
- d.mkdir(parents=True, exist_ok=True)
- return d
-
- xdg = os.environ.get('XDG_RUNTIME_DIR')
- if xdg:
- d = Path(xdg) / 'browser-use'
- d.mkdir(parents=True, exist_ok=True)
- return d
-
- home_dir = Path.home() / '.browser-use' / 'run'
- try:
- home_dir.mkdir(parents=True, exist_ok=True)
- return home_dir
- except OSError:
- pass
-
- d = Path(tempfile.gettempdir()) / 'browser-use'
+ env = os.environ.get('BROWSER_USE_HOME')
+ if env:
+ d = Path(env).expanduser()
+ else:
+ d = Path.home() / '.browser-use'
d.mkdir(parents=True, exist_ok=True)
return d
@@ -59,12 +44,12 @@ def get_socket_path(session: str = 'default') -> str:
if sys.platform == 'win32':
port = 49152 + zlib.adler32(session.encode()) % 16383
return f'tcp://127.0.0.1:{port}'
- return str(get_runtime_dir() / f'browser-use-{session}.sock')
+ return str(get_home_dir() / f'{session}.sock')
def get_pid_path(session: str = 'default') -> Path:
"""Get PID file path for a session."""
- return get_runtime_dir() / f'browser-use-{session}.pid'
+ return get_home_dir() / f'{session}.pid'
def is_daemon_alive(session: str = 'default') -> bool:
@@ -109,13 +94,11 @@ def list_sessions() -> list[dict]:
Returns list of {'name': str, 'pid': int, 'socket': str} for alive sessions.
Cleans up stale PID/socket files for dead sessions.
"""
- runtime_dir = get_runtime_dir()
+ home_dir = get_home_dir()
sessions: list[dict] = []
- for pid_file in sorted(runtime_dir.glob('browser-use-*.pid')):
- # Extract session name from filename: browser-use-<session>.pid
- stem = pid_file.stem # browser-use-<session>
- session_name = stem[len('browser-use-') :]
+ for pid_file in sorted(home_dir.glob('*.pid')):
+ session_name = pid_file.stem
if not session_name:
continue
@@ -150,7 +133,7 @@ def list_sessions() -> list[dict]:
def get_log_path() -> Path:
"""Get log file path for the daemon."""
- return Path(tempfile.gettempdir()) / 'browser-use-cli.log'
+ return get_home_dir() / 'cli.log'
def find_chrome_executable() -> str | None:
@@ -353,15 +336,41 @@ def list_chrome_profiles() -> list[dict[str, str]]:
return []
-def get_config_dir() -> Path:
- """Get browser-use config directory."""
+def get_config_path() -> Path:
+ """Get browser-use config file path."""
+ return get_home_dir() / 'config.json'
+
+
+def get_bin_dir() -> Path:
+ """Get directory for CLI-managed binaries."""
+ d = get_home_dir() / 'bin'
+ d.mkdir(parents=True, exist_ok=True)
+ return d
+
+
+def get_tunnel_dir() -> Path:
+ """Get directory for tunnel metadata and logs."""
+ return get_home_dir() / 'tunnels'
+
+
+def migrate_legacy_paths() -> None:
+ """One-time migration of config from old XDG location to ~/.browser-use/.
+
+ Copies (not moves) config.json if old location exists and new location does not.
+ """
+ new_config = get_home_dir() / 'config.json'
+ if new_config.exists():
+ return
+
+ # Check old XDG location
if sys.platform == 'win32':
- base = Path(os.environ.get('APPDATA', Path.home()))
+ old_base = Path(os.environ.get('APPDATA', Path.home()))
else:
- base = Path(os.environ.get('XDG_CONFIG_HOME', Path.home() / '.config'))
- return base / 'browser-use'
+ old_base = Path(os.environ.get('XDG_CONFIG_HOME', Path.home() / '.config'))
+ old_config = old_base / 'browser-use' / 'config.json'
+ if old_config.exists():
+ import shutil
-def get_config_path() -> Path:
- """Get browser-use config file path."""
- return get_config_dir() / 'config.json'
+ shutil.copy2(str(old_config), str(new_config))
+ print(f'Migrated config from {old_config} to {new_config}', file=sys.stderr)
diff --git a/skills/browser-use/SKILL.md b/skills/browser-use/SKILL.md
index d62139923..c15fea537 100644
--- a/skills/browser-use/SKILL.md
+++ b/skills/browser-use/SKILL.md
@@ -185,7 +185,7 @@ browser-use cloud v3 --help # Show API v3 endpoin
`cloud connect` provisions a cloud browser, connects via CDP, and prints a live URL. `browser-use close` disconnects AND stops the cloud browser (no orphaned billing). Mutually exclusive with `--cdp-url` and `--profile`.
-API key: env var `BROWSER_USE_API_KEY` or `browser-use cloud login`. Stored in `~/.config/browser-use/config.json`.
+API key: env var `BROWSER_USE_API_KEY` or `browser-use cloud login`. Stored in `~/.browser-use/config.json`.
### Tunnels
```bash
diff --git a/tests/ci/test_cli_cloud.py b/tests/ci/test_cli_cloud.py
index 9e8cc30ee..ceec2ce72 100644
--- a/tests/ci/test_cli_cloud.py
+++ b/tests/ci/test_cli_cloud.py
@@ -50,14 +50,14 @@ def test_cloud_login_saves_key(tmp_path: Path):
'login',
'sk-test-key-123',
env_override={
- 'XDG_CONFIG_HOME': str(tmp_path),
+ 'BROWSER_USE_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'
+ real_config = tmp_path / 'config.json'
assert real_config.exists()
data = json.loads(real_config.read_text())
assert data['api_key'] == 'sk-test-key-123'
@@ -65,14 +65,12 @@ def test_cloud_login_saves_key(tmp_path: Path):
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 = tmp_path / '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)},
+ env_override={'BROWSER_USE_HOME': str(tmp_path)},
)
assert result.returncode == 0
assert 'removed' in result.stdout.lower()
@@ -84,7 +82,7 @@ def test_cloud_logout_removes_key(tmp_path: Path):
def test_cloud_logout_no_key(tmp_path: Path):
result = run_cli(
'logout',
- env_override={'XDG_CONFIG_HOME': str(tmp_path)},
+ env_override={'BROWSER_USE_HOME': str(tmp_path)},
)
assert result.returncode == 0
assert 'no api key' in result.stdout.lower()
@@ -183,7 +181,7 @@ def test_cloud_rest_no_api_key_errors(tmp_path: Path):
'GET',
'/browsers',
env_override={
- 'XDG_CONFIG_HOME': str(tmp_path),
+ 'BROWSER_USE_HOME': str(tmp_path),
},
)
# _get_api_key calls sys.exit(1)
diff --git a/tests/ci/test_cli_sessions.py b/tests/ci/test_cli_sessions.py
index c3cc3e0a4..859660f27 100644
--- a/tests/ci/test_cli_sessions.py
+++ b/tests/ci/test_cli_sessions.py
@@ -9,14 +9,14 @@ import re
import pytest
from browser_use.skill_cli.main import (
+ _get_home_dir,
_get_pid_path,
- _get_runtime_dir,
_get_socket_path,
build_parser,
)
from browser_use.skill_cli.utils import (
+ get_home_dir,
get_pid_path,
- get_runtime_dir,
get_socket_path,
validate_session_name,
)
@@ -92,19 +92,19 @@ def test_session_name_regex_in_main():
def test_socket_path_includes_session():
path = _get_socket_path('work')
- assert 'browser-use-work.sock' in path or 'tcp://' in path
+ assert 'work.sock' in path or 'tcp://' in path
def test_pid_path_includes_session():
path = _get_pid_path('work')
- assert path.name == 'browser-use-work.pid'
+ assert path.name == 'work.pid'
def test_default_session_paths():
sock = _get_socket_path('default')
pid = _get_pid_path('default')
- assert 'browser-use-default' in sock or 'tcp://' in sock
- assert pid.name == 'browser-use-default.pid'
+ assert 'default' in sock or 'tcp://' in sock
+ assert pid.name == 'default.pid'
# ---------------------------------------------------------------------------
@@ -124,16 +124,16 @@ def test_main_utils_pid_path_agreement():
assert _get_pid_path(session) == get_pid_path(session), f'PID mismatch for {session!r}'
-def test_main_utils_runtime_dir_agreement():
- """main._get_runtime_dir must produce identical results to utils.get_runtime_dir."""
- assert _get_runtime_dir() == get_runtime_dir()
+def test_main_utils_home_dir_agreement():
+ """main._get_home_dir must produce identical results to utils.get_home_dir."""
+ assert _get_home_dir() == get_home_dir()
def test_path_agreement_with_env_override(tmp_path, monkeypatch):
- """Path agreement under BROWSER_USE_RUNTIME_DIR override."""
- override = str(tmp_path / 'custom-runtime')
- monkeypatch.setenv('BROWSER_USE_RUNTIME_DIR', override)
+ """Path agreement under BROWSER_USE_HOME override."""
+ override = str(tmp_path / 'custom-home')
+ monkeypatch.setenv('BROWSER_USE_HOME', override)
- assert _get_runtime_dir() == get_runtime_dir()
+ assert _get_home_dir() == get_home_dir()
assert _get_socket_path('test') == get_socket_path('test')
assert _get_pid_path('test') == get_pid_path('test')
diff --git a/tests/ci/test_doctor_command.py b/tests/ci/test_doctor_command.py
index 8c02d800c..69160f023 100644
--- a/tests/ci/test_doctor_command.py
+++ b/tests/ci/test_doctor_command.py
@@ -14,7 +14,7 @@ async def test_doctor_handle_returns_valid_structure():
assert 'summary' in result
# Verify all expected checks are present
- expected_checks = ['package', 'browser', 'network']
+ expected_checks = ['package', 'browser', 'network', 'cloudflared', 'profile_use']
for check in expected_checks:
assert check in result['checks']
assert 'status' in result['checks'][check]
@@ -46,6 +46,22 @@ async def test_check_network_returns_valid_structure():
assert 'message' in result
+def test_check_cloudflared_returns_valid_structure():
+ """Test _check_cloudflared returns a valid result."""
+ result = doctor._check_cloudflared()
+ assert 'status' in result
+ assert result['status'] in ('ok', 'missing')
+ assert 'message' in result
+
+
+def test_check_profile_use_returns_valid_structure():
+ """Test _check_profile_use returns a valid result."""
+ result = doctor._check_profile_use()
+ assert 'status' in result
+ assert result['status'] in ('ok', 'missing')
+ assert 'message' in result
+
+
def test_summarize_checks_all_ok():
"""Test _summarize_checks when all checks pass."""
checks = {