Skip to content

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

feat: add `tab` command (list, new, switch, close) and agent registration

ShawnPanaf819d3e3a64a
diff --git a/browser_use/skill_cli/commands/browser.py b/browser_use/skill_cli/commands/browser.py
index b1ca714bf..2b2bf03e1 100644
--- a/browser_use/skill_cli/commands/browser.py
+++ b/browser_use/skill_cli/commands/browser.py
@@ -21,6 +21,7 @@ COMMANDS = {
'state',
'switch',
'close-tab',
+ 'tab',
'keys',
'select',
'upload',
@@ -224,6 +225,78 @@ async def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> A
await bs.event_bus.dispatch(CloseTabEvent(target_id=target_id))
return {'closed': params.get('tab')}
+ elif action == 'tab':
+ tab_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):
+ lines.append(f'{i:<4} {t.url}')
+ return {'_raw_text': '\n'.join(lines)}
+
+ elif tab_command == 'new':
+ url = params.get('url', 'about:blank')
+ target_id = await bs._cdp_create_new_page(url, background=True)
+ bs.agent_focus_target_id = target_id
+ return {'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)}
+
+ elif tab_command == 'close':
+ from browser_use.browser.events import CloseTabEvent
+
+ tab_indices = params.get('tabs', [])
+
+ page_targets = bs.session_manager.get_all_page_targets() if bs.session_manager else []
+
+ if not tab_indices:
+ # 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': [0]}
+
+ # Close specific tabs
+ closed = []
+ errors = []
+ for idx in sorted(tab_indices, reverse=True): # reverse to avoid index shift
+ if 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}')
+ continue
+ try:
+ await bs.event_bus.dispatch(CloseTabEvent(target_id=page_targets[idx].target_id))
+ closed.append(idx)
+ except Exception as e:
+ errors.append(f'Tab {idx}: {e}')
+ result: dict[str, Any] = {'closed': closed}
+ if errors:
+ result['errors'] = errors
+ return result
+
+ return {'error': 'Invalid tab command. Use: list, switch, close'}
+
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 a486a3f54..e6e355a0d 100644
--- a/browser_use/skill_cli/daemon.py
+++ b/browser_use/skill_cli/daemon.py
@@ -275,6 +275,37 @@ class Daemon:
}
params['_resolved_target_id'] = resolved
+ # Handle tab subcommands
+ elif 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)
@@ -301,10 +332,14 @@ class Daemon:
finally:
# Save caller's updated focus/selector map and restore previous
if self._tab_ownership:
- ctx.focused_target_id = bs.agent_focus_target_id
+ 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 # type: ignore[possibly-undefined]
bs._cached_selector_map = saved_selector_map # type: ignore[possibly-undefined]
+ # If focus changed (e.g. tab new), lock the new tab
+ if new_focus and new_focus != saved_focus: # type: ignore[possibly-undefined]
+ self._tab_ownership.lock_tab(agent_id, new_focus)
return {'id': req_id, 'success': True, 'data': result}
diff --git a/browser_use/skill_cli/main.py b/browser_use/skill_cli/main.py
index 811c2d5bc..dfb181795 100755
--- a/browser_use/skill_cli/main.py
+++ b/browser_use/skill_cli/main.py
@@ -485,12 +485,26 @@ Setup:
# state
subparsers.add_parser('state', help='Get browser state (URL, title, elements)')
- # switch <tab>
- p = subparsers.add_parser('switch', help='Switch to tab')
+ # tab (list, switch, close)
+ tab_p = subparsers.add_parser('tab', help='Tab management (list, switch, close)')
+ tab_sub = tab_p.add_subparsers(dest='tab_command')
+
+ tab_sub.add_parser('list', help='List all tabs with lock status')
+
+ p = tab_sub.add_parser('new', help='Open a new blank tab')
+ p.add_argument('url', nargs='?', default='about:blank', help='URL to open (default: about:blank)')
+
+ p = tab_sub.add_parser('switch', help='Switch to tab')
+ p.add_argument('tab', type=int, help='Tab index')
+
+ p = tab_sub.add_parser('close', help='Close tab(s)')
+ p.add_argument('tabs', type=int, nargs='*', help='Tab indices to close (current if none)')
+
+ # Backward compat aliases
+ p = subparsers.add_parser('switch', help='Switch to tab (alias for tab switch)')
p.add_argument('tab', type=int, help='Tab index')
- # close-tab [tab]
- p = subparsers.add_parser('close-tab', help='Close tab')
+ p = subparsers.add_parser('close-tab', help='Close tab (alias for tab close)')
p.add_argument('tab', type=int, nargs='?', help='Tab index (current if not specified)')
# keys <keys>
diff --git a/browser_use/skill_cli/tab_ownership.py b/browser_use/skill_cli/tab_ownership.py
index b8fff10e7..a36474012 100644
--- a/browser_use/skill_cli/tab_ownership.py
+++ b/browser_use/skill_cli/tab_ownership.py
@@ -103,6 +103,26 @@ class TabOwnershipManager:
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.
diff --git a/skills/browser-use/SKILL.md b/skills/browser-use/SKILL.md
index 92b88aafd..c97042864 100644
--- a/skills/browser-use/SKILL.md
+++ b/skills/browser-use/SKILL.md
@@ -55,8 +55,10 @@ browser-use open <url> # Navigate to URL
browser-use back # Go back in history
browser-use scroll down # Scroll down (--amount N for pixels)
browser-use scroll up # Scroll up
-browser-use switch <tab> # Switch to tab by index
-browser-use close-tab [tab] # Close tab (current if no index)
+browser-use tab list # List all tabs with lock status
+browser-use tab new [url] # Open a new tab (blank or with URL)
+browser-use tab switch <index> # Switch to tab by index
+browser-use tab close <index> [index...] # Close one or more tabs
# Page State — always run state first to get element indices
browser-use state # URL, title, clickable elements with indices
diff --git a/skills/remote-browser/SKILL.md b/skills/remote-browser/SKILL.md
index ed27d50f4..9c8b0efe9 100644
--- a/skills/remote-browser/SKILL.md
+++ b/skills/remote-browser/SKILL.md
@@ -42,8 +42,10 @@ browser-use open <url> # Navigate to URL
browser-use back # Go back in history
browser-use scroll down # Scroll down (--amount N for pixels)
browser-use scroll up # Scroll up
-browser-use switch <tab> # Switch to tab by index
-browser-use close-tab [tab] # Close tab (current if no index)
+browser-use tab list # List all tabs with lock status
+browser-use tab new [url] # Open a new tab (blank or with URL)
+browser-use tab switch <index> # Switch to tab by index
+browser-use tab close <index> [index...] # Close one or more tabs
# Page State — always run state first to get element indices
browser-use state # URL, title, clickable elements with indices