Skip to content

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

feat: multi-agent tab isolation for --connect mode

ShawnPana31694df28374
diff --git a/browser_use/skill_cli/commands/browser.py b/browser_use/skill_cli/commands/browser.py
index af3b82cb7..b1ca714bf 100644
--- a/browser_use/skill_cli/commands/browser.py
+++ b/browser_use/skill_cli/commands/browser.py
@@ -191,32 +191,38 @@ async def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> A
elif action == 'switch':
from browser_use.browser.events import SwitchTabEvent
- tab_index = params['tab']
- # Get target_id from tab index
- page_targets = bs.session_manager.get_all_page_targets() if bs.session_manager else []
- if tab_index < 0 or tab_index >= len(page_targets):
- return {'error': f'Invalid tab index {tab_index}. Available: 0-{len(page_targets) - 1}'}
- target_id = page_targets[tab_index].target_id
+ # Use pre-resolved target_id from tab ownership (scoped to caller's tabs)
+ if '_resolved_target_id' in params:
+ target_id = params['_resolved_target_id']
+ else:
+ tab_index = params['tab']
+ page_targets = bs.session_manager.get_all_page_targets() if bs.session_manager else []
+ if tab_index < 0 or tab_index >= len(page_targets):
+ return {'error': f'Invalid tab index {tab_index}. Available: 0-{len(page_targets) - 1}'}
+ target_id = page_targets[tab_index].target_id
await bs.event_bus.dispatch(SwitchTabEvent(target_id=target_id))
- return {'switched': tab_index}
+ return {'switched': params.get('tab', 0)}
elif action == 'close-tab':
from browser_use.browser.events import CloseTabEvent
- tab_index = params.get('tab')
- # Get target_id from tab index
- page_targets = bs.session_manager.get_all_page_targets() if bs.session_manager else []
- if tab_index is not None:
- if tab_index < 0 or tab_index >= len(page_targets):
- return {'error': f'Invalid tab index {tab_index}. Available: 0-{len(page_targets) - 1}'}
- target_id = page_targets[tab_index].target_id
+ # Use pre-resolved target_id from tab ownership (scoped to caller's tabs)
+ if '_resolved_target_id' in params:
+ target_id = params['_resolved_target_id']
else:
- # Close current/focused tab
- target_id = bs.session_manager.get_focused_target().target_id if bs.session_manager else None
- if not target_id:
- return {'error': 'No focused tab to close'}
+ tab_index = params.get('tab')
+ page_targets = bs.session_manager.get_all_page_targets() if bs.session_manager else []
+ if tab_index is not None:
+ if tab_index < 0 or tab_index >= len(page_targets):
+ return {'error': f'Invalid tab index {tab_index}. Available: 0-{len(page_targets) - 1}'}
+ target_id = page_targets[tab_index].target_id
+ else:
+ # Close current/focused tab
+ target_id = bs.session_manager.get_focused_target().target_id if bs.session_manager else None
+ if not target_id:
+ return {'error': 'No focused tab to close'}
await bs.event_bus.dispatch(CloseTabEvent(target_id=target_id))
- return {'closed': tab_index}
+ return {'closed': params.get('tab')}
elif action == 'keys':
from browser_use.browser.events import SendKeysEvent
diff --git a/browser_use/skill_cli/daemon.py b/browser_use/skill_cli/daemon.py
index 32a3b77aa..a486a3f54 100644
--- a/browser_use/skill_cli/daemon.py
+++ b/browser_use/skill_cli/daemon.py
@@ -18,6 +18,7 @@ from typing import TYPE_CHECKING
if TYPE_CHECKING:
from browser_use.skill_cli.sessions import SessionInfo
+ from browser_use.skill_cli.tab_ownership import TabOwnershipManager
# Configure logging before imports
logging.basicConfig(
@@ -59,39 +60,78 @@ class Daemon:
self._session: SessionInfo | None = None
self._shutdown_task: asyncio.Task | None = None
self._browser_watchdog_task: asyncio.Task | None = None
+ self._agent_cleanup_task: asyncio.Task | None = None
+ self._tab_ownership: TabOwnershipManager | None = None
+ self._session_lock = asyncio.Lock()
async def _get_or_create_session(self) -> SessionInfo:
"""Lazy-create the single session on first command."""
if self._session is not None:
return self._session
- from browser_use.skill_cli.sessions import SessionInfo, create_browser_session
-
- logger.info(
- f'Creating session (headed={self.headed}, profile={self.profile}, cdp_url={self.cdp_url}, use_cloud={self.use_cloud})'
- )
-
- bs = await create_browser_session(
- self.headed,
- self.profile,
- self.cdp_url,
- use_cloud=self.use_cloud,
- cloud_timeout=self.cloud_timeout,
- cloud_proxy_country_code=self.cloud_proxy_country_code,
- cloud_profile_id=self.cloud_profile_id,
- )
- await bs.start()
-
- self._session = SessionInfo(
- name=self.session,
- headed=self.headed,
- profile=self.profile,
- cdp_url=self.cdp_url,
- browser_session=bs,
- use_cloud=self.use_cloud,
- )
- self._browser_watchdog_task = asyncio.create_task(self._watch_browser())
- return self._session
+ async with self._session_lock:
+ # Double-check after acquiring lock
+ if self._session is not None:
+ return self._session
+
+ from browser_use.skill_cli.sessions import SessionInfo, create_browser_session
+
+ logger.info(
+ f'Creating session (headed={self.headed}, profile={self.profile}, cdp_url={self.cdp_url}, use_cloud={self.use_cloud})'
+ )
+
+ bs = await create_browser_session(
+ self.headed,
+ self.profile,
+ self.cdp_url,
+ use_cloud=self.use_cloud,
+ cloud_timeout=self.cloud_timeout,
+ cloud_proxy_country_code=self.cloud_proxy_country_code,
+ cloud_profile_id=self.cloud_profile_id,
+ )
+ await bs.start()
+
+ # Wait for Chrome to stabilize after CDP setup before accepting commands
+ try:
+ await bs.get_browser_state_summary()
+ except Exception:
+ pass
+
+ self._session = SessionInfo(
+ name=self.session,
+ headed=self.headed,
+ profile=self.profile,
+ cdp_url=self.cdp_url,
+ browser_session=bs,
+ use_cloud=self.use_cloud,
+ )
+ self._browser_watchdog_task = asyncio.create_task(self._watch_browser())
+
+ # Initialize tab ownership for multi-agent isolation
+ from browser_use.skill_cli.tab_ownership import TabOwnershipManager
+ from browser_use.skill_cli.utils import get_home_dir
+
+ self._tab_ownership = TabOwnershipManager(bs)
+ self._tab_ownership.set_agents_file(get_home_dir() / 'agents.json')
+
+ # Listen for tab lifecycle events to track ownership
+ from browser_use.browser.events import TabClosedEvent, TabCreatedEvent
+
+ def _on_tab_created(event: TabCreatedEvent) -> None:
+ assert self._tab_ownership is not None
+ self._tab_ownership.on_tab_created(event.target_id)
+
+ def _on_tab_closed(event: TabClosedEvent) -> None:
+ assert self._tab_ownership is not None
+ self._tab_ownership.on_tab_closed(event.target_id)
+
+ bs.event_bus.on(TabCreatedEvent, _on_tab_created)
+ bs.event_bus.on(TabClosedEvent, _on_tab_closed)
+
+ # Start periodic agent cleanup
+ self._agent_cleanup_task = asyncio.create_task(self._cleanup_stale_agents())
+
+ return self._session
async def _watch_browser(self) -> None:
"""Poll BrowserSession.is_cdp_connected every 2s. Shutdown when browser dies."""
@@ -102,6 +142,16 @@ class Daemon:
await self.shutdown()
return
+ async def _cleanup_stale_agents(self) -> None:
+ """Periodically clean up contexts for agents whose parent process is dead."""
+ while self.running:
+ await asyncio.sleep(30.0)
+ if self._tab_ownership:
+ try:
+ await self._tab_ownership.cleanup_stale_agents()
+ except Exception as e:
+ logger.debug(f'Agent cleanup error: {e}')
+
async def handle_connection(
self,
reader: asyncio.StreamReader,
@@ -182,16 +232,79 @@ class Daemon:
from browser_use.skill_cli.commands import browser, python_exec
+ # Commands that mutate browser state — these acquire a tab lock
+ MUTATING_COMMANDS = {
+ 'open', 'click', 'type', 'input', 'scroll', 'back',
+ 'keys', 'select', 'upload', 'eval', 'dblclick', 'rightclick', 'hover',
+ }
+
# Get or create the single session
session = await self._get_or_create_session()
+ bs = session.browser_session
+ agent_id = request.get('agent_id', '__shared__')
+
+ # --- Tab locking: scope commands to the caller's focused tab ---
+ if self._tab_ownership:
+ ctx = await self._tab_ownership.ensure_caller_has_tab(agent_id)
+
+ # Pre-resolve tab indices for switch/close-tab (global indices)
+ if action == 'switch' and 'tab' in params:
+ resolved = self._tab_ownership.resolve_tab_index(params['tab'])
+ if resolved is None:
+ all_targets = bs.session_manager.get_all_page_targets() if bs.session_manager else []
+ return {
+ 'id': req_id,
+ 'success': False,
+ 'error': f'Invalid tab index {params["tab"]}. {len(all_targets)} tab(s) available (indices 0-{len(all_targets) - 1}).',
+ }
+ # Check lock before switching
+ lock_err = self._tab_ownership.check_lock(agent_id, resolved)
+ if lock_err:
+ return {'id': req_id, 'success': False, 'error': lock_err}
+ params['_resolved_target_id'] = resolved
+ # Update caller's focus to the switched tab
+ ctx.focused_target_id = resolved
+ elif action == 'close-tab' and params.get('tab') is not None:
+ resolved = self._tab_ownership.resolve_tab_index(params['tab'])
+ if resolved is None:
+ all_targets = bs.session_manager.get_all_page_targets() if bs.session_manager else []
+ return {
+ 'id': req_id,
+ 'success': False,
+ 'error': f'Invalid tab index {params["tab"]}. {len(all_targets)} tab(s) available (indices 0-{len(all_targets) - 1}).',
+ }
+ params['_resolved_target_id'] = resolved
+
+ # For mutating commands, check lock on focused tab
+ if action in MUTATING_COMMANDS:
+ lock_err = self._tab_ownership.check_lock(agent_id, ctx.focused_target_id)
+ if lock_err:
+ return {'id': req_id, 'success': False, 'error': lock_err}
+ # Lock the tab for this caller
+ if ctx.focused_target_id:
+ self._tab_ownership.lock_tab(agent_id, ctx.focused_target_id)
+
+ # Swap focus and selector map to caller's tab
+ saved_focus = bs.agent_focus_target_id
+ saved_selector_map = bs._cached_selector_map
+ bs.agent_focus_target_id = ctx.focused_target_id
+ bs._cached_selector_map = ctx.cached_selector_map
# Dispatch to handler
- if action in browser.COMMANDS:
- result = await browser.handle(action, session, params)
- elif action == 'python':
- result = await python_exec.handle(session, params)
- else:
- return {'id': req_id, 'success': False, 'error': f'Unknown action: {action}'}
+ try:
+ if action in browser.COMMANDS:
+ result = await browser.handle(action, session, params)
+ elif action == 'python':
+ result = await python_exec.handle(session, params)
+ else:
+ return {'id': req_id, 'success': False, 'error': f'Unknown action: {action}'}
+ finally:
+ # Save caller's updated focus/selector map and restore previous
+ if self._tab_ownership:
+ ctx.focused_target_id = bs.agent_focus_target_id
+ ctx.cached_selector_map = bs._cached_selector_map
+ bs.agent_focus_target_id = saved_focus # type: ignore[possibly-undefined]
+ bs._cached_selector_map = saved_selector_map # type: ignore[possibly-undefined]
return {'id': req_id, 'success': True, 'data': result}
@@ -290,6 +403,9 @@ class Daemon:
if self._browser_watchdog_task:
self._browser_watchdog_task.cancel()
+ if self._agent_cleanup_task:
+ self._agent_cleanup_task.cancel()
+
if self._server:
self._server.close()
diff --git a/browser_use/skill_cli/main.py b/browser_use/skill_cli/main.py
index 74c1c7556..811c2d5bc 100755
--- a/browser_use/skill_cli/main.py
+++ b/browser_use/skill_cli/main.py
@@ -99,6 +99,29 @@ if _get_subcommand() == 'init':
init_main()
sys.exit(0)
+# Handle 'register' command — assigns an agent index for multi-agent --connect mode
+if _get_subcommand() == 'register':
+ _home = os.environ.get('BROWSER_USE_HOME')
+ _home_dir = Path(_home).expanduser() if _home else Path.home() / '.browser-use'
+ _home_dir.mkdir(parents=True, exist_ok=True)
+ agents_file = _home_dir / 'agents.json'
+ agents = {}
+ if agents_file.exists():
+ try:
+ agents = json.loads(agents_file.read_text())
+ except (json.JSONDecodeError, OSError):
+ pass
+ # Clean expired entries (>5min) and find next available index
+ now = time.time()
+ agents = {k: v for k, v in agents.items() if now - v.get('last_active', 0) < 300}
+ next_idx = 1
+ while str(next_idx) in agents:
+ next_idx += 1
+ agents[str(next_idx)] = {'last_active': now}
+ agents_file.write_text(json.dumps(agents))
+ print(next_idx)
+ sys.exit(0)
+
# Handle --template flag directly (without 'init' subcommand)
# Delegate to init_main() which handles full template logic (directories, manifests, etc.)
if '--template' in sys.argv:
@@ -312,12 +335,13 @@ def ensure_daemon(
sys.exit(1)
-def send_command(action: str, params: dict, *, session: str = 'default') -> dict:
+def send_command(action: str, params: dict, *, session: str = 'default', agent_id: str = '__shared__') -> dict:
"""Send command to daemon and get response."""
request = {
'id': f'r{int(time.time() * 1000000) % 1000000}',
'action': action,
'params': params,
+ 'agent_id': agent_id,
}
sock = _connect_to_daemon(session=session)
@@ -388,8 +412,10 @@ Setup:
)
parser.add_argument(
'--connect',
- action='store_true',
- help='Auto-discover and connect to running Chrome via CDP',
+ nargs=1,
+ metavar='AGENT_INDEX',
+ default=None,
+ help='Connect to running Chrome via CDP with agent index (run "browser-use register" first)',
)
parser.add_argument('--session', default=None, help='Session name (default: "default")')
parser.add_argument('--json', action='store_true', help='Output as JSON')
@@ -405,6 +431,9 @@ Setup:
# install
subparsers.add_parser('install', help='Install Chromium browser + system dependencies')
+ # register
+ subparsers.add_parser('register', help='Register an agent for multi-agent --connect mode')
+
# init
p = subparsers.add_parser('init', help='Generate browser-use template file')
p.add_argument('--template', '-t', help='Template name (interactive if not specified)')
@@ -1017,6 +1046,33 @@ def main() -> int:
print('No active browser session')
return 0
+ # Resolve --connect to agent_id + CDP URL
+ agent_id = '__shared__'
+ if args.connect:
+ agent_id = args.connect[0]
+ # Validate agent index against registry
+ agents_file = _get_home_dir() / 'agents.json'
+ agents = {}
+ if agents_file.exists():
+ try:
+ agents = json.loads(agents_file.read_text())
+ except (json.JSONDecodeError, OSError):
+ pass
+ now = time.time()
+ agent_entry = agents.get(agent_id)
+ if agent_entry is None:
+ print(f'Error: Agent {agent_id} not registered. Run \'browser-use register\' first.', file=sys.stderr)
+ return 1
+ if now - agent_entry.get('last_active', 0) > 300:
+ # Expired — remove it
+ agents.pop(agent_id, None)
+ agents_file.write_text(json.dumps(agents))
+ print(f'Error: Agent {agent_id} session expired. Run \'browser-use register\' to get a new agent ID.', file=sys.stderr)
+ return 1
+ # Update last_active
+ agent_entry['last_active'] = now
+ agents_file.write_text(json.dumps(agents))
+
# 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)
@@ -1063,7 +1119,7 @@ def main() -> int:
params['profile'] = args.profile
# Send command to daemon
- response = send_command(args.command, params, session=session)
+ response = send_command(args.command, params, session=session, agent_id=agent_id)
# Output response
if args.json:
diff --git a/browser_use/skill_cli/tab_ownership.py b/browser_use/skill_cli/tab_ownership.py
new file mode 100644
index 000000000..b8fff10e7
--- /dev/null
+++ b/browser_use/skill_cli/tab_ownership.py
@@ -0,0 +1,184 @@
+"""Tab locking for multi-agent browser sharing.
+
+All agents can see all tabs. A tab becomes locked to an agent when the agent
+mutates it (click, type, navigate, etc.). If another agent tries to mutate a
+locked tab, it gets an error. Read-only commands (state, screenshot) work on
+any tab regardless of locks.
+
+Agent identity comes from --connect <index>, assigned by 'browser-use register'.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import time
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ from browser_use.browser.session import BrowserSession
+
+logger = logging.getLogger('browser_use.skill_cli.tab_ownership')
+
+SHARED_CONTEXT = '__shared__'
+AGENT_EXPIRY_SECONDS = 300 # 5 minutes
+
+
+@dataclass
+class CallerContext:
+ """Per-agent state."""
+
+ agent_id: str
+ locked_target_ids: set[str] = field(default_factory=set)
+ focused_target_id: str | None = None
+ cached_selector_map: dict[int, Any] = field(default_factory=dict)
+ last_active: float = field(default_factory=time.time)
+
+
+class TabOwnershipManager:
+ """Tab locking for multi-agent browser sharing.
+
+ All agents see all tabs. Tabs become locked to an agent when the agent
+ mutates them. Locks prevent other agents from mutating the same tab.
+ Read-only commands bypass locks entirely.
+ """
+
+ def __init__(self, browser_session: BrowserSession) -> None:
+ self._browser_session = browser_session
+ self._contexts: dict[str, CallerContext] = {}
+ self._tab_locks: dict[str, str] = {} # target_id → agent_id that holds the lock
+ self._agents_file: Path | None = None
+
+ def set_agents_file(self, path: Path) -> None:
+ """Set the path to the agents registry file."""
+ self._agents_file = path
+
+ def get_or_create_context(self, agent_id: str) -> CallerContext:
+ """Get or create a CallerContext for the given agent."""
+ if agent_id not in self._contexts:
+ self._contexts[agent_id] = CallerContext(agent_id=agent_id)
+ ctx = self._contexts[agent_id]
+ ctx.last_active = time.time()
+ return ctx
+
+ def lock_tab(self, agent_id: str, target_id: str) -> None:
+ """Lock a tab for an agent."""
+ ctx = self.get_or_create_context(agent_id)
+ ctx.locked_target_ids.add(target_id)
+ self._tab_locks[target_id] = agent_id
+ logger.debug(f'Locked tab {target_id[:8]}... for agent {agent_id}')
+
+ def unlock_tab(self, target_id: str) -> None:
+ """Release a lock on a tab."""
+ agent_id = self._tab_locks.pop(target_id, None)
+ if agent_id is None:
+ return
+ ctx = self._contexts.get(agent_id)
+ if ctx is None:
+ return
+ ctx.locked_target_ids.discard(target_id)
+
+ def check_lock(self, agent_id: str, target_id: str | None) -> str | None:
+ """Check if a tab is locked by another agent.
+
+ Returns an error message if locked by someone else, None if OK.
+ """
+ if target_id is None:
+ return None
+ lock_holder = self._tab_locks.get(target_id)
+ if lock_holder is not None and lock_holder != agent_id:
+ return 'Tab is currently in use by another agent. Navigate your own tab with `open <url>`, or run `browser-use register` to get a new agent index.'
+ return None
+
+ def resolve_tab_index(self, index: int) -> str | None:
+ """Map a global tab index to a TargetID.
+
+ All agents see all tabs — indices are global, not scoped per-agent.
+ Returns None if the index is out of range.
+ """
+ all_targets = self._browser_session.session_manager.get_all_page_targets() if self._browser_session.session_manager else []
+ if index < 0 or index >= len(all_targets):
+ return None
+ return all_targets[index].target_id
+
+ async def ensure_caller_has_tab(self, agent_id: str) -> CallerContext:
+ """Ensure an agent has a focused tab.
+
+ On first connect, adopts the browser's current focused tab if it's
+ unlocked. Only creates a new tab if nothing is available.
+ """
+ ctx = self.get_or_create_context(agent_id)
+
+ # If caller already has a valid focused tab, we're good
+ if ctx.focused_target_id:
+ all_target_ids = set()
+ if self._browser_session.session_manager:
+ all_target_ids = {t.target_id for t in self._browser_session.session_manager.get_all_page_targets()}
+ if ctx.focused_target_id in all_target_ids:
+ return ctx
+ ctx.focused_target_id = None
+
+ # Try to adopt the browser's current focused tab if it's unlocked
+ existing_focus = self._browser_session.agent_focus_target_id
+ if existing_focus and self.check_lock(agent_id, existing_focus) is None:
+ ctx.focused_target_id = existing_focus
+ self.lock_tab(agent_id, existing_focus)
+ return ctx
+
+ # Try to adopt any unlocked tab
+ if self._browser_session.session_manager:
+ for t in self._browser_session.session_manager.get_all_page_targets():
+ if self.check_lock(agent_id, t.target_id) is None:
+ ctx.focused_target_id = t.target_id
+ self.lock_tab(agent_id, t.target_id)
+ return ctx
+
+ # No unlocked tabs available — create a new one
+ target_id = await self._browser_session._cdp_create_new_page('about:blank')
+ ctx.focused_target_id = target_id
+ logger.info(f'Created new tab {target_id[:8]}... for agent {agent_id}')
+ return ctx
+
+ def on_tab_created(self, target_id: str) -> None:
+ """Handle a new tab being created. New tabs start unlocked."""
+ if target_id in self._tab_locks:
+ return
+ logger.debug(f'New tab {target_id[:8]}... starts unlocked')
+
+ def on_tab_closed(self, target_id: str) -> None:
+ """Handle a tab being closed. Release its lock and clear any agent's focus."""
+ self.unlock_tab(target_id)
+ for ctx in self._contexts.values():
+ if ctx.focused_target_id == target_id:
+ ctx.focused_target_id = None
+
+ async def cleanup_stale_agents(self) -> None:
+ """Remove contexts for agents that haven't been active for 5+ minutes.
+
+ Also updates the agents.json registry file to remove expired entries.
+ """
+ now = time.time()
+ stale_agents = []
+ for agent_id, ctx in self._contexts.items():
+ if agent_id == SHARED_CONTEXT:
+ continue
+ if now - ctx.last_active > AGENT_EXPIRY_SECONDS:
+ stale_agents.append(agent_id)
+
+ for agent_id in stale_agents:
+ ctx = self._contexts.pop(agent_id, None)
+ if ctx:
+ for target_id in list(ctx.locked_target_ids):
+ self._tab_locks.pop(target_id, None)
+ logger.info(f'Cleaned up stale agent {agent_id} ({len(ctx.locked_target_ids)} locks released)')
+
+ # Update agents.json to remove expired entries
+ if self._agents_file and self._agents_file.exists():
+ try:
+ agents = json.loads(self._agents_file.read_text())
+ agents = {k: v for k, v in agents.items() if now - v.get('last_active', 0) < AGENT_EXPIRY_SECONDS}
+ self._agents_file.write_text(json.dumps(agents))
+ except (json.JSONDecodeError, OSError):
+ pass
diff --git a/skills/browser-use/SKILL.md b/skills/browser-use/SKILL.md
index 56c3170a5..92b88aafd 100644
--- a/skills/browser-use/SKILL.md
+++ b/skills/browser-use/SKILL.md
@@ -18,22 +18,31 @@ For setup details, see https://github.com/browser-use/browser-use/blob/main/brow
## Core Workflow
-1. **Navigate**: `browser-use open <url>` — starts browser if needed
-2. **Inspect**: `browser-use state` — returns clickable elements with indices
-3. **Interact**: use indices from state (`browser-use click 5`, `browser-use input 3 "text"`)
-4. **Verify**: `browser-use state` or `browser-use screenshot` to confirm
-5. **Repeat**: browser stays open between commands
-6. **Cleanup**: `browser-use close` when done
+**Default: connect to the user's existing Chrome browser.** This preserves their logins, cookies, and open tabs.
+
+1. **Register**: `INDEX=$(browser-use register)` — get an agent index (once per session)
+2. **Navigate**: `browser-use --connect $INDEX open <url>` — opens in a new tab in the user's Chrome
+3. **Inspect**: `browser-use --connect $INDEX state` — returns clickable elements with indices
+4. **Interact**: use indices from state (`browser-use --connect $INDEX click 5`, `browser-use --connect $INDEX input 3 "text"`)
+5. **Verify**: `browser-use --connect $INDEX state` or `browser-use --connect $INDEX screenshot` to confirm
+6. **Repeat**: browser stays open between commands
+
+If `--connect` fails (Chrome not running with remote debugging), fall back to `browser-use --headed open <url>` which launches a fresh Chromium.
## Browser Modes
```bash
-browser-use open <url> # Default: headless Chromium
-browser-use --headed open <url> # Visible window
-browser-use --profile "Default" open <url> # Real Chrome with Default profile (existing logins/cookies)
-browser-use --profile "Profile 1" open <url> # Real Chrome with named profile
-browser-use --connect open <url> # Auto-discover running Chrome via CDP
-browser-use --cdp-url ws://localhost:9222/... open <url> # Connect via CDP URL
+# Preferred: connect to user's existing Chrome (requires remote debugging enabled)
+INDEX=$(browser-use register)
+browser-use --connect $INDEX open <url> # Connect to running Chrome with agent index
+
+# Fallback: launch a new browser
+browser-use --headed open <url> # Visible Chromium window
+browser-use open <url> # Headless Chromium
+
+# Other modes
+browser-use --profile "Default" open <url> # Real Chrome with Default profile
+browser-use --cdp-url ws://localhost:9222/... open <url> # Connect via explicit CDP URL
```
`--connect`, `--cdp-url`, and `--profile` are mutually exclusive.
@@ -157,7 +166,8 @@ browser-use --profile "Default" open https://github.com # Already logged in
### Connecting to Existing Chrome
```bash
-browser-use --connect open https://example.com # Auto-discovers Chrome's CDP endpoint
+INDEX=$(browser-use register) # Get agent index first
+browser-use --connect $INDEX open https://example.com # Connect with agent index
```
Requires Chrome with remote debugging enabled. Falls back to probing ports 9222/9229.
@@ -169,13 +179,33 @@ browser-use tunnel 3000 # → https://abc.trycloudfla
browser-use open https://abc.trycloudflare.com # Browse the tunnel
```
+## Multi-Agent (--connect mode)
+
+Multiple agents can share one Chrome browser via `--connect`. Each agent gets its own tab — other agents can't interfere.
+
+**Setup**: Register once, then pass the index with every `--connect` command:
+
+```bash
+INDEX=$(browser-use register) # → prints "1"
+browser-use --connect $INDEX open <url> # Navigate in agent's own tab
+browser-use --connect $INDEX state # Get state from agent's tab
+browser-use --connect $INDEX click <element> # Click in agent's tab
+```
+
+- **Tab locking**: When an agent mutates a tab (click, type, navigate), that tab is locked to it. Other agents get an error if they try to mutate the same tab.
+- **Read-only access**: `state`, `screenshot`, `get`, and `wait` commands work on any tab regardless of locks.
+- **Pre-existing tabs**: Tabs already open in Chrome start unlocked — any agent can claim them.
+- **Agent sessions expire** after 5 minutes of inactivity. Run `browser-use register` again to get a new index.
+- **If you get "Tab is currently in use by another agent"**: do NOT close sessions or force it. Just use `open` to navigate your own tab to the URL you need.
+- **Never run `browser-use close --all`** when other agents are sharing the browser — it kills everything.
+
## Global Options
| Option | Description |
|--------|-------------|
| `--headed` | Show browser window |
| `--profile [NAME]` | Use real Chrome (bare `--profile` uses "Default") |
-| `--connect` | Auto-discover running Chrome via CDP |
+| `--connect INDEX` | Connect to running Chrome via CDP with agent index (run `browser-use register` first) |
| `--cdp-url <url>` | Connect via CDP URL (`http://` or `ws://`) |
| `--session NAME` | Target a named session (default: "default") |
| `--json` | Output as JSON |
diff --git a/skills/remote-browser/SKILL.md b/skills/remote-browser/SKILL.md
index a57ee44f4..ed27d50f4 100644
--- a/skills/remote-browser/SKILL.md
+++ b/skills/remote-browser/SKILL.md
@@ -129,6 +129,23 @@ browser-use open https://abc.trycloudflare.com # Browse the tunnel
Tunnels are independent of browser sessions and persist across `browser-use close`.
+## Multi-Agent (--connect mode)
+
+Multiple agents can share one browser via `--connect`. Each agent gets its own tab — other agents can't interfere.
+
+**Setup**: Register once, then pass the index with every `--connect` command:
+
+```bash
+INDEX=$(browser-use register) # → prints "1"
+browser-use --connect $INDEX open <url> # Navigate in agent's own tab
+browser-use --connect $INDEX state # Get state from agent's tab
+browser-use --connect $INDEX click <element> # Click in agent's tab
+```
+
+- **Tab locking**: When an agent mutates a tab (click, type, navigate), that tab is locked to it. Other agents get an error if they try to mutate the same tab.
+- **Read-only access**: `state`, `screenshot`, `get`, and `wait` commands work on any tab regardless of locks.
+- **Agent sessions expire** after 5 minutes of inactivity. Run `browser-use register` again to get a new index.
+
## Global Options
| Option | Description |
diff --git a/tests/ci/test_tab_ownership.py b/tests/ci/test_tab_ownership.py
new file mode 100644
index 000000000..fe9df3adf
--- /dev/null
+++ b/tests/ci/test_tab_ownership.py
@@ -0,0 +1,330 @@
+"""Tests for tab locking and agent registration (TabOwnershipManager).
+
+Validates that multiple agents can see all tabs but cannot mutate
+tabs that are locked by another agent. Agent identity comes from
+'browser-use register' which assigns numeric indices.
+"""
+
+import json
+import time
+from unittest.mock import AsyncMock, MagicMock
+
+from browser_use.skill_cli.tab_ownership import AGENT_EXPIRY_SECONDS, SHARED_CONTEXT, TabOwnershipManager
+
+
+def _make_target(target_id: str) -> MagicMock:
+ t = MagicMock()
+ t.target_id = target_id
+ t.target_type = 'page'
+ return t
+
+
+def _make_browser_session(targets: list[MagicMock] | None = None) -> MagicMock:
+ bs = MagicMock()
+ bs.agent_focus_target_id = None
+ bs.session_manager = MagicMock()
+ bs.session_manager.get_all_page_targets.return_value = targets or []
+ bs._cdp_create_new_page = AsyncMock(return_value='new-target-001')
+ return bs
+
+
+# ---------------------------------------------------------------------------
+# Context management
+# ---------------------------------------------------------------------------
+
+
+def test_get_or_create_context():
+ bs = _make_browser_session()
+ mgr = TabOwnershipManager(bs)
+ ctx = mgr.get_or_create_context('1')
+ assert ctx.agent_id == '1'
+ assert ctx.locked_target_ids == set()
+ assert ctx.focused_target_id is None
+ assert mgr.get_or_create_context('1') is ctx
+
+
+def test_context_updates_last_active():
+ bs = _make_browser_session()
+ mgr = TabOwnershipManager(bs)
+ ctx = mgr.get_or_create_context('1')
+ first_active = ctx.last_active
+ import time as _time
+
+ _time.sleep(0.01)
+ mgr.get_or_create_context('1')
+ assert ctx.last_active > first_active
+
+
+# ---------------------------------------------------------------------------
+# Tab locking
+# ---------------------------------------------------------------------------
+
+
+def test_lock_tab():
+ bs = _make_browser_session()
+ mgr = TabOwnershipManager(bs)
+ mgr.lock_tab('1', 'target-A')
+ ctx = mgr.get_or_create_context('1')
+ assert 'target-A' in ctx.locked_target_ids
+ assert mgr._tab_locks['target-A'] == '1'
+
+
+def test_unlock_tab():
+ bs = _make_browser_session()
+ mgr = TabOwnershipManager(bs)
+ mgr.lock_tab('1', 'target-A')
+ mgr.unlock_tab('target-A')
+ ctx = mgr.get_or_create_context('1')
+ assert 'target-A' not in ctx.locked_target_ids
+ assert 'target-A' not in mgr._tab_locks
+
+
+# ---------------------------------------------------------------------------
+# Lock checking
+# ---------------------------------------------------------------------------
+
+
+def test_check_lock_unlocked():
+ bs = _make_browser_session()
+ mgr = TabOwnershipManager(bs)
+ assert mgr.check_lock('1', 'target-A') is None
+
+
+def test_check_lock_own_tab():
+ bs = _make_browser_session()
+ mgr = TabOwnershipManager(bs)
+ mgr.lock_tab('1', 'target-A')
+ assert mgr.check_lock('1', 'target-A') is None
+
+
+def test_check_lock_other_agent():
+ bs = _make_browser_session()
+ mgr = TabOwnershipManager(bs)
+ mgr.lock_tab('1', 'target-A')
+ err = mgr.check_lock('2', 'target-A')
+ assert err is not None
+ assert 'in use by another agent' in err
+
+
+def test_check_lock_none_target():
+ bs = _make_browser_session()
+ mgr = TabOwnershipManager(bs)
+ assert mgr.check_lock('1', None) is None
+
+
+# ---------------------------------------------------------------------------
+# Tab index resolution — ALL tabs visible
+# ---------------------------------------------------------------------------
+
+
+def test_resolve_tab_index_sees_all_tabs():
+ t1 = _make_target('target-A')
+ t2 = _make_target('target-B')
+ t3 = _make_target('target-C')
+ bs = _make_browser_session(targets=[t1, t2, t3])
+ mgr = TabOwnershipManager(bs)
+ mgr.lock_tab('1', 'target-A')
+
+ assert mgr.resolve_tab_index(0) == 'target-A'
+ assert mgr.resolve_tab_index(1) == 'target-B'
+ assert mgr.resolve_tab_index(2) == 'target-C'
+ assert mgr.resolve_tab_index(3) is None
+ assert mgr.resolve_tab_index(-1) is None
+
+
+# ---------------------------------------------------------------------------
+# ensure_caller_has_tab
+# ---------------------------------------------------------------------------
+
+
+async def test_ensure_adopts_unlocked_tab():
+ t1 = _make_target('existing-tab')
+ bs = _make_browser_session(targets=[t1])
+ bs.agent_focus_target_id = 'existing-tab'
+ mgr = TabOwnershipManager(bs)
+
+ ctx = await mgr.ensure_caller_has_tab('1')
+ bs._cdp_create_new_page.assert_not_awaited()
+ assert ctx.focused_target_id == 'existing-tab'
+
+
+async def test_ensure_skips_locked_tab():
+ t1 = _make_target('locked-tab')
+ t2 = _make_target('free-tab')
+ bs = _make_browser_session(targets=[t1, t2])
+ bs.agent_focus_target_id = 'locked-tab'
+ mgr = TabOwnershipManager(bs)
+ mgr.lock_tab('1', 'locked-tab')
+
+ ctx = await mgr.ensure_caller_has_tab('2')
+ bs._cdp_create_new_page.assert_not_awaited()
+ assert ctx.focused_target_id == 'free-tab'
+
+
+async def test_ensure_creates_tab_when_all_locked():
+ t1 = _make_target('locked-tab')
+ bs = _make_browser_session(targets=[t1])
+ bs.agent_focus_target_id = 'locked-tab'
+ mgr = TabOwnershipManager(bs)
+ mgr.lock_tab('1', 'locked-tab')
+
+ ctx = await mgr.ensure_caller_has_tab('2')
+ bs._cdp_create_new_page.assert_awaited_once_with('about:blank')
+ assert ctx.focused_target_id == 'new-target-001'
+
+
+async def test_ensure_reuses_own_tab():
+ t1 = _make_target('my-tab')
+ bs = _make_browser_session(targets=[t1])
+ mgr = TabOwnershipManager(bs)
+ ctx = mgr.get_or_create_context('1')
+ ctx.focused_target_id = 'my-tab'
+
+ result = await mgr.ensure_caller_has_tab('1')
+ bs._cdp_create_new_page.assert_not_awaited()
+ assert result.focused_target_id == 'my-tab'
+
+
+# ---------------------------------------------------------------------------
+# Tab lifecycle
+# ---------------------------------------------------------------------------
+
+
+def test_on_tab_created_starts_unlocked():
+ bs = _make_browser_session()
+ mgr = TabOwnershipManager(bs)
+ mgr.on_tab_created('new-tab')
+ assert 'new-tab' not in mgr._tab_locks
+
+
+def test_on_tab_closed_releases_lock():
+ bs = _make_browser_session()
+ mgr = TabOwnershipManager(bs)
+ mgr.lock_tab('1', 'target-A')
+ ctx = mgr.get_or_create_context('1')
+ ctx.focused_target_id = 'target-A'
+
+ mgr.on_tab_closed('target-A')
+ assert 'target-A' not in mgr._tab_locks
+ assert ctx.focused_target_id is None
+
+
+# ---------------------------------------------------------------------------
+# Timestamp-based cleanup
+# ---------------------------------------------------------------------------
+
+
+async def test_cleanup_stale_agents(tmp_path):
+ bs = _make_browser_session()
+ mgr = TabOwnershipManager(bs)
+
+ # Active agent
+ mgr.lock_tab('1', 'target-live')
+
+ # Stale agent (expired)
+ ctx2 = mgr.get_or_create_context('2')
+ ctx2.last_active = time.time() - AGENT_EXPIRY_SECONDS - 1
+ mgr.lock_tab('2', 'target-stale')
+ ctx2.last_active = time.time() - AGENT_EXPIRY_SECONDS - 1 # re-set after lock_tab touches it
+
+ # Set up agents file
+ agents_file = tmp_path / 'agents.json'
+ agents_file.write_text(json.dumps({
+ '1': {'last_active': time.time()},
+ '2': {'last_active': time.time() - AGENT_EXPIRY_SECONDS - 1},
+ }))
+ mgr.set_agents_file(agents_file)
+
+ await mgr.cleanup_stale_agents()
+
+ # Active agent still tracked
+ assert '1' in mgr._contexts
+ assert 'target-live' in mgr._tab_locks
+
+ # Stale agent cleaned up
+ assert '2' not in mgr._contexts
+ assert 'target-stale' not in mgr._tab_locks
+
+ # Agents file updated
+ agents = json.loads(agents_file.read_text())
+ assert '1' in agents
+ assert '2' not in agents
+
+
+async def test_cleanup_never_removes_shared():
+ bs = _make_browser_session()
+ mgr = TabOwnershipManager(bs)
+ mgr.lock_tab(SHARED_CONTEXT, 'target-shared')
+
+ await mgr.cleanup_stale_agents()
+ assert SHARED_CONTEXT in mgr._contexts
+
+
+# ---------------------------------------------------------------------------
+# Two agents: isolation
+# ---------------------------------------------------------------------------
+
+
+def test_two_agents_lock_different_tabs():
+ bs = _make_browser_session()
+ mgr = TabOwnershipManager(bs)
+
+ mgr.lock_tab('1', 'tab-A')
+ mgr.lock_tab('2', 'tab-B')
+
+ assert mgr.check_lock('1', 'tab-A') is None
+ assert mgr.check_lock('2', 'tab-B') is None
+ assert mgr.check_lock('1', 'tab-B') is not None
+ assert mgr.check_lock('2', 'tab-A') is not None
+ assert mgr.check_lock('1', 'tab-unlocked') is None
+ assert mgr.check_lock('2', 'tab-unlocked') is None
+
+
+# ---------------------------------------------------------------------------
+# Register command
+# ---------------------------------------------------------------------------
+
+
+def test_register_assigns_sequential_indices(tmp_path):
+ """Test that register assigns 1, 2, 3 etc."""
+ agents_file = tmp_path / 'agents.json'
+
+ # First register
+ agents = {}
+ now = time.time()
+ next_idx = 1
+ while str(next_idx) in agents:
+ next_idx += 1
+ agents[str(next_idx)] = {'last_active': now}
+ agents_file.write_text(json.dumps(agents))
+ assert next_idx == 1
+
+ # Second register
+ agents = json.loads(agents_file.read_text())
+ next_idx = 1
+ while str(next_idx) in agents:
+ next_idx += 1
+ agents[str(next_idx)] = {'last_active': now}
+ agents_file.write_text(json.dumps(agents))
+ assert next_idx == 2
+
+
+def test_register_reclaims_expired_indices(tmp_path):
+ """Test that expired indices get reclaimed."""
+ agents_file = tmp_path / 'agents.json'
+ now = time.time()
+ agents = {
+ '1': {'last_active': now - AGENT_EXPIRY_SECONDS - 1}, # expired
+ '2': {'last_active': now}, # active
+ }
+ agents_file.write_text(json.dumps(agents))
+
+ # Clean expired and find next
+ agents = json.loads(agents_file.read_text())
+ agents = {k: v for k, v in agents.items() if now - v.get('last_active', 0) < AGENT_EXPIRY_SECONDS}
+ next_idx = 1
+ while str(next_idx) in agents:
+ next_idx += 1
+
+ # Should reclaim index 1
+ assert next_idx == 1