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
add --connect flag for Chrome auto-discovery and fix daemon shutdown for external browsers
ShawnPanabff291855870
diff --git a/browser_use/skill_cli/README.md b/browser_use/skill_cli/README.mdindex 36844f9b1..ed3d8af5f 100644--- a/browser_use/skill_cli/README.md+++ b/browser_use/skill_cli/README.md@@ -99,6 +99,9 @@ browser-use --profile open https://gmail.com# Use a specific Chrome profilebrowser-use --profile "Profile 1" open https://gmail.com+# Auto-discover and connect to running Chrome+browser-use --connect open https://example.com+# Connect to an existing browser via CDP URLbrowser-use --cdp-url http://localhost:9222 open https://example.com@@ -300,6 +303,7 @@ BROWSER_USE_SESSION=work browser-use state|--------|-------------|| `--headed` | Show browser window || `--profile [NAME]` | Use real Chrome (bare `--profile` uses "Default") |+| `--connect` | Auto-discover and connect to running Chrome via CDP || `--cdp-url <url>` | Connect to existing browser via CDP URL (`http://` or `ws://`) || `--session NAME` | Target a named session (default: "default", env: `BROWSER_USE_SESSION`) || `--json` | Output as JSON |diff --git a/browser_use/skill_cli/daemon.py b/browser_use/skill_cli/daemon.pyindex ebb044420..ee9029aa6 100644--- a/browser_use/skill_cli/daemon.py+++ b/browser_use/skill_cli/daemon.py@@ -290,7 +290,12 @@ class Daemon:if self._session:try:- await self._session.browser_session.kill()+ # Only kill the browser if the daemon launched it.+ # For external connections (--connect, --cdp-url, cloud), just disconnect.+ if self.cdp_url or self.use_cloud:+ await self._session.browser_session.stop()+ else:+ await self._session.browser_session.kill()except Exception as e:logger.warning(f'Error closing session: {e}')self._session = Nonediff --git a/browser_use/skill_cli/main.py b/browser_use/skill_cli/main.pyindex ed371dba1..32fef987c 100755--- a/browser_use/skill_cli/main.py+++ b/browser_use/skill_cli/main.py@@ -385,6 +385,11 @@ Setup:default=None,help='Connect to existing browser via CDP URL (http:// or ws://)',)+ parser.add_argument(+ '--connect',+ action='store_true',+ help='Auto-discover and connect to running Chrome via CDP',+ )parser.add_argument('--session', default=None, help='Session name (default: "default")')parser.add_argument('--json', action='store_true', help='Output as JSON')parser.add_argument('--mcp', action='store_true', help='Run as MCP server (JSON-RPC via stdin/stdout)')@@ -643,6 +648,9 @@ def _handle_cloud_connect(cloud_args: list[str], args: argparse.Namespace, sessiconnect_args, _ = connect_parser.parse_known_args(cloud_args)# Mutual exclusivity checks+ if getattr(args, 'connect', False):+ print('Error: --connect and cloud connect are mutually exclusive', file=sys.stderr)+ return 1if args.cdp_url:print('Error: --cdp-url and cloud connect are mutually exclusive', file=sys.stderr)return 1@@ -985,22 +993,38 @@ def main() -> int:print('No active browser session')return 0- # Mutual exclusivity: --cdp-url and --profile+ # Mutual exclusivity: --connect, --cdp-url, and --profile+ if args.connect and args.cdp_url:+ print('Error: --connect and --cdp-url are mutually exclusive', file=sys.stderr)+ return 1+ if args.connect and args.profile:+ print('Error: --connect and --profile are mutually exclusive', file=sys.stderr)+ return 1if args.cdp_url and args.profile:print('Error: --cdp-url and --profile are mutually exclusive', file=sys.stderr)return 1+ # Resolve --connect to a CDP URL+ if args.connect:+ from browser_use.skill_cli.utils import discover_chrome_cdp_url++ try:+ args.cdp_url = discover_chrome_cdp_url()+ except RuntimeError as e:+ print(f'Error: {e}', file=sys.stderr)+ return 1+# One-time legacy migration_migrate_legacy_socket()# Ensure daemon is running# Only restart on config mismatch if the user explicitly passed config flags- explicit_config = any(flag in sys.argv for flag in ('--headed', '--profile', '--cdp-url'))+ explicit_config = any(flag in sys.argv for flag in ('--headed', '--profile', '--cdp-url', '--connect'))ensure_daemon(args.headed, args.profile, args.cdp_url, session=session, explicit_config=explicit_config)# Build params from argsparams = {}- skip_keys = {'command', 'headed', 'json', 'cdp_url', 'session'}+ skip_keys = {'command', 'headed', 'json', 'cdp_url', 'session', 'connect'}for key, value in vars(args).items():if key not in skip_keys and value is not None:diff --git a/browser_use/skill_cli/utils.py b/browser_use/skill_cli/utils.pyindex 5e7c87eb5..4b4738b40 100644--- a/browser_use/skill_cli/utils.py+++ b/browser_use/skill_cli/utils.py@@ -1,11 +1,13 @@"""Platform utilities for CLI and daemon."""+import json as _jsonimport osimport platformimport reimport subprocessimport sysimport tempfile+import urllib.requestimport zlibfrom pathlib import Path@@ -212,6 +214,110 @@ def get_chrome_profile_path(profile: str | None) -> str | None:return None+def get_chrome_user_data_dirs() -> list[Path]:+ """Return candidate Chrome/Chromium user-data directories for the current OS.++ Covers Google Chrome, Chrome Canary, Chromium, and Brave on macOS/Linux/Windows.+ """+ system = platform.system()+ home = Path.home()+ candidates: list[Path] = []++ if system == 'Darwin':+ base = home / 'Library' / 'Application Support'+ for name in ('Google/Chrome', 'Google/Chrome Canary', 'Chromium', 'BraveSoftware/Brave-Browser'):+ candidates.append(base / name)+ elif system == 'Linux':+ base = home / '.config'+ for name in ('google-chrome', 'google-chrome-unstable', 'chromium', 'BraveSoftware/Brave-Browser'):+ candidates.append(base / name)+ elif system == 'Windows':+ local_app_data = os.environ.get('LOCALAPPDATA', str(home / 'AppData' / 'Local'))+ base = Path(local_app_data)+ for name in (+ 'Google\\Chrome\\User Data',+ 'Google\\Chrome SxS\\User Data',+ 'Chromium\\User Data',+ 'BraveSoftware\\Brave-Browser\\User Data',+ ):+ candidates.append(base / name)++ return [d for d in candidates if d.is_dir()]+++def discover_chrome_cdp_url() -> str:+ """Auto-discover a running Chrome instance's CDP WebSocket URL.++ Strategy:+ 1. Read ``DevToolsActivePort`` from known Chrome data dirs.+ 2. Probe ``/json/version`` via HTTP to get ``webSocketDebuggerUrl``.+ 3. If HTTP fails, construct ``ws://`` URL directly from the port file.+ 4. Fallback: probe well-known ports 9222, 9229.++ Raises ``RuntimeError`` if no running Chrome with remote debugging is found.+ """++ def _probe_http(port: int) -> str | None:+ """Try GET http://127.0.0.1:{port}/json/version and return webSocketDebuggerUrl."""+ try:+ req = urllib.request.Request(f'http://127.0.0.1:{port}/json/version')+ with urllib.request.urlopen(req, timeout=2) as resp:+ data = _json.loads(resp.read())+ url = data.get('webSocketDebuggerUrl')+ if url and isinstance(url, str):+ return url+ except Exception:+ pass+ return None++ def _port_is_open(port: int) -> bool:+ """Check if something is listening on 127.0.0.1:{port}."""+ import socket++ try:+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ s.settimeout(1)+ s.connect(('127.0.0.1', port))+ s.close()+ return True+ except OSError:+ return False++ # --- Phase 1: DevToolsActivePort files ---+ for data_dir in get_chrome_user_data_dirs():+ port_file = data_dir / 'DevToolsActivePort'+ if not port_file.is_file():+ continue+ try:+ lines = port_file.read_text().strip().splitlines()+ if not lines:+ continue+ port = int(lines[0].strip())+ ws_path = lines[1].strip() if len(lines) > 1 else '/devtools/browser'+ except (ValueError, OSError):+ continue++ # Try HTTP probe first (gives us the full canonical URL)+ ws_url = _probe_http(port)+ if ws_url:+ return ws_url++ # HTTP may not respond (Chrome M144+), but if the port is open, trust the file+ if _port_is_open(port):+ return f'ws://127.0.0.1:{port}{ws_path}'++ # --- Phase 2: well-known fallback ports ---+ for port in (9222, 9229):+ ws_url = _probe_http(port)+ if ws_url:+ return ws_url++ raise RuntimeError(+ 'Could not discover a running Chrome instance with remote debugging enabled.\n'+ 'Enable remote debugging in Chrome (chrome://inspect, or launch with --remote-debugging-port=9222) and try again.'+ )++def list_chrome_profiles() -> list[dict[str, str]]:"""List available Chrome profiles with their names.diff --git a/skills/browser-use/SKILL.md b/skills/browser-use/SKILL.mdindex 4da64c5ff..d62139923 100644--- a/skills/browser-use/SKILL.md+++ b/skills/browser-use/SKILL.md@@ -33,13 +33,15 @@ browser-use open <url> # Default: headless Chromiumbrowser-use --headed open <url> # Visible Chromium windowbrowser-use --profile open <url> # Real Chrome with Default profilebrowser-use --profile "Profile 1" open <url> # Real Chrome with named profile+browser-use --connect open <url> # Auto-discover running Chrome via CDPbrowser-use --cdp-url http://localhost:9222 open <url> # Connect to existing browser via CDPbrowser-use --cdp-url ws://localhost:9222/devtools/browser/... state # WebSocket CDP URL```- **Default (no --profile)**: Fast, isolated Chromium, headless by default- **With --profile**: Uses your real Chrome binary with the specified profile (cookies, logins, extensions). Bare `--profile` uses "Default".-- **With --cdp-url**: Connects to an already-running browser via CDP URL (http:// or ws://). Useful for Docker containers, remote debugging sessions, or cloud-provisioned browsers. `--cdp-url` and `--profile` are mutually exclusive.+- **With --connect**: Auto-discovers a running Chrome instance with remote debugging enabled by reading `DevToolsActivePort` or probing well-known ports. No manual URL needed.+- **With --cdp-url**: Connects to an already-running browser via CDP URL (http:// or ws://). Useful for Docker containers, remote debugging sessions, or cloud-provisioned browsers. `--connect`, `--cdp-url`, and `--profile` are mutually exclusive.## Essential Commands@@ -252,15 +254,25 @@ Use when the user has Chrome already running and wants to control it via browser**Requirement:** Chrome must have remote debugging enabled (`chrome://inspect/#remote-debugging` on Chrome >= 144, or launch with `--remote-debugging-port=<port>`).-**Connection flow:**+**Recommended: auto-discovery with `--connect`:**+```bash+browser-use close # Close any existing session+browser-use --connect open https://example.com # Auto-discovers Chrome's CDP endpoint+browser-use --connect state # Works with all commands+```++`--connect` reads `DevToolsActivePort` from known Chrome data directories and probes well-known ports (9222, 9229) as a fallback — no manual URL construction needed.++**Manual fallback with `--cdp-url`:**-1. Read Chrome's `DevToolsActivePort` file to get the port and WebSocket path (the HTTP `/json/version` endpoint often does not respond):+If auto-discovery doesn't work (e.g. non-standard Chrome location or remote host), read Chrome's `DevToolsActivePort` file manually:- macOS: `~/Library/Application Support/Google/Chrome/DevToolsActivePort`- Linux: `~/.config/google-chrome/DevToolsActivePort`- The file contains two lines: the port and the WebSocket path. Combine into `ws://127.0.0.1:<port><path>`.-2. Close any existing browser-use session (`browser-use close`), then connect with `--cdp-url ws://...`.-3. List tabs with: `browser-use --cdp-url <ws_url> python "import json; tabs = browser._run(browser._session.get_tabs()); print(json.dumps(tabs, indent=2, default=str))"`-4. Switch tabs with `browser-use --cdp-url <ws_url> switch <tab_index>`.++```bash+browser-use --cdp-url ws://127.0.0.1:<port><path> open https://example.com+```**Important:** Always use the `ws://` WebSocket URL (not `http://`) with `--cdp-url` when connecting to an existing Chrome instance.@@ -290,6 +302,7 @@ browser-use screenshot|--------|-------------|| `--headed` | Show browser window || `--profile [NAME]` | Use real Chrome (bare `--profile` uses "Default") |+| `--connect` | Auto-discover and connect to running Chrome via CDP || `--cdp-url <url>` | Connect to existing browser via CDP URL (`http://` or `ws://`) || `--json` | Output as JSON || `--mcp` | Run as MCP server via stdin/stdout |diff --git a/skills/remote-browser/SKILL.md b/skills/remote-browser/SKILL.mdindex 4ba841977..dcbdaa2c1 100644--- a/skills/remote-browser/SKILL.md+++ b/skills/remote-browser/SKILL.md@@ -23,12 +23,14 @@ For more information, see https://github.com/browser-use/browser-use/blob/main/b```bashbrowser-use open <url> # Default: headless Chromiumbrowser-use cloud connect # Provision cloud browser and connect+browser-use --connect open <url> # Auto-discover running Chrome via CDPbrowser-use --cdp-url http://localhost:9222 open <url> # Connect to existing browser via CDPbrowser-use --cdp-url ws://localhost:9222/devtools/browser/... state # WebSocket CDP URL```- **Default**: Launches headless Chromium- **With cloud connect**: Provisions a cloud browser via Browser-Use Cloud API, connects via CDP, and prints a live URL. `browser-use close` disconnects AND stops the cloud browser. Requires API key (`BROWSER_USE_API_KEY` env var or `browser-use cloud login`).+- **With --connect**: Auto-discovers a running Chrome instance with remote debugging enabled. No manual URL needed.- **With --cdp-url**: Connects to an already-running browser via CDP URL (http:// or ws://). Useful for Docker containers, remote debugging sessions, or cloud-provisioned browsers. `browser-use close` disconnects without killing the external browser.## Core Workflow@@ -214,6 +216,7 @@ browser-use screenshot|--------|-------------|| `--headed` | Show browser window || `--profile [NAME]` | Use real Chrome (bare `--profile` uses "Default") |+| `--connect` | Auto-discover and connect to running Chrome via CDP || `--cdp-url <url>` | Connect to existing browser via CDP URL (`http://` or `ws://`) || `--json` | Output as JSON |diff --git a/tests/ci/test_cli_connect.py b/tests/ci/test_cli_connect.pynew file mode 100644index 000000000..412e92839--- /dev/null+++ b/tests/ci/test_cli_connect.py@@ -0,0 +1,190 @@+"""Tests for browser-use --connect flag (Chrome CDP auto-discovery)."""++import http.server+import json+import socket+import subprocess+import sys+import threading+from pathlib import Path++import pytest+++def run_cli(*args: str) -> subprocess.CompletedProcess:+ """Run the CLI as a subprocess, returning the result."""+ import os++ env = os.environ.copy()+ env.pop('BROWSER_USE_API_KEY', None)++ return subprocess.run(+ [sys.executable, '-m', 'browser_use.skill_cli.main', *args],+ capture_output=True,+ text=True,+ env=env,+ timeout=15,+ )+++# ---------------------------------------------------------------------------+# Fixtures+# ---------------------------------------------------------------------------+++def chrome_data_dir(tmp_path: Path, monkeypatch):+ """Create a fake Chrome data directory and patch get_chrome_user_data_dirs."""+ data_dir = tmp_path / 'FakeChrome'+ data_dir.mkdir()++ import browser_use.skill_cli.utils as utils_mod++ monkeypatch.setattr(utils_mod, 'get_chrome_user_data_dirs', lambda: [data_dir])+ return data_dir+++def _find_free_port() -> int:+ """Find a free TCP port on localhost."""+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:+ s.bind(('127.0.0.1', 0))+ return s.getsockname()[1]+++def _start_json_version_server(port: int, ws_url: str):+ """Start a minimal HTTP server that responds to /json/version with a webSocketDebuggerUrl."""++ class Handler(http.server.BaseHTTPRequestHandler):+ def do_GET(self):+ if self.path == '/json/version':+ body = json.dumps({'webSocketDebuggerUrl': ws_url}).encode()+ self.send_response(200)+ self.send_header('Content-Type', 'application/json')+ self.send_header('Content-Length', str(len(body)))+ self.end_headers()+ self.wfile.write(body)+ else:+ self.send_error(404)++ def log_message(self, format, *_args):+ pass # silence logs++ server = http.server.HTTPServer(('127.0.0.1', port), Handler)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ return server+++def _start_tcp_listener(port: int) -> socket.socket:+ """Start a bare TCP listener (accepts connections but serves no HTTP)."""+ srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ srv.bind(('127.0.0.1', port))+ srv.listen(16) # larger backlog so HTTP probe doesn't exhaust it+ return srv+++# ---------------------------------------------------------------------------+# Unit tests for discover_chrome_cdp_url+# ---------------------------------------------------------------------------+++def test_discover_from_devtools_active_port(chrome_data_dir: Path):+ """DevToolsActivePort exists + /json/version responds → return webSocketDebuggerUrl."""+ from browser_use.skill_cli.utils import discover_chrome_cdp_url++ port = _find_free_port()+ expected_ws = f'ws://127.0.0.1:{port}/devtools/browser/abc123'++ # Write DevToolsActivePort+ (chrome_data_dir / 'DevToolsActivePort').write_text(f'{port}\n/devtools/browser/abc123\n')++ # Start HTTP server that serves /json/version+ server = _start_json_version_server(port, expected_ws)+ try:+ result = discover_chrome_cdp_url()+ assert result == expected_ws+ finally:+ server.shutdown()+++def test_discover_direct_ws_when_http_fails(chrome_data_dir: Path):+ """DevToolsActivePort exists, port is open, but no HTTP → fall back to ws:// from file."""+ from browser_use.skill_cli.utils import discover_chrome_cdp_url++ port = _find_free_port()++ (chrome_data_dir / 'DevToolsActivePort').write_text(f'{port}\n/devtools/browser/xyz789\n')++ # Start a bare TCP listener (no HTTP)+ srv = _start_tcp_listener(port)+ try:+ result = discover_chrome_cdp_url()+ assert result == f'ws://127.0.0.1:{port}/devtools/browser/xyz789'+ finally:+ srv.close()+++def test_discover_stale_port_falls_through(chrome_data_dir: Path):+ """DevToolsActivePort with a dead port, no fallback listeners → RuntimeError."""+ from browser_use.skill_cli.utils import discover_chrome_cdp_url++ # Use a port that nothing is listening on+ port = _find_free_port()+ (chrome_data_dir / 'DevToolsActivePort').write_text(f'{port}\n/devtools/browser/stale\n')++ with pytest.raises(RuntimeError, match='remote debugging'):+ discover_chrome_cdp_url()+++def test_discover_no_chrome_errors(chrome_data_dir: Path):+ """No DevToolsActivePort at all, no fallback listeners → RuntimeError."""+ from browser_use.skill_cli.utils import discover_chrome_cdp_url++ # chrome_data_dir exists but has no DevToolsActivePort file+ with pytest.raises(RuntimeError, match='remote debugging'):+ discover_chrome_cdp_url()+++def test_discover_fallback_well_known_port(chrome_data_dir: Path):+ """No DevToolsActivePort, but port 9222 serves /json/version → returns that URL."""+ from browser_use.skill_cli.utils import discover_chrome_cdp_url++ expected_ws = 'ws://127.0.0.1:9222/devtools/browser/fallback'++ # No DevToolsActivePort file — discovery should fall through to port 9222+ try:+ server = _start_json_version_server(9222, expected_ws)+ except OSError:+ pytest.skip('Port 9222 already in use')++ try:+ result = discover_chrome_cdp_url()+ assert result == expected_ws+ finally:+ server.shutdown()+++# ---------------------------------------------------------------------------+# CLI integration tests (subprocess)+# ---------------------------------------------------------------------------+++def test_connect_mutual_exclusivity_with_cdp_url():+ """--connect + --cdp-url should error."""+ result = run_cli('--connect', '--cdp-url', 'ws://localhost:9222', 'open', 'https://example.com')+ assert result.returncode == 1+ assert 'mutually exclusive' in result.stderr.lower()+++def test_connect_mutual_exclusivity_with_profile():+ """--connect + --profile should error."""+ result = run_cli('--connect', '--profile', 'Default', 'open', 'https://example.com')+ assert result.returncode == 1+ assert 'mutually exclusive' in result.stderr.lower()+++def test_connect_shows_in_help():+ """--help output should contain --connect."""+ result = run_cli('--help')+ assert '--connect' in result.stdout