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
refactor: remove --agent/register/tab-ownership, sessions-as-agents model
ShawnPanaca05f46352fa
diff --git a/browser_use/skill_cli/commands/browser.py b/browser_use/skill_cli/commands/browser.pyindex ad97783dc..2ec016717 100644--- a/browser_use/skill_cli/commands/browser.py+++ b/browser_use/skill_cli/commands/browser.py@@ -180,10 +180,6 @@ async def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> Atab_command = params.get('tab_command')if tab_command == 'list':- # tab list — handled by daemon which injects _tab_list- if '_tab_list' in params:- return {'_raw_text': params['_tab_list']}- # Fallback without tab ownership (no --connect)page_targets = bs.session_manager.get_all_page_targets() if bs.session_manager else []lines = ['TAB URL']for i, t in enumerate(page_targets):@@ -197,18 +193,12 @@ async def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> Areturn {'created': target_id[:8], 'url': url}elif tab_command == 'switch':- # Just update internal focus — don't visually activate the tab in Chrome- # The daemon already sets ctx.focused_target_id and swaps agent_focus_target_id- 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- bs.agent_focus_target_id = target_id- return {'switched': params.get('tab', 0)}+ 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}'}+ bs.agent_focus_target_id = page_targets[tab_index].target_id+ return {'switched': tab_index}elif tab_command == 'close':tab_indices = params.get('tabs', [])@@ -236,10 +226,6 @@ async def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> Aif idx < 0 or idx >= len(page_targets):errors.append(f'Tab {idx} out of range')continue- lock_err = params.get(f'_lock_check_{idx}')- if lock_err:- errors.append(f'Tab {idx}: {lock_err}')- continuetry:await _close_target(page_targets[idx].target_id)closed.append(idx)diff --git a/browser_use/skill_cli/daemon.py b/browser_use/skill_cli/daemon.pyindex 6526866b7..c681c8e1e 100644--- a/browser_use/skill_cli/daemon.py+++ b/browser_use/skill_cli/daemon.py@@ -18,7 +18,6 @@ from typing import TYPE_CHECKINGif TYPE_CHECKING:from browser_use.skill_cli.sessions import SessionInfo- from browser_use.skill_cli.tab_ownership import TabOwnershipManager# Configure logging before importslogging.basicConfig(@@ -60,10 +59,7 @@ class Daemon:self._session: SessionInfo | None = Noneself._shutdown_task: asyncio.Task | None = Noneself._browser_watchdog_task: asyncio.Task | None = None- self._agent_cleanup_task: asyncio.Task | None = None- self._tab_ownership: TabOwnershipManager | None = Noneself._session_lock = asyncio.Lock()- self._dispatch_lock = asyncio.Lock()self._last_command_time: float = 0.0self._idle_timeout: float = 30 * 60.0 # 30 minutesself._idle_watchdog_task: asyncio.Task | None = None@@ -158,21 +154,6 @@ class Daemon:)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() / f'{self.session}.agents.json')-- # Register initial tabs with tab ownership (no event bus)- if bs.session_manager:- for target in bs.session_manager.get_all_page_targets():- self._tab_ownership.on_tab_created(target.target_id)-- # Start periodic agent cleanup- self._agent_cleanup_task = asyncio.create_task(self._cleanup_stale_agents())-# Start idle timeout watchdogself._idle_watchdog_task = asyncio.create_task(self._watch_idle())@@ -226,16 +207,6 @@ class Daemon:self._request_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,@@ -321,97 +292,16 @@ 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 sessionsession = 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)-- # Handle tab subcommands- if action == 'tab':- tab_cmd = params.get('tab_command')- if tab_cmd == 'list':- tab_list = self._tab_ownership.get_tab_list(agent_id)- lines = ['TAB LOCKED URL']- for t in tab_list:- lines.append(f'{t["index"]:<4} {t["locked"]:<9} {t["url"]}')- params['_tab_list'] = '\n'.join(lines)- elif tab_cmd == '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}).',- }- 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- ctx.focused_target_id = resolved- elif tab_cmd == 'close':- # Pre-check locks for each tab the agent wants to close- all_targets = bs.session_manager.get_all_page_targets() if bs.session_manager else []- for i in range(len(all_targets)):- lock_err = self._tab_ownership.check_lock(agent_id, all_targets[i].target_id)- if lock_err:- params[f'_lock_check_{i}'] = lock_err-- # 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)-- # Serialize focus swap + command execution so concurrent agents- # don't corrupt each other's focus state on the shared BrowserSession.- async with self._dispatch_lock:- # 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- 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- new_focus = bs.agent_focus_target_id- ctx.focused_target_id = new_focus- ctx.cached_selector_map = bs._cached_selector_map- bs.agent_focus_target_id = saved_focus- bs._cached_selector_map = saved_selector_map- # If focus changed (e.g. tab new), lock the new tab- if new_focus and new_focus != saved_focus:- self._tab_ownership.lock_tab(agent_id, new_focus)+ # 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:- # No tab ownership — single agent mode, no lock needed- 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}'}+ return {'id': req_id, 'success': False, 'error': f'Unknown action: {action}'}return {'id': req_id, 'success': True, 'data': result}@@ -511,8 +401,7 @@ class Daemon:if self._browser_watchdog_task:self._browser_watchdog_task.cancel()- if self._agent_cleanup_task:- self._agent_cleanup_task.cancel()+if self._idle_watchdog_task:self._idle_watchdog_task.cancel()diff --git a/browser_use/skill_cli/main.py b/browser_use/skill_cli/main.pyindex 8beec121d..90a5d22a8 100755--- a/browser_use/skill_cli/main.py+++ b/browser_use/skill_cli/main.py@@ -100,37 +100,6 @@ if _get_subcommand() == 'init':init_main()sys.exit(0)-# Handle 'register' command — assigns an agent index for multi-agent mode (per-session)-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)- # Resolve session name from --session flag or env- _session = 'default'- for i, arg in enumerate(sys.argv):- if arg == '--session' and i + 1 < len(sys.argv):- _session = sys.argv[i + 1]- break- if _session == 'default':- _session = os.environ.get('BROWSER_USE_SESSION', 'default')- agents_file = _home_dir / f'{_session}.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:@@ -667,13 +636,6 @@ Setup:default=False,help='(Deprecated) Use "browser-use connect" instead',)- parser.add_argument(- '--agent',- nargs=1,- metavar='INDEX',- default=None,- help='Multi-agent mode with tab isolation (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')parser.add_argument('--mcp', action='store_true', help='Run as MCP server (JSON-RPC via stdin/stdout)')@@ -689,7 +651,6 @@ Setup:subparsers.add_parser('install', help='Install Chromium browser + system dependencies')# register- subparsers.add_parser('register', help='Register an agent for multi-agent --connect mode')# initp = subparsers.add_parser('init', help='Generate browser-use template file')@@ -1407,9 +1368,9 @@ def main() -> int:# Handle --connect deprecationif args.connect:print('Note: --connect has been replaced.', file=sys.stderr)- print(' To connect to Chrome: browser-use connect', file=sys.stderr)- print(' Then run commands: browser-use open <url>', file=sys.stderr)- print(' For multi-agent: browser-use --agent INDEX open <url>', file=sys.stderr)+ print(' To connect to Chrome: browser-use connect', file=sys.stderr)+ print(' For cloud browser: browser-use cloud connect', file=sys.stderr)+ print(' For multiple agents: use --session NAME per agent', file=sys.stderr)return 1# Handle connect command (discover local Chrome, start daemon)@@ -1438,31 +1399,6 @@ def main() -> int:return 1return 0- # Resolve --agent to agent_id- agent_id = '__shared__'- if args.agent:- agent_id = args.agent[0]- # Validate agent index against per-session registry- agents_file = _get_home_dir() / f'{session}.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:- 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- agent_entry['last_active'] = now- agents_file.write_text(json.dumps(agents))-# Mutual exclusivityif args.cdp_url and args.profile:print('Error: --cdp-url and --profile are mutually exclusive', file=sys.stderr)@@ -1492,7 +1428,7 @@ def main() -> int:params['profile'] = args.profile# Send command to daemon- response = send_command(args.command, params, session=session, agent_id=agent_id)+ response = send_command(args.command, params, session=session)# Output responseif args.json:diff --git a/browser_use/skill_cli/tab_ownership.py b/browser_use/skill_cli/tab_ownership.pydeleted file mode 100644index a36474012..000000000--- a/browser_use/skill_cli/tab_ownership.py+++ /dev/null@@ -1,204 +0,0 @@-"""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-- def get_tab_list(self, agent_id: str) -> list[dict[str, Any]]:- """Get all tabs with their lock status relative to the calling agent."""- all_targets = self._browser_session.session_manager.get_all_page_targets() if self._browser_session.session_manager else []- tabs = []- for i, target in enumerate(all_targets):- lock_holder = self._tab_locks.get(target.target_id)- if lock_holder is None:- locked = '-'- elif lock_holder == agent_id:- locked = 'you'- else:- locked = f'agent{lock_holder}'- tabs.append({- 'index': i,- 'locked': locked,- 'url': target.url,- 'title': target.title,- })- return tabs-- 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):- passdiff --git a/skills/browser-use/SKILL.md b/skills/browser-use/SKILL.mdindex 8302ef06d..d2e0b4ee9 100644--- a/skills/browser-use/SKILL.md+++ b/skills/browser-use/SKILL.md@@ -57,7 +57,7 @@ browser-use open <url> # Navigate to URLbrowser-use back # Go back in historybrowser-use scroll down # Scroll down (--amount N for pixels)browser-use scroll up # Scroll up-browser-use tab list # List all tabs with lock status+browser-use tab list # List all tabsbrowser-use tab new [url] # Open a new tab (blank or with URL)browser-use tab switch <index> # Switch to tab by indexbrowser-use tab close <index> [index...] # Close one or more tabs@@ -201,42 +201,30 @@ browser-use tunnel 3000 # → https://abc.trycloudflabrowser-use open https://abc.trycloudflare.com # Browse the tunnel```-## Multi-Agent (--agent)+## Multi-Agent Workflows-Multiple agents can share one browser via `--agent`. Each agent gets its own tab — other agents can't interfere. Works with any browser mode (connect, cloud connect, profile, headless).--**Setup**: Connect once, register agents, then pass `--agent` with every command:+Each agent gets its own session with its own browser. No shared state, no conflicts.```bash-browser-use connect # or cloud connect, or --profile, etc.-INDEX=$(browser-use register) # → prints "1"-browser-use --agent $INDEX open <url> # Navigate in agent's own tab-browser-use --agent $INDEX state # Get state from agent's tab-browser-use --agent $INDEX click <element> # Click in agent's tab-```+# Agent 1: research on cloud browser+browser-use --session research cloud connect+browser-use --session research open https://wikipedia.org-- **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 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.+# Agent 2: coding on cloud browser+browser-use --session coding cloud connect+browser-use --session coding open https://github.com-## Multiple Browser Sessions+# Agent 3: local headless Chromium+browser-use --session local open https://example.com-Run different browsers simultaneously with `--session`:--```bash-browser-use --session cloud cloud connect # Cloud browser-browser-use --session local --headed open <url> # Local Chromium-browser-use --session work --profile "Default" open <url> # Real Chrome+# List all+browser-use sessions-browser-use sessions # List all active-browser-use --session cloud close # Close one-browser-use close --all # Close all+# Clean up+browser-use close --all```-Each session gets its own daemon, socket, and state. See `references/multi-session.md` for details.+For cloud browsers, each session provisions its own instance. For local, each session launches its own headless Chromium. Use `--session NAME` on every command. See `references/multi-session.md` for details.## Configuration@@ -257,7 +245,6 @@ Config stored in `~/.browser-use/config.json`.|--------|-------------|| `--headed` | Show browser window || `--profile [NAME]` | Use real Chrome (bare `--profile` uses "Default") |-| `--agent INDEX` | Multi-agent mode with tab isolation (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/browser-use/references/multi-session.md b/skills/browser-use/references/multi-session.mdindex eb9a595ca..1679b5bd3 100644--- a/skills/browser-use/references/multi-session.md+++ b/skills/browser-use/references/multi-session.md@@ -35,9 +35,8 @@ If you forget `--session`, the command goes to the `default` session. This is th# Session 1: cloud browserbrowser-use --session cloud cloud connect-# Session 2: connect to user's Chrome with multi-agent-INDEX=$(browser-use register)-browser-use --session chrome --connect $INDEX open <url>+# Session 2: connect to user's Chrome+browser-use --session chrome connect# Session 3: headed Chromium for debuggingbrowser-use --session debug --headed open <url>@@ -45,12 +44,6 @@ browser-use --session debug --headed open <url>Each session is fully independent. The cloud session talks to a remote browser, the chrome session talks to the user's Chrome, and the debug session manages its own Chromium — all running simultaneously.-## Agent indices and sessions--`browser-use register` writes to a shared `agents.json` (not per-session). An index like `1` can be used with any session that connects to the same Chrome. Typically you'd use `--connect` with one session and bare commands with others.--If two sessions both use `--connect` to the same Chrome, their tab ownership is independent — locks in one session don't protect tabs in the other. Use one session per Chrome instance for multi-agent work.-## Listing and managing sessions```bashdiff --git a/tests/ci/test_tab_ownership.py b/tests/ci/test_tab_ownership.pydeleted file mode 100644index c49370853..000000000--- a/tests/ci/test_tab_ownership.py+++ /dev/null@@ -1,325 +0,0 @@-"""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 _run_register(tmp_path) -> int:- """Run the real `browser-use register` command and return the assigned index."""- import os- import subprocess- import sys-- env = {**os.environ, 'BROWSER_USE_HOME': str(tmp_path)}- result = subprocess.run(- [sys.executable, '-m', 'browser_use.skill_cli.main', 'register'],- capture_output=True,- text=True,- env=env,- timeout=10,- )- assert result.returncode == 0, f'register failed: {result.stderr}'- return int(result.stdout.strip())---def test_register_assigns_sequential_indices(tmp_path):- """Test that register assigns 1, 2, 3 etc."""- assert _run_register(tmp_path) == 1- assert _run_register(tmp_path) == 2- assert _run_register(tmp_path) == 3---def test_register_reclaims_expired_indices(tmp_path):- """Test that expired indices get reclaimed."""- agents_file = tmp_path / 'agents.json'- now = time.time()- # Pre-populate: index 1 expired, index 2 active- agents = {- '1': {'last_active': now - AGENT_EXPIRY_SECONDS - 1},- '2': {'last_active': now},- }- agents_file.write_text(json.dumps(agents))-- # Should reclaim expired index 1- assert _run_register(tmp_path) == 1