Skip to content

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

fix SwitchTab by using TargetID for all tab_ids

Nick Sweeting8d86832095bb
diff --git a/browser_use/agent/prompts.py b/browser_use/agent/prompts.py
index 7501e2531..d1e859206 100644
--- a/browser_use/agent/prompts.py
+++ b/browser_use/agent/prompts.py
@@ -162,16 +162,16 @@ class AgentMessagePrompt:
# Find tabs that match both URL and title to identify current tab more reliably
for tab in self.browser_state.tabs:
if tab.url == self.browser_state.url and tab.title == self.browser_state.title:
- current_tab_candidates.append(tab.page_id)
+ current_tab_candidates.append(tab.target_id)
# If we have exactly one match, mark it as current
# Otherwise, don't mark any tab as current to avoid confusion
- current_tab_index = current_tab_candidates[0] if len(current_tab_candidates) == 1 else None
+ current_target_id = current_tab_candidates[0] if len(current_tab_candidates) == 1 else None
for tab in self.browser_state.tabs:
- tabs_text += f'Tab {tab.page_id}: {tab.url} - {tab.title[:30]}\n'
+ tabs_text += f'Tab {tab.target_id[-4:]}: {tab.url} - {tab.title[:30]}\n'
- current_tab_text = f'Current tab: {current_tab_index}' if current_tab_index is not None else ''
+ current_tab_text = f'Current tab: {current_target_id[-4:]}' if current_target_id is not None else ''
# Check if current page is a PDF viewer and add appropriate message
pdf_message = ''
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 15e9288bc..9461b21d4 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -460,12 +460,12 @@ class Agent(Generic[Context, AgentStructuredOutput]):
"""Get instance-specific logger with task ID in the name"""
_browser_session_id = self.browser_session.id if self.browser_session else self.id
- _current_page_id = (
- self.browser_session.agent_focus.target_id[-2:]
+ _current_target_id = (
+ self.browser_session.agent_focus.target_id[-4:]
if self.browser_session and self.browser_session.agent_focus and self.browser_session.agent_focus.target_id
else '--'
)
- return logging.getLogger(f'browser_use.AgentπŸ…° {self.task_id[-4:]} on πŸ†‚ {_browser_session_id[-4:]} πŸ…Ÿ {_current_page_id}')
+ return logging.getLogger(f'browser_use.AgentπŸ…° {self.task_id[-4:]} on πŸ†‚ {_browser_session_id[-4:]} πŸ…Ÿ {_current_target_id}')
@property
def browser_profile(self) -> BrowserProfile:
diff --git a/browser_use/browser/aboutblank_watchdog.py b/browser_use/browser/aboutblank_watchdog.py
index c76a97a62..343fbc231 100644
--- a/browser_use/browser/aboutblank_watchdog.py
+++ b/browser_use/browser/aboutblank_watchdog.py
@@ -3,6 +3,7 @@
from typing import TYPE_CHECKING, ClassVar
from bubus import BaseEvent
+from cdp_use.cdp.target import TargetID
from pydantic import PrivateAttr
from browser_use.browser.events import (
@@ -81,7 +82,7 @@ class AboutBlankWatchdog(BaseWatchdog):
# Multiple tabs exist, check after close
await self._check_and_ensure_about_blank_tab()
- async def attach_to_target(self, target_id: str) -> None:
+ async def attach_to_target(self, target_id: TargetID) -> None:
"""AboutBlankWatchdog doesn't monitor individual targets."""
pass
@@ -122,7 +123,7 @@ class AboutBlankWatchdog(BaseWatchdog):
except Exception as e:
self.logger.error(f'[AboutBlankWatchdog] Error showing DVD screensaver: {e}')
- async def _show_dvd_screensaver_loading_animation_cdp(self, target_id: str, browser_session_label: str) -> None:
+ async def _show_dvd_screensaver_loading_animation_cdp(self, target_id: TargetID, browser_session_label: str) -> None:
"""
Injects a DVD screensaver-style bouncing logo loading animation overlay into the target using CDP.
This is used to visually indicate that the browser is setting up or waiting.
@@ -246,8 +247,7 @@ class AboutBlankWatchdog(BaseWatchdog):
# No need to detach - session is cached
# Dispatch event
- tab_index = await self.browser_session.get_tab_index(target_id)
- self.event_bus.dispatch(AboutBlankDVDScreensaverShownEvent(tab_index=tab_index))
+ self.event_bus.dispatch(AboutBlankDVDScreensaverShownEvent(target_id=target_id))
except Exception as e:
self.logger.error(f'[AboutBlankWatchdog] Error injecting DVD screensaver: {e}')
diff --git a/browser_use/browser/crash_watchdog.py b/browser_use/browser/crash_watchdog.py
index 2118354d0..6f5372507 100644
--- a/browser_use/browser/crash_watchdog.py
+++ b/browser_use/browser/crash_watchdog.py
@@ -6,6 +6,7 @@ from typing import TYPE_CHECKING, ClassVar
import psutil
from bubus import BaseEvent
+from cdp_use.cdp.target import SessionID, TargetID
from cdp_use.cdp.target.events import TargetCrashedEvent
from pydantic import Field, PrivateAttr
@@ -71,7 +72,7 @@ class CrashWatchdog(BaseWatchdog):
assert self.browser_session.agent_focus is not None, 'No current target ID'
await self.attach_to_target(self.browser_session.agent_focus.target_id)
- async def attach_to_target(self, target_id: str) -> None:
+ async def attach_to_target(self, target_id: TargetID) -> None:
"""Set up crash monitoring for a specific target using CDP."""
try:
# Create temporary session for monitoring without switching focus
@@ -106,7 +107,7 @@ class CrashWatchdog(BaseWatchdog):
# cdp_client.on('Network.loadingFailed', on_loading_failed, session_id=session_id)
# cdp_client.on('Network.loadingFinished', on_loading_finished, session_id=session_id)
- def on_target_crashed(event: TargetCrashedEvent, session_id: str | None = None):
+ def on_target_crashed(event: TargetCrashedEvent, session_id: SessionID | None = None):
# Create and track the task
task = asyncio.create_task(self._on_target_crash_cdp(target_id))
self._cdp_event_tasks.add(task)
@@ -165,7 +166,7 @@ class CrashWatchdog(BaseWatchdog):
request_id = event.get('requestId', '')
self._active_requests.pop(request_id, None)
- async def _on_target_crash_cdp(self, target_id: str) -> None:
+ async def _on_target_crash_cdp(self, target_id: TargetID) -> None:
"""Handle target crash detected via CDP."""
# Remove crashed session from pool
if session := self.browser_session._cdp_session_pool.pop(target_id, None):
@@ -187,17 +188,13 @@ class CrashWatchdog(BaseWatchdog):
f'[CrashWatchdog] πŸ’₯ Target crashed, navigating Agent to a new tab: {target_info.get("url", "unknown")}'
)
- # Get tab index
- tab_index = await self.browser_session.get_tab_index(target_id)
-
# Also emit generic browser error
self.event_bus.dispatch(
BrowserErrorEvent(
error_type='TargetCrash',
- message=f'Target crashed: #{tab_index}',
+ message=f'Target crashed: {target_id}',
details={
# 'url': target_url, # TODO: add url to details
- 'tab_index': tab_index,
'target_id': target_id,
},
)
diff --git a/browser_use/browser/default_action_watchdog.py b/browser_use/browser/default_action_watchdog.py
index c7fd0082c..f98ea2933 100644
--- a/browser_use/browser/default_action_watchdog.py
+++ b/browser_use/browser/default_action_watchdog.py
@@ -91,7 +91,8 @@ class DefaultActionWatchdog(BaseWatchdog):
# Check if a new tab was opened
after_target_ids = await self.browser_session._cdp_get_all_pages()
- if len(after_target_ids) > len(initial_target_ids):
+ new_target_ids = set(t['targetId'] for t in after_target_ids) - set(t['targetId'] for t in initial_target_ids)
+ if new_target_ids:
new_tab_msg = 'New tab opened - switching to it'
msg += f' - {new_tab_msg}'
self.logger.info(f'πŸ”— {new_tab_msg}')
@@ -104,8 +105,8 @@ class DefaultActionWatchdog(BaseWatchdog):
# so in multi_act it usually already sends [click_element_by_index(123, new_tab=True), switch_tab(-1)] anyway
from browser_use.browser.events import SwitchTabEvent
- last_tab_index = len(after_target_ids) - 1
- switch_event = await self.event_bus.dispatch(SwitchTabEvent(tab_index=last_tab_index))
+ new_target_id = new_target_ids.pop()
+ switch_event = await self.event_bus.dispatch(SwitchTabEvent(target_id=new_target_id))
await switch_event
return None
@@ -531,7 +532,9 @@ class DefaultActionWatchdog(BaseWatchdog):
raise Exception(f'Failed to click element: {e}')
finally:
# always re-focus back to original top-level page session context in case click opened a new tab/popup/window/dialog/etc.
- await self.browser_session.get_or_create_cdp_session(focus=True)
+ cdp_session = await self.browser_session.get_or_create_cdp_session(focus=True)
+ await cdp_session.cdp_client.send.Target.activateTarget(params={'targetId': cdp_session.target_id})
+ await cdp_session.cdp_client.send.Runtime.runIfWaitingForDebugger(session_id=cdp_session.session_id)
except URLNotAllowedError as e:
raise e
diff --git a/browser_use/browser/downloads_watchdog.py b/browser_use/browser/downloads_watchdog.py
index b88ef485c..380b49116 100644
--- a/browser_use/browser/downloads_watchdog.py
+++ b/browser_use/browser/downloads_watchdog.py
@@ -11,6 +11,7 @@ from urllib.parse import urlparse
import anyio
from bubus import BaseEvent
from cdp_use.cdp.browser import DownloadProgressEvent, DownloadWillBeginEvent
+from cdp_use.cdp.target import SessionID, TargetID
from pydantic import PrivateAttr
from browser_use.browser.events import (
@@ -62,17 +63,16 @@ class DownloadsWatchdog(BaseWatchdog):
async def on_TabCreatedEvent(self, event: TabCreatedEvent) -> None:
"""Monitor new tabs for downloads."""
- # logger.info(f'[DownloadsWatchdog] TabCreatedEvent received for tab {event.tab_index}: {event.url}')
+ # logger.info(f'[DownloadsWatchdog] TabCreatedEvent received for tab {event.target_id[-4:]}: {event.url}')
# Assert downloads path is configured (should always be set by BrowserProfile default)
assert self.browser_session.browser_profile.downloads_path is not None, 'Downloads path must be configured'
- target_id = await self.browser_session.get_target_id_by_tab_index(event.tab_index)
- if target_id:
- # logger.info(f'[DownloadsWatchdog] Found target for tab {event.tab_index}, calling attach_to_target')
- await self.attach_to_target(target_id)
+ if event.target_id:
+ # logger.info(f'[DownloadsWatchdog] Found target for tab {event.target_id}, calling attach_to_target')
+ await self.attach_to_target(event.target_id)
else:
- self.logger.warning(f'[DownloadsWatchdog] No target found for tab {event.tab_index}')
+ self.logger.warning(f'[DownloadsWatchdog] No target found for tab {event.target_id}')
async def on_TabClosedEvent(self, event: TabClosedEvent) -> None:
"""Stop monitoring closed tabs."""
@@ -101,7 +101,7 @@ class DownloadsWatchdog(BaseWatchdog):
async def on_NavigationCompleteEvent(self, event: NavigationCompleteEvent) -> None:
"""Check for PDFs after navigation completes."""
- self.logger.debug(f'[DownloadsWatchdog] NavigationCompleteEvent received for {event.url}, tab_index={event.tab_index}')
+ self.logger.debug(f'[DownloadsWatchdog] NavigationCompleteEvent received for {event.url}, tab #{event.target_id[-4:]}')
# Clear PDF cache for the navigated URL since content may have changed
if event.url in self._pdf_viewer_cache:
@@ -113,8 +113,8 @@ class DownloadsWatchdog(BaseWatchdog):
self.logger.debug('[DownloadsWatchdog] Skipping PDF check - auto-download disabled')
return
- target_id = await self.browser_session.get_target_id_by_tab_index(event.tab_index)
- self.logger.debug(f'[DownloadsWatchdog] Got target_id={target_id} for tab_index={event.tab_index}')
+ target_id = event.target_id
+ self.logger.debug(f'[DownloadsWatchdog] Got target_id={target_id} for tab #{event.target_id[-4:]}')
if target_id:
is_pdf = await self.check_for_pdf_viewer(target_id)
@@ -124,13 +124,13 @@ class DownloadsWatchdog(BaseWatchdog):
if not download_path:
self.logger.warning(f'[DownloadsWatchdog] ⚠️ PDF download failed for {event.url}')
else:
- self.logger.debug(f'[DownloadsWatchdog] Could not get target_id for tab_index={event.tab_index}')
+ self.logger.debug(f'[DownloadsWatchdog] Could not get target_id for tab #{event.target_id[-4:]}')
def _is_auto_download_enabled(self) -> bool:
"""Check if auto-download PDFs is enabled in browser profile."""
return self.browser_session.browser_profile.auto_download_pdfs
- async def attach_to_target(self, target_id: str) -> None:
+ async def attach_to_target(self, target_id: TargetID) -> None:
"""Set up download monitoring for a specific target."""
try:
downloads_path_raw = self.browser_session.browser_profile.downloads_path
@@ -164,7 +164,7 @@ class DownloadsWatchdog(BaseWatchdog):
)
# Register download event handlers
- async def download_will_begin_handler(event: DownloadWillBeginEvent, session_id: str | None):
+ async def download_will_begin_handler(event: DownloadWillBeginEvent, session_id: SessionID | None):
self.logger.info(f'[DownloadsWatchdog] Download will begin: {event}')
# Create and track the task
task = asyncio.create_task(self._handle_cdp_download(event, target_id, session_id))
@@ -172,7 +172,7 @@ class DownloadsWatchdog(BaseWatchdog):
# Remove from set when done
task.add_done_callback(lambda t: self._cdp_event_tasks.discard(t))
- async def download_progress_handler(event: DownloadProgressEvent, session_id: str | None):
+ async def download_progress_handler(event: DownloadProgressEvent, session_id: SessionID | None):
# Check if download is complete
if event.get('state') == 'completed':
file_path = event.get('filePath')
@@ -223,7 +223,7 @@ class DownloadsWatchdog(BaseWatchdog):
except Exception as e:
self.logger.error(f'[DownloadsWatchdog] Error tracking download: {e}')
- async def _handle_cdp_download(self, event: DownloadWillBeginEvent, target_id: str, session_id: str | None) -> None:
+ async def _handle_cdp_download(self, event: DownloadWillBeginEvent, target_id: TargetID, session_id: SessionID | None) -> None:
"""Handle a CDP Page.downloadWillBegin event."""
downloads_dir = Path(
self.browser_session.browser_profile.downloads_path
@@ -502,7 +502,7 @@ class DownloadsWatchdog(BaseWatchdog):
if download_id in self._active_downloads:
del self._active_downloads[download_id]
- async def check_for_pdf_viewer(self, target_id: str) -> bool:
+ async def check_for_pdf_viewer(self, target_id: TargetID) -> bool:
"""Check if the current target is Chrome's built-in PDF viewer.
Returns True if a PDF is detected and should be downloaded.
@@ -618,7 +618,7 @@ class DownloadsWatchdog(BaseWatchdog):
self._pdf_viewer_cache[page_url] = False
return False
- async def trigger_pdf_download(self, target_id: str) -> str | None:
+ async def trigger_pdf_download(self, target_id: TargetID) -> str | None:
"""Trigger download of a PDF from Chrome's PDF viewer.
Returns the download path if successful, None otherwise.
diff --git a/browser_use/browser/events.py b/browser_use/browser/events.py
index 99f2b60e7..bbb812a38 100644
--- a/browser_use/browser/events.py
+++ b/browser_use/browser/events.py
@@ -1,7 +1,7 @@
"""Event definitions for browser communication."""
import inspect
-from typing import Any, Literal
+from typing import Any, Generic, Literal
from bubus import BaseEvent
from bubus.models import T_EventResultType
@@ -9,6 +9,7 @@ from pydantic import BaseModel, Field, field_validator
from browser_use.browser.views import BrowserStateSummary
from browser_use.dom.views import EnhancedDOMTreeNode
+from cdp_use.cdp.target import TargetID
# ============================================================================
# Agent/Controller -> BrowserSession Events (High-level browser actions)
@@ -53,13 +54,12 @@ class ElementSelectedEvent(BaseEvent[T_EventResultType]):
# TODO: add page handle to events
# class PageHandle(share a base with browser.session.CDPSession?):
# url: str
-# tab_index: int
-# target_id: str
+# target_id: TargetID
# @classmethod
-# def from_tab_index(cls, tab_index: int) -> Self:
-# return cls(tab_index=tab_index)
+# def from_target_id(cls, target_id: TargetID) -> Self:
+# return cls(target_id=target_id)
# @classmethod
-# def from_target_id(cls, target_id: str) -> Self:
+# def from_target_id(cls, target_id: TargetID) -> Self:
# return cls(target_id=target_id)
# @classmethod
# def from_url(cls, url: str) -> Self:
@@ -97,7 +97,7 @@ class ClickElementEvent(ElementSelectedEvent[None]):
button: Literal['left', 'right', 'middle'] = 'left'
new_tab: bool = Field(
default=False,
- description='Set True to open any link clicked in a new tab in the background, can use switch_tab(page_id=0) after to focus it',
+ description='Set True to open any link clicked in a new tab in the background, can use switch_tab(tab_id=-1) after to focus it',
)
# click_count: int = 1 # TODO
# expect_download: bool = False # moved to downloads_watchdog.py
@@ -128,7 +128,7 @@ class ScrollEvent(ElementSelectedEvent[None]):
class SwitchTabEvent(BaseEvent[None]):
"""Switch to a different tab."""
- tab_index: int
+ target_id: TargetID | None = Field(default=None, description='None means switch to the most recently opened tab')
event_timeout: float | None = 10.0 # seconds
@@ -136,7 +136,7 @@ class SwitchTabEvent(BaseEvent[None]):
class CloseTabEvent(BaseEvent[None]):
"""Close a tab."""
- tab_index: int
+ target_id: TargetID
event_timeout: float | None = 10.0 # seconds
@@ -287,42 +287,44 @@ class BrowserKillEvent(BaseEvent):
event_timeout: float | None = 30.0 # seconds
-class ExecuteJavaScriptEvent(BaseEvent):
- """Execute JavaScript in page context."""
+# TODO: replace all Runtime.evaluate() calls with this event
+# class ExecuteJavaScriptEvent(BaseEvent):
+# """Execute JavaScript in page context."""
- tab_index: int
- expression: str
- await_promise: bool = True
+# target_id: TargetID
+# expression: str
+# await_promise: bool = True
- event_timeout: float | None = 60.0 # seconds
+# event_timeout: float | None = 60.0 # seconds
+# TODO: add this and use the old BrowserProfile.viewport options to set it
+# class SetViewportEvent(BaseEvent):
+# """Set the viewport size."""
-class SetViewportEvent(BaseEvent):
- """Set the viewport size."""
+# width: int
+# height: int
+# device_scale_factor: float = 1.0
- width: int
- height: int
- device_scale_factor: float = 1.0
+# event_timeout: float | None = 15.0 # seconds
- event_timeout: float | None = 15.0 # seconds
+# Moved to strorage state
+# class SetCookiesEvent(BaseEvent):
+# """Set browser cookies."""
-class SetCookiesEvent(BaseEvent):
- """Set browser cookies."""
+# cookies: list[dict[str, Any]]
- cookies: list[dict[str, Any]]
-
- event_timeout: float | None = (
- 30.0 # only long to support the edge case of restoring a big localStorage / on many origins (has to O(n) visit each origin to restore)
- )
+# event_timeout: float | None = (
+# 30.0 # only long to support the edge case of restoring a big localStorage / on many origins (has to O(n) visit each origin to restore)
+# )
-class GetCookiesEvent(BaseEvent):
- """Get browser cookies."""
+# class GetCookiesEvent(BaseEvent):
+# """Get browser cookies."""
- urls: list[str] | None = None
+# urls: list[str] | None = None
- event_timeout: float | None = 30.0 # seconds
+# event_timeout: float | None = 30.0 # seconds
# ============================================================================
@@ -349,9 +351,8 @@ class BrowserStoppedEvent(BaseEvent):
class TabCreatedEvent(BaseEvent):
"""A new tab was created."""
- tab_index: int
+ target_id: TargetID
url: str
- target_id: str
event_timeout: float | None = 30.0 # seconds
@@ -359,11 +360,10 @@ class TabCreatedEvent(BaseEvent):
class TabClosedEvent(BaseEvent):
"""A tab was closed."""
- tab_index: int
+ target_id: TargetID
# TODO:
- # new_focus_tab_index: int | None = None
- # new_focus_target_id: str | None = None
+ # new_focus_target_id: int | None = None
# new_focus_url: str | None = None
event_timeout: float | None = 10.0 # seconds
@@ -373,14 +373,14 @@ class TabClosedEvent(BaseEvent):
# class TabUpdatedEvent(BaseEvent):
# """Tab information updated (URL changed, etc.)."""
-# tab_index: int
+# target_id: TargetID
# url: str
class AgentFocusChangedEvent(BaseEvent):
"""Agent focus changed to a different tab."""
- tab_index: int
+ target_id: TargetID
url: str
event_timeout: float | None = 10.0 # seconds
@@ -389,7 +389,7 @@ class AgentFocusChangedEvent(BaseEvent):
class TargetCrashedEvent(BaseEvent):
"""A target has crashed."""
- tab_index: int
+ target_id: TargetID
error: str
event_timeout: float | None = 10.0 # seconds
@@ -398,7 +398,7 @@ class TargetCrashedEvent(BaseEvent):
class NavigationStartedEvent(BaseEvent):
"""Navigation started."""
- tab_index: int
+ target_id: TargetID
url: str
event_timeout: float | None = 30.0 # seconds
@@ -407,7 +407,7 @@ class NavigationStartedEvent(BaseEvent):
class NavigationCompleteEvent(BaseEvent):
"""Navigation completed."""
- tab_index: int
+ target_id: TargetID
url: str
status: int | None = None
error_message: str | None = None # Error/timeout message if navigation had issues
@@ -499,7 +499,7 @@ class FileDownloadedEvent(BaseEvent):
class AboutBlankDVDScreensaverShownEvent(BaseEvent):
"""AboutBlankWatchdog has shown DVD screensaver animation on an about:blank tab."""
- tab_index: int
+ target_id: TargetID
error: str | None = None
@@ -510,6 +510,7 @@ class DialogOpenedEvent(BaseEvent):
message: str
url: str
frame_id: str
+ # target_id: TargetID # TODO: add this to avoid needing target_id_from_frame() later
# Note: Model rebuilding for forward references is handled in the importing modules
diff --git a/browser_use/browser/popups_watchdog.py b/browser_use/browser/popups_watchdog.py
index 9411526bf..c55abb3d8 100644
--- a/browser_use/browser/popups_watchdog.py
+++ b/browser_use/browser/popups_watchdog.py
@@ -36,7 +36,7 @@ class PopupsWatchdog(BaseWatchdog):
self.logger.info(f'πŸ“Œ Starting dialog handler setup for target {target_id}')
try:
- cdp_session = await self.browser_session.get_or_create_cdp_session(target_id, focus=False)
+ cdp_session = await self.browser_session.get_or_create_cdp_session(target_id, focus=False) # don't auto-focus new tabs! sometimes we need to open tabs in background
# Set up async handler for JavaScript dialogs - now we can handle them immediately!
async def handle_dialog(event_data, session_id: str | None = None):
@@ -99,7 +99,7 @@ class PopupsWatchdog(BaseWatchdog):
cdp_session = await asyncio.wait_for(self.browser_session.cdp_client_for_frame(event.frame_id), timeout=5.0)
try:
- # delay to look more human
+ # delay to look more human before auto-closing, some popular antibot fingerprint tests check for modals closing too fast
await asyncio.sleep(0.25)
assert self.browser_session._cdp_client_root
# self.browser_session._cdp_client_root.register.Page.javascriptDialogClosed(lambda *args: None)
@@ -110,13 +110,11 @@ class PopupsWatchdog(BaseWatchdog):
),
timeout=5.0,
)
- # CRITICAL: you must activate the target after handling the dialog, otherwise the browser will crash 5 seconds later
- await self.browser_session.agent_focus.cdp_client.send.Target.activateTarget(
- params={'targetId': current_focus_target_id}
- )
+ # CRITICAL: you must re-focus (Target.activateTarget()) after handling the dialog, otherwise the browser will crash ~5 seconds later
+ await self.browser_session.get_or_create_cdp_session(target_id=current_focus_target_id, focus=True)
self.logger.info('βœ… JS dialog popup handled successfully')
- # graveyard:
+ # graveyard of past attempts:
# # new_target = await self.browser_session._cdp_client_root.send.Target.createTarget(params={'url': current_focus_url})
# # self.browser_session.agent_focus = await self.browser_session.get_or_create_cdp_session(target_id=new_target.get('targetId'), new_socket=True, focus=True)
# # raise NotImplementedError('TODO: figure out why this requires a hard refresh and new socket to avoid crashing the entire browser on JS dialogs')
@@ -135,6 +133,6 @@ class PopupsWatchdog(BaseWatchdog):
# raise
# finally:
# self.event_bus.dispatch(AgentFocusChangedEvent(
- # tab_index=0,
+ # target_id=current_focus_target_id,
# url=self.browser_session.agent_focus.url,
# ))
diff --git a/browser_use/browser/security_watchdog.py b/browser_use/browser/security_watchdog.py
index c4140602c..8e5096867 100644
--- a/browser_use/browser/security_watchdog.py
+++ b/browser_use/browser/security_watchdog.py
@@ -58,19 +58,16 @@ class SecurityWatchdog(BaseWatchdog):
BrowserErrorEvent(
error_type='NavigationBlocked',
message=f'Navigation to non-allowed URL: {event.url}',
- details={'url': event.url, 'tab_index': event.tab_index},
+ details={'url': event.url, 'target_id': event.target_id},
)
)
# Close the target that navigated to the disallowed URL
try:
- targets = await self.browser_session._cdp_get_all_pages()
- if 0 <= event.tab_index < len(targets):
- target_id = targets[event.tab_index]['targetId']
- await self.browser_session._cdp_close_page(target_id)
- self.logger.info(f'⛔️ Closed target with non-allowed URL: {event.url}')
+ await self.browser_session._cdp_close_page(event.target_id)
+ self.logger.info(f'⛔️ Closed target with non-allowed URL: {event.url}')
except Exception as e:
- self.logger.error(f'⛔️ Failed to close target with non-allowed URL: {str(e)}')
+ self.logger.error(f'⛔️ Failed to close target with non-allowed URL: {type(e).__name__} {e}')
async def on_TabCreatedEvent(self, event: TabCreatedEvent) -> None:
"""Check if new tab URL is allowed."""
@@ -82,7 +79,7 @@ class SecurityWatchdog(BaseWatchdog):
BrowserErrorEvent(
error_type='TabCreationBlocked',
message=f'Tab created with non-allowed URL: {event.url}',
- details={'url': event.url, 'tab_index': event.tab_index, 'target_id': event.target_id},
+ details={'url': event.url, 'target_id': event.target_id},
)
)
@@ -91,7 +88,7 @@ class SecurityWatchdog(BaseWatchdog):
await self.browser_session._cdp_close_page(event.target_id)
self.logger.info(f'⛔️ Closed new tab with non-allowed URL: {event.url}')
except Exception as e:
- self.logger.error(f'⛔️ Failed to close new tab with non-allowed URL: {str(e)}')
+ self.logger.error(f'⛔️ Failed to close new tab with non-allowed URL: {type(e).__name__} {e}')
def _log_glob_warning(self) -> None:
"""Log a warning about glob patterns in allowed_domains."""
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index c0748defc..3af623ebd 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -8,6 +8,7 @@ import httpx
from bubus import EventBus
from cdp_use import CDPClient
from cdp_use.cdp.network import Cookie
+from cdp_use.cdp.target import TargetID, SessionID
from pydantic import BaseModel, ConfigDict, Field, PrivateAttr
from uuid_extensions import uuid7str
@@ -52,8 +53,8 @@ class CDPSession(BaseModel):
cdp_client: CDPClient
- target_id: str
- session_id: str
+ target_id: TargetID
+ session_id: SessionID
title: str = 'Unknown title'
url: str = 'about:blank'
@@ -64,7 +65,7 @@ class CDPSession(BaseModel):
async def for_target(
cls,
cdp_client: CDPClient,
- target_id: str,
+ target_id: TargetID,
new_socket: bool = False,
cdp_url: str | None = None,
domains: list[str] | None = None,
@@ -120,7 +121,7 @@ class CDPSession(BaseModel):
self.session_id = result['sessionId']
# Use specified domains or default domains
- domains = domains or ['Page', 'DOM', 'DOMSnapshot', 'Accessibility', 'Runtime', 'Inspector', 'Debugger']
+ domains = domains or ['Page', 'DOM', 'DOMSnapshot', 'Accessibility', 'Runtime', 'Inspector']
# Enable all domains in parallel
enable_tasks = []
@@ -138,7 +139,8 @@ class CDPSession(BaseModel):
if any(isinstance(result, Exception) for result in results):
raise RuntimeError(f'Failed to enable requested CDP domain: {results}')
- # disable breakpoints on the page so it doesnt pause on crashes / debugger statements
+ # in case 'Debugger' domain is enabled, disable breakpoints on the page so it doesnt pause on crashes / debugger statements
+ # also covered by Runtime.runIfWaitingForDebugger() calls in get_or_create_cdp_session()
try:
await self.cdp_client.send.Debugger.setSkipAllPauses(params={'skip': True}, session_id=self.session_id)
# if 'Debugger' not in domains:
@@ -164,7 +166,7 @@ class CDPSession(BaseModel):
async def get_tab_info(self) -> TabInfo:
target_info = await self.get_target_info()
return TabInfo(
- page_id=-1, # TODO: get tab order efficiently somehow
+ target_id=target_info['targetId'],
url=target_info['url'],
title=target_info['title'],
)
@@ -407,15 +409,14 @@ class BrowserSession(BaseModel):
return
target_id = None
- tab_index = 0
- # check if the url is already open in a tab somewhere that we haven't interacted with yet, if so, short-circuit and just switch to it
+ # check if the url is already open in a tab somewhere that we're not currently on, if so, short-circuit and just switch to it
targets = await self._cdp_get_all_pages()
for target in targets:
if target.get('url') == event.url and target['targetId'] != self.agent_focus.target_id and not event.new_tab:
target_id = target['targetId']
event.new_tab = False
- # await self.event_bus.dispatch(SwitchTabEvent(tab_index=tab_index))
+ # await self.event_bus.dispatch(SwitchTabEvent(target_id=target_id))
try:
# Find or create target for navigation
@@ -434,8 +435,7 @@ class BrowserSession(BaseModel):
)
if target.get('url') == 'about:blank' and target['targetId'] != current_target_id:
target_id = target['targetId']
- tab_index = idx
- self.logger.info(f'Reusing existing about:blank tab at index {tab_index}')
+ self.logger.info(f'Reusing existing about:blank tab #{target_id[-4:]}')
break
# Create new tab if no reusable one found
@@ -445,31 +445,27 @@ class BrowserSession(BaseModel):
target_id = await self._cdp_create_new_page('about:blank')
self.logger.info(f'[on_NavigateToUrlEvent] Created new page with target_id: {target_id}')
targets = await self._cdp_get_all_pages()
- tab_index = len(targets) - 1
- self.logger.info(f'Created new tab at index {tab_index}')
+
+ self.logger.info(f'Created new tab #{target_id[-4:]}')
# Dispatch TabCreatedEvent for new tab
- await self.event_bus.dispatch(
- TabCreatedEvent(tab_index=tab_index, url='about:blank', target_id=target_id)
- )
+ await self.event_bus.dispatch(TabCreatedEvent(target_id=target_id, url='about:blank'))
except Exception as e:
- self.logger.error(f'[on_NavigateToUrlEvent] Failed to create new tab: {e}')
+ self.logger.error(f'[on_NavigateToUrlEvent] Failed to create new tab: {type(e).__name__}: {e}')
# Fall back to using current tab
target_id = self.agent_focus.target_id
- tab_index = await self.get_tab_index(target_id)
- self.logger.warning(f'[on_NavigateToUrlEvent] Falling back to current tab at index {tab_index}')
+ self.logger.warning(f'[on_NavigateToUrlEvent] Falling back to current tab #{target_id[-4:]}')
else:
# Use current tab
target_id = target_id or self.agent_focus.target_id
# Activate target (bring to foreground)
- tab_index = await self.get_tab_index(target_id)
- await self.event_bus.dispatch(SwitchTabEvent(tab_index=tab_index))
-
- # Update agent focus to the target
- self.agent_focus = await self.get_or_create_cdp_session(target_id)
+ await self.event_bus.dispatch(SwitchTabEvent(target_id=target_id))
+ # which does this for us:
+ # self.agent_focus = await self.get_or_create_cdp_session(target_id)
+ assert self.agent_focus is not None and self.agent_focus.target_id == target_id, 'Agent focus not updated to new target_id after SwitchTabEvent should have switched to it'
# Dispatch navigation started
- await self.event_bus.dispatch(NavigationStartedEvent(tab_index=tab_index, url=event.url))
+ await self.event_bus.dispatch(NavigationStartedEvent(target_id=target_id, url=event.url))
# Navigate to URL
await self.agent_focus.cdp_client.send.Page.navigate(
@@ -485,15 +481,15 @@ class BrowserSession(BaseModel):
await asyncio.sleep(0.5)
# Dispatch navigation complete
- self.logger.debug(f'Dispatching NavigationCompleteEvent for {event.url} (tab_index={tab_index})')
+ self.logger.debug(f'Dispatching NavigationCompleteEvent for {event.url} (tab #{target_id[-4:]})')
await self.event_bus.dispatch(
NavigationCompleteEvent(
- tab_index=tab_index,
+ target_id=target_id,
url=event.url,
status=None, # CDP doesn't provide status directly
)
)
- await self.event_bus.dispatch(AgentFocusChangedEvent(tab_index=tab_index, url=event.url))
+ await self.event_bus.dispatch(AgentFocusChangedEvent(target_id=target_id, url=event.url)) # do not await! AgentFocusChangedEvent calls SwitchTabEvent and it will deadlock, dispatch to enqueue and return
# Note: These should be handled by dedicated watchdogs:
# - Security checks (security_watchdog)
@@ -506,12 +502,12 @@ class BrowserSession(BaseModel):
self.logger.error(f'Navigation failed: {type(e).__name__}: {e}')
await self.event_bus.dispatch(
NavigationCompleteEvent(
- tab_index=tab_index,
+ target_id=target_id,
url=event.url,
error_message=f'{type(e).__name__}: {e}',
)
)
- await self.event_bus.dispatch(AgentFocusChangedEvent(tab_index=tab_index, url=event.url))
+ await self.event_bus.dispatch(AgentFocusChangedEvent(target_id=target_id, url=event.url))
raise
async def on_SwitchTabEvent(self, event: SwitchTabEvent) -> None:
@@ -519,26 +515,29 @@ class BrowserSession(BaseModel):
if not self.agent_focus:
self.logger.warning('Cannot switch tabs - browser not connected')
return
+
+ all_pages = await self._cdp_get_all_pages()
+ if event.target_id is None:
+ # most recently opened page
+ if all_pages:
+ # update the target id to be the id of the most recently opened page, then proceed to switch to it
+ event.target_id = all_pages[-1]['targetId']
+ else:
+ # no pages open at all, create a new one (handles switching to it automatically)
+ self.event_bus.dispatch(NavigateToUrlEvent(url='about:blank', new_tab=True)) # do not await! NavigateToUrlEvent calls SwitchTabEvent and it will deadlock, dispatch to enqueue and return
+ return
- targets = await self._cdp_get_all_pages()
- if -len(targets) <= event.tab_index < len(targets):
- target_id = targets[event.tab_index]['targetId']
-
- # Activate target
- self.agent_focus = await self.get_or_create_cdp_session(target_id=target_id, focus=True)
+ # switch to the target
+ self.agent_focus = await self.get_or_create_cdp_session(target_id=event.target_id, focus=True)
- # Dispatch focus changed event
- target_url = targets[event.tab_index].get('url', '')
- await self.event_bus.dispatch(
- AgentFocusChangedEvent(
- tab_index=event.tab_index,
- url=target_url,
- )
+ # dispatch focus changed event
+ await self.event_bus.dispatch(
+ AgentFocusChangedEvent(
+ target_id=self.agent_focus.target_id,
+ url=self.agent_focus.url,
)
-
- self.logger.info(f'Switched to tab {event.tab_index}: {target_url}')
- else:
- self.logger.warning(f'Invalid tab index: {event.tab_index}')
+ )
+
async def on_TabClosedEvent(self, event: TabClosedEvent) -> None:
"""Handle tab closure - update focus if needed."""
@@ -546,32 +545,15 @@ class BrowserSession(BaseModel):
return
# Get current tab index
- current_tab_index = await self.get_tab_index(self.agent_focus.target_id)
+ current_target_id = self.agent_focus.target_id
# If the closed tab was the current one, find a new target
- if current_tab_index == event.tab_index:
- targets = await self._cdp_get_all_pages()
- if targets:
- # Try to stay at same index or go to previous
- new_index = min(current_tab_index, len(targets) - 1)
- if new_index >= 0:
- # Dispatch focus changed
- await self.event_bus.dispatch(
- AgentFocusChangedEvent(
- tab_index=new_index,
- url=targets[new_index].get('url', ''),
- # target_id=new_target_id,
- )
- )
- self.logger.info(f'Moved focus to tab {new_index} after tab closure')
- else:
- self.agent_focus = None
- else:
- self.agent_focus = None
+ if current_target_id == event.target_id:
+ await self.event_bus.dispatch(SwitchTabEvent(target_id=None))
async def on_AgentFocusChangedEvent(self, event: AgentFocusChangedEvent) -> None:
"""Handle agent focus change - update focus and clear cache."""
- self.logger.debug(f'πŸ”„ AgentFocusChangedEvent received: tab_index={event.tab_index}, url={event.url}')
+ self.logger.debug(f'πŸ”„ AgentFocusChangedEvent received: target_id=...{event.target_id[-4:]} url={event.url}')
# Clear cached DOM state since focus changed
# self.logger.debug('πŸ”„ Clearing DOM cache...')
@@ -584,21 +566,18 @@ class BrowserSession(BaseModel):
self._cached_browser_state_summary = None
self._cached_selector_map.clear()
self.logger.debug('πŸ”„ Cached browser state cleared')
+ all_targets = await self._cdp_get_all_pages(include_chrome=True)
- # Update agent focus if tab_index is provided
- if event.tab_index is not None:
- self.logger.debug(f'πŸ”„ Getting all pages for tab_index={event.tab_index}...')
- targets = await self._cdp_get_all_pages()
- self.logger.debug(f'πŸ”„ Got {len(targets)} targets')
- if 0 <= event.tab_index < len(targets):
- target_id = targets[event.tab_index]['targetId']
- # self.logger.debug(f'πŸ”„ Getting CDP session for target {target_id}...')
- self.agent_focus = await self.get_or_create_cdp_session(target_id, focus=True)
- self.logger.debug(f'πŸ”„ Updated agent focus to tab {event.tab_index} (target {target_id})')
+ # Update agent focus if a specific target_id is provided
+ if event.target_id:
+ self.agent_focus = await self.get_or_create_cdp_session(target_id=event.target_id, focus=True)
+ self.logger.debug(f'πŸ”„ Updated agent focus to tab target_id=...{event.target_id[-4:]}')
+ else:
+ raise RuntimeError('AgentFocusChangedEvent received with no target_id for newly focused tab')
# Test that the browser is responsive by evaluating a simple expression
if self.agent_focus:
- self.logger.debug('πŸ”„ Testing browser responsiveness...')
+ self.logger.debug('πŸ”„ Testing tab responsiveness...')
try:
test_result = await asyncio.wait_for(
self.agent_focus.cdp_client.send.Runtime.evaluate(
@@ -612,7 +591,10 @@ class BrowserSession(BaseModel):
else:
raise Exception('❌ Failed to execute test JS expression with Page.evaluate')
except Exception as e:
- self.logger.error(f'πŸ”„ ❌ Page appears crashed after focus change: {e}')
+ self.logger.error(f'πŸ”„ ❌ Target {self.agent_focus.target_id} seems closed/crashed, switching to fallback page {all_targets[0]}: {type(e).__name__}: {e}')
+ all_pages = (await self._cdp_get_all_pages())
+ last_target_id = all_pages[-1]['targetId'] if all_pages else None
+ self.agent_focus = await self.get_or_create_cdp_session(target_id=last_target_id, focus=True)
raise
# self.logger.debug('πŸ”„ AgentFocusChangedEvent handler completed successfully')
@@ -666,7 +648,7 @@ class BrowserSession(BaseModel):
return self._cdp_client_root
async def get_or_create_cdp_session(
- self, target_id: str | None = None, focus: bool = True, new_socket: bool | None = None
+ self, target_id: TargetID | None = None, focus: bool = True, new_socket: bool | None = None
) -> CDPSession:
"""Get or create a CDP session for a target.
@@ -1025,12 +1007,12 @@ class BrowserSession(BaseModel):
for idx, target in enumerate(page_targets):
target_url = target.get('url', '')
self.logger.debug(f'Dispatching TabCreatedEvent for initial tab {idx}: {target_url}')
- self.event_bus.dispatch(TabCreatedEvent(tab_index=idx, url=target_url, target_id=target['targetId']))
+ self.event_bus.dispatch(TabCreatedEvent(url=target_url, target_id=target['targetId']))
# Dispatch initial focus event
if page_targets:
initial_url = page_targets[0].get('url', '')
- self.event_bus.dispatch(AgentFocusChangedEvent(tab_index=0, url=initial_url))
+ self.event_bus.dispatch(AgentFocusChangedEvent(target_id=page_targets[0]['targetId'], url=initial_url))
self.logger.info(f'Initial agent focus set to tab 0: {initial_url}')
except Exception as e:
@@ -1100,12 +1082,10 @@ class BrowserSession(BaseModel):
title = ''
tab_info = TabInfo(
- page_id=i,
+ target_id=target_id,
url=url,
title=title,
- parent_page_id=None,
- id=target_id, # Use target ID as the unique identifier
- index=i,
+ parent_target_id=None,
)
tabs.append(tab_info)
@@ -1113,21 +1093,6 @@ class BrowserSession(BaseModel):
# ========== ID Lookup Methods ==========
- async def get_tab_index(self, target_id: str) -> int:
- """Get tab index for a target ID."""
- targets = await self._cdp_get_all_pages()
- target_ids = [t['targetId'] for t in targets]
- if target_id in target_ids:
- return target_ids.index(target_id)
- return -1
-
- async def get_target_id_by_tab_index(self, tab_index: int) -> str | None:
- """Get target ID by tab index."""
- target_ids = await self._cdp_get_all_pages()
- if 0 <= tab_index < len(target_ids):
- return target_ids[tab_index]['targetId']
- return None
-
async def get_current_target_info(self) -> TargetInfo | None:
"""Get info about the current active target using CDP."""
if not self.agent_focus or not self.agent_focus.target_id:
@@ -1187,6 +1152,13 @@ class BrowserSession(BaseModel):
async def get_element_by_index(self, index: int) -> EnhancedDOMTreeNode | None:
"""Alias for get_dom_element_by_index for backwards compatibility."""
return await self.get_dom_element_by_index(index)
+
+ def get_target_id_from_tab_id(self, tab_id: str) -> TargetID:
+ """Get the full-length TargetID from the truncated 4-char tab_id."""
+ for session in self._cdp_session_pool.values():
+ if session.target_id[-4:] == tab_id:
+ return session.target_id
+ raise ValueError(f'No TargetID found ending in tab_id=...{tab_id}')
def is_file_input(self, element: Any) -> bool:
"""Check if element is a file input.
@@ -1339,7 +1311,7 @@ class BrowserSession(BaseModel):
)
return result['targetId']
- async def _cdp_close_page(self, target_id: str) -> None:
+ async def _cdp_close_page(self, target_id: TargetID) -> None:
"""Close a page/tab using CDP Target.closeTarget."""
await self.cdp_client.send.Target.closeTarget(params={'targetId': target_id})
@@ -1431,7 +1403,7 @@ class BrowserSession(BaseModel):
'origins': [], # Would need to iterate through origins for localStorage/sessionStorage
}
- async def _cdp_navigate(self, url: str, target_id: str | None = None) -> None:
+ async def _cdp_navigate(self, url: str, target_id: TargetID | None = None) -> None:
"""Navigate to URL using CDP Page.navigate."""
# Use provided target_id or fall back to current_target_id
@@ -1690,7 +1662,7 @@ class BrowserSession(BaseModel):
return all_frames.get(frame_id)
- async def cdp_client_for_target(self, target_id: str) -> CDPSession:
+ async def cdp_client_for_target(self, target_id: TargetID) -> CDPSession:
return await self.get_or_create_cdp_session(target_id, focus=False)
async def cdp_client_for_frame(self, frame_id: str) -> CDPSession:
diff --git a/browser_use/browser/views.py b/browser_use/browser/views.py
index 84045feac..ceb09630a 100644
--- a/browser_use/browser/views.py
+++ b/browser_use/browser/views.py
@@ -2,7 +2,8 @@ from dataclasses import dataclass, field
from typing import Any
from bubus import BaseEvent
-from pydantic import BaseModel
+from cdp_use.cdp.target import TargetID
+from pydantic import AliasChoices, BaseModel, ConfigDict, Field, field_serializer
from browser_use.dom.views import DOMInteractedElement, SerializedDOMState
@@ -16,16 +17,26 @@ PLACEHOLDER_4PX_SCREENSHOT = (
class TabInfo(BaseModel):
"""Represents information about a browser tab"""
+ model_config = ConfigDict(
+ extra='forbid',
+ validate_by_name=True,
+ validate_by_alias=True,
+ populate_by_name=True,
+ )
+
# Original fields
- page_id: int
url: str
title: str
- parent_page_id: int | None = None # parent page that contains this popup or cross-origin iframe
-
- # Additional fields for compatibility with dictionary format
- id: str | None = None # tab ID string like "tab_0"
- index: int | None = None # tab index
-
+ target_id: TargetID = Field(serialization_alias='tab_id', validation_alias=AliasChoices('tab_id', 'target_id'))
+ parent_target_id: TargetID | None = Field(default=None, serialization_alias='parent_tab_id', validation_alias=AliasChoices('parent_tab_id', 'parent_target_id')) # parent page that contains this popup or cross-origin iframe
+
+ @field_serializer('target_id')
+ def serialize_target_id(self, target_id: TargetID, _info: Any) -> str:
+ return target_id[-4:]
+
+ @field_serializer('parent_target_id')
+ def serialize_parent_target_id(self, parent_target_id: TargetID | None, _info: Any) -> str | None:
+ return parent_target_id[-4:] if parent_target_id else None
class PageInfo(BaseModel):
"""Comprehensive page size and scroll information"""
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index 21edf13ad..cfc2b2760 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -127,9 +127,9 @@ class Controller(Generic[Context]):
# Switch to this tab first if it's not the current one
from browser_use.browser.events import SwitchTabEvent
- if browser_session.agent_focus and tab.id != browser_session.agent_focus.target_id:
+ if browser_session.agent_focus and tab.target_id != browser_session.agent_focus.target_id:
try:
- switch_event = browser_session.event_bus.dispatch(SwitchTabEvent(tab_index=i))
+ switch_event = browser_session.event_bus.dispatch(SwitchTabEvent(target_id=tab.target_id))
await switch_event
await switch_event.event_result(raise_if_none=False)
except Exception as e:
@@ -150,9 +150,9 @@ class Controller(Generic[Context]):
# Switch to this tab first
from browser_use.browser.events import SwitchTabEvent
- if browser_session.agent_focus and tab.id != browser_session.agent_focus.target_id:
+ if browser_session.agent_focus and tab.target_id != browser_session.agent_focus.target_id:
try:
- switch_event = browser_session.event_bus.dispatch(SwitchTabEvent(tab_index=i))
+ switch_event = browser_session.event_bus.dispatch(SwitchTabEvent(target_id=tab.target_id))
await switch_event
await switch_event.event_result()
except Exception as e:
@@ -455,8 +455,8 @@ class Controller(Generic[Context]):
event = browser_session.event_bus.dispatch(UploadFileEvent(node=file_input_node, file_path=params.path))
await event
await event.event_result(raise_if_any=True, raise_if_none=False)
- msg = f'πŸ“ Successfully uploaded file to index {params.index}'
- logger.info(msg)
+ msg = f'Successfully uploaded file to index {params.index}'
+ logger.info(f'πŸ“ {msg}')
return ActionResult(
extracted_content=msg,
include_in_memory=True,
@@ -472,28 +472,28 @@ class Controller(Generic[Context]):
async def switch_tab(params: SwitchTabAction, browser_session: BrowserSession):
# Dispatch switch tab event
try:
- event = browser_session.event_bus.dispatch(SwitchTabEvent(tab_index=params.page_id))
+ target_id = browser_session.get_target_id_from_tab_id(params.tab_id)
+ event = browser_session.event_bus.dispatch(SwitchTabEvent(target_id=target_id))
await event
await event.event_result(raise_if_any=True, raise_if_none=False)
- memory = f'Switched to tab #{params.page_id}'
- msg = f'πŸ”„ {memory}'
- logger.info(msg)
+ memory = f'Switched to tab #{params.tab_id}'
+ logger.info(f'πŸ”„ {memory}')
return ActionResult(extracted_content=memory, include_in_memory=True, long_term_memory=memory)
except Exception as e:
- logger.error(f'Failed to switch tab: {e}')
+ logger.error(f'Failed to switch tab: {type(e).__name__}: {e}')
clean_msg = extract_llm_error_message(e)
- return ActionResult(error=f'Failed to switch to tab {params.page_id}: {clean_msg}')
+ return ActionResult(error=f'Failed to switch to tab {params.tab_id}: {clean_msg}')
@self.registry.action('Close an existing tab', param_model=CloseTabAction)
async def close_tab(params: CloseTabAction, browser_session: BrowserSession):
# Dispatch close tab event
try:
- event = browser_session.event_bus.dispatch(CloseTabEvent(tab_index=params.page_id))
+ target_id = browser_session.get_target_id_from_tab_id(params.tab_id)
+ event = browser_session.event_bus.dispatch(CloseTabEvent(target_id=target_id))
await event
await event.event_result(raise_if_any=True, raise_if_none=False)
- memory = f'Closed tab #{params.page_id}'
- msg = f'❌ {memory}'
- logger.info(msg)
+ memory = f'Closed tab # {params.tab_id}'
+ logger.info(f'❌ {memory}')
return ActionResult(
extracted_content=memory,
include_in_memory=True,
@@ -502,7 +502,7 @@ class Controller(Generic[Context]):
except Exception as e:
logger.error(f'Failed to close tab: {e}')
clean_msg = extract_llm_error_message(e)
- return ActionResult(error=f'Failed to close tab {params.page_id}: {clean_msg}')
+ return ActionResult(error=f'Failed to close tab {params.tab_id}: {clean_msg}')
# Content Actions
diff --git a/browser_use/controller/views.py b/browser_use/controller/views.py
index 261bf9043..8db6fbbe0 100644
--- a/browser_use/controller/views.py
+++ b/browser_use/controller/views.py
@@ -21,7 +21,7 @@ class ClickElementAction(BaseModel):
class InputTextAction(BaseModel):
- index: int
+ index: int = Field(ge=0, description='index of the element to input text into, 0 is the page')
text: str
clear_existing: bool = Field(default=True, description='set True to clear existing text, False to append to existing text')
@@ -41,11 +41,11 @@ class StructuredOutputAction(BaseModel, Generic[T]):
class SwitchTabAction(BaseModel):
- page_id: int
+ tab_id: str = Field(min_length=4, max_length=4, description='4 character Tab ID') # last 4 chars of TargetID
class CloseTabAction(BaseModel):
- page_id: int
+ tab_id: str = Field(min_length=4, max_length=4, description='4 character Tab ID') # last 4 chars of TargetID
class ScrollAction(BaseModel):
diff --git a/browser_use/dom/service.py b/browser_use/dom/service.py
index bae957f9c..73590612f 100644
--- a/browser_use/dom/service.py
+++ b/browser_use/dom/service.py
@@ -6,6 +6,7 @@ from typing import TYPE_CHECKING
from cdp_use.cdp.accessibility.commands import GetFullAXTreeReturns
from cdp_use.cdp.accessibility.types import AXNode
from cdp_use.cdp.dom.types import Node
+from cdp_use.cdp.target import TargetID
from browser_use.dom.enhanced_snapshot import (
REQUIRED_COMPUTED_STYLES,
@@ -52,7 +53,7 @@ class DomService:
async def __aexit__(self, exc_type, exc_value, traceback):
pass # no need to cleanup anything, browser_session auto handles cleaning up session cache
- async def _get_targets_for_page(self, target_id: str | None = None) -> CurrentPageTargets:
+ async def _get_targets_for_page(self, target_id: TargetID | None = None) -> CurrentPageTargets:
"""Get the target info for a specific page.
Args:
@@ -122,7 +123,7 @@ class DomService:
)
return enhanced_ax_node
- async def _get_viewport_ratio(self, target_id: str) -> float:
+ async def _get_viewport_ratio(self, target_id: TargetID) -> float:
"""Get viewport dimensions, device pixel ratio, and scroll position using CDP."""
cdp_session = await self.browser_session.get_or_create_cdp_session(target_id=target_id, focus=True)
@@ -256,7 +257,7 @@ class DomService:
# If we reach here, element is visible in main viewport and all containing iframes
return True
- async def _get_ax_tree_for_all_frames(self, target_id: str) -> GetFullAXTreeReturns:
+ async def _get_ax_tree_for_all_frames(self, target_id: TargetID) -> GetFullAXTreeReturns:
"""Recursively collect all frames and merge their accessibility trees into a single array."""
cdp_session = await self.browser_session.get_or_create_cdp_session(target_id=target_id, focus=False)
@@ -293,7 +294,7 @@ class DomService:
return {'nodes': merged_nodes}
- async def _get_all_trees(self, target_id: str) -> TargetAllTrees:
+ async def _get_all_trees(self, target_id: TargetID) -> TargetAllTrees:
cdp_session = await self.browser_session.get_or_create_cdp_session(target_id=target_id, focus=False)
# Wait for the page to be ready first
@@ -397,7 +398,7 @@ class DomService:
async def get_dom_tree(
self,
- target_id: str,
+ target_id: TargetID,
initial_html_frames: list[EnhancedDOMTreeNode] | None = None,
initial_total_frame_offset: DOMRect | None = None,
) -> EnhancedDOMTreeNode:
diff --git a/browser_use/dom/views.py b/browser_use/dom/views.py
index 14d9e7a5f..0f182888f 100644
--- a/browser_use/dom/views.py
+++ b/browser_use/dom/views.py
@@ -8,7 +8,7 @@ from cdp_use.cdp.accessibility.types import AXPropertyName
from cdp_use.cdp.dom.commands import GetDocumentReturns
from cdp_use.cdp.dom.types import ShadowRootType
from cdp_use.cdp.domsnapshot.commands import CaptureSnapshotReturns
-from cdp_use.cdp.target.types import TargetInfo
+from cdp_use.cdp.target.types import SessionID, TargetID, TargetInfo
from uuid_extensions import uuid7str
from browser_use.dom.utils import cap_text_length
@@ -191,7 +191,7 @@ class EnhancedSnapshotNode:
# node_id: int
# backend_node_id: int
# frame_id: str | None
-# target_id: str
+# target_id: TargetID
# node_type: NodeType
# node_name: str
@@ -243,9 +243,9 @@ class EnhancedDOMTreeNode:
"""
# frames
- session_id: str | None
- target_id: str
+ target_id: TargetID
frame_id: str | None
+ session_id: SessionID | None
content_document: 'EnhancedDOMTreeNode | None'
"""
Content document is the document inside a new iframe.
diff --git a/browser_use/llm/tests/test_single_step.py b/browser_use/llm/tests/test_single_step.py
index eec24bfc5..02f45db52 100644
--- a/browser_use/llm/tests/test_single_step.py
+++ b/browser_use/llm/tests/test_single_step.py
@@ -35,7 +35,7 @@ def create_mock_state_message(temp_dir: str):
is_visible=True,
absolute_position=None,
session_id=None,
- target_id='test-target',
+ target_id='ABCD1234ABCD1234ABCD1234ABCD1234ABCD1234',
frame_id=None,
content_document=None,
shadow_root_type=None,
@@ -49,9 +49,9 @@ def create_mock_state_message(temp_dir: str):
# Create selector map
selector_map: DOMSelectorMap = {1: mock_button}
- # Create mock tab info with proper integer page_id
+ # Create mock tab info with proper target_id
mock_tab = TabInfo(
- page_id=1, # Changed to integer
+ target_id='ABCD1234ABCD1234ABCD1234ABCD1234ABCD1234',
url='https://example.com',
title='Test Page',
)
diff --git a/browser_use/mcp/server.py b/browser_use/mcp/server.py
index 2d3711a72..39f39d24a 100644
--- a/browser_use/mcp/server.py
+++ b/browser_use/mcp/server.py
@@ -309,8 +309,8 @@ class BrowserUseServer:
description='Switch to a different tab',
inputSchema={
'type': 'object',
- 'properties': {'tab_index': {'type': 'integer', 'description': 'Index of the tab to switch to'}},
- 'required': ['tab_index'],
+ 'properties': {'tab_id': {'type': 'str', 'description': '4 Character Tab ID of the tab to switch to'}},
+ 'required': ['tab_id'],
},
),
types.Tool(
@@ -318,8 +318,8 @@ class BrowserUseServer:
description='Close a tab',
inputSchema={
'type': 'object',
- 'properties': {'tab_index': {'type': 'integer', 'description': 'Index of the tab to close'}},
- 'required': ['tab_index'],
+ 'properties': {'tab_id': {'type': 'str', 'description': '4 Character Tab ID of the tab to close'}},
+ 'required': ['tab_id'],
},
),
# types.Tool(
@@ -439,10 +439,10 @@ class BrowserUseServer:
return await self._list_tabs()
elif tool_name == 'browser_switch_tab':
- return await self._switch_tab(arguments['tab_index'])
+ return await self._switch_tab(arguments['tab_id'])
elif tool_name == 'browser_close_tab':
- return await self._close_tab(arguments['tab_index'])
+ return await self._close_tab(arguments['tab_id'])
return f'Unknown tool: {tool_name}'
@@ -598,10 +598,7 @@ class BrowserUseServer:
if new_tab:
event = self.browser_session.event_bus.dispatch(NavigateToUrlEvent(url=url, new_tab=True))
await event
- # Get the current tab count to determine the new tab index
- tabs = await self.browser_session.get_tabs()
- tab_index = len(tabs) - 1
- return f'Opened new tab #{tab_index} with URL: {url}'
+ return f'Opened new tab with URL: {url}'
else:
event = self.browser_session.event_bus.dispatch(NavigateToUrlEvent(url=url))
await event
@@ -638,9 +635,7 @@ class BrowserUseServer:
event = self.browser_session.event_bus.dispatch(NavigateToUrlEvent(url=full_url, new_tab=True))
await event
- tabs = await self.browser_session.get_tabs()
- tab_index = len(tabs) - 1
- return f'Clicked element {index} and opened in new tab #{tab_index}'
+ return f'Clicked element {index} and opened in new tab {full_url[:20]}...'
else:
# For non-link elements, just do a normal click
# Opening in new tab without href is not reliably supported
@@ -789,35 +784,36 @@ class BrowserUseServer:
tabs_info = await self.browser_session.get_tabs()
tabs = []
for i, tab in enumerate(tabs_info):
- tabs.append({'index': i, 'url': tab.url, 'title': tab.title or ''})
+ tabs.append({'tab_id': tab.target_id[-4:], 'url': tab.url, 'title': tab.title or ''})
return json.dumps(tabs, indent=2)
- async def _switch_tab(self, tab_index: int) -> str:
+ async def _switch_tab(self, tab_id: str) -> str:
"""Switch to a different tab."""
if not self.browser_session:
return 'Error: No browser session active'
from browser_use.browser.events import SwitchTabEvent
- event = self.browser_session.event_bus.dispatch(SwitchTabEvent(tab_index=tab_index))
+ target_id = self.browser_session.get_target_id_from_tab_id(tab_id)
+ event = self.browser_session.event_bus.dispatch(SwitchTabEvent(target_id=target_id))
await event
state = await self.browser_session.get_browser_state_summary()
- return f'Switched to tab {tab_index}: {state.url}'
+ return f'Switched to tab {tab_id}: {state.url}'
- async def _close_tab(self, tab_index: int) -> str:
+ async def _close_tab(self, tab_id: str) -> str:
"""Close a specific tab."""
if not self.browser_session:
return 'Error: No browser session active'
- tabs = await self.browser_session.get_tabs()
- if 0 <= tab_index < len(tabs):
- url = tabs[tab_index].url
- from browser_use.browser.events import CloseTabEvent
- event = self.browser_session.event_bus.dispatch(CloseTabEvent(tab_index=tab_index))
- await event
- return f'Closed tab {tab_index}: {url}'
- return f'Invalid tab index: {tab_index}'
+ from browser_use.browser.events import CloseTabEvent
+
+ target_id = self.browser_session.get_target_id_from_tab_id(tab_id)
+ event = self.browser_session.event_bus.dispatch(CloseTabEvent(target_id=target_id))
+ await event
+ current_url = await self.browser_session.get_current_page_url()
+ return f'Closed tab # {tab_id}, now on {current_url}'
+
async def run(self):
"""Run the MCP server."""
diff --git a/docs/customize/mcp-server.mdx b/docs/customize/mcp-server.mdx
index 497b6923a..ebfe9c9bf 100644
--- a/docs/customize/mcp-server.mdx
+++ b/docs/customize/mcp-server.mdx
@@ -243,7 +243,7 @@ browser_list_tabs(): string
```json
[
{
- "index": 0,
+ "tab_id": 'AE21',
"url": "https://example.com",
"title": "Page Title"
}
@@ -255,13 +255,13 @@ browser_list_tabs(): string
Switch to a specific tab.
```typescript
-browser_switch_tab(tab_index: number): string
+browser_switch_tab(tab_id: string): string
```
**Parameters:**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
-| `tab_index` | `number` | Yes | Index of tab to switch to |
+| `tab_id` | `string` | Yes | ID of tab to switch to (last 4 characters of TargetID) |
**Returns:** Success message with tab URL
@@ -270,13 +270,13 @@ browser_switch_tab(tab_index: number): string
Close a specific tab.
```typescript
-browser_close_tab(tab_index: number): string
+browser_close_tab(tab_id: string): string
```
**Parameters:**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
-| `tab_index` | `number` | Yes | Tab to close |
+| `tab_id` | `string` | Yes | ID of the Tab to close (last 4 characters of TargetID) |
**Returns:** Success message with closed tab URL
diff --git a/tests/ci/test_browser_session_tab_management.py b/tests/ci/test_browser_session_tab_management.py
index 5619bccd4..108b90754 100644
--- a/tests/ci/test_browser_session_tab_management.py
+++ b/tests/ci/test_browser_session_tab_management.py
@@ -113,25 +113,9 @@ class TestTabManagement:
return result
async def _reset_tab_state(self, browser_session: BrowserSession, base_url: str):
- # Ensure browser session is started and watchdogs are initialized
- if not browser_session._browser_context:
- await browser_session.start()
-
- # close all existing tabs
- if browser_session._browser_context:
- for page in browser_session._browser_context.pages:
- await page.close()
-
- await asyncio.sleep(0.5)
-
- # get/create a new tab - this will trigger the new event-driven page creation
- initial_tab = await browser_session.get_current_page()
-
- assert initial_tab is not None
- assert browser_session.page is not None
- assert browser_session.page.url == initial_tab.url
- # page may be None until actual user interaction occurs
- return initial_tab
+ # await browser_session.event_bus.dispatch(CloseTabEvent(target_id=browser_session.agent_focus.target_id))
+ # TODO: close all tabs using events + create new tab + focus it
+ pass
# Tab management tests
@@ -216,16 +200,17 @@ class TestTabManagement:
assert current_tab.url == second_tab.url == f'{base_url}/page2' == browser_session.page.url
# Find the correct tab index for the first tab (page1)
- first_tab_index = None
+ first_tab_id = None
for i, tab in enumerate(browser_session.tabs):
if f'{base_url}/page1' in tab.url:
- first_tab_index = i
+ first_tab_id = tab.target_id[-4:]
break
- assert first_tab_index is not None, f'Could not find tab with page1 URL in {[p.url for p in browser_session.tabs]}'
+ assert first_tab_id is not None, f'Could not find tab with page1 URL in {[p.url for p in browser_session.tabs]}'
# Switch agent back to the first tab using correct index
- await browser_session.switch_to_tab(first_tab_index)
+ from browser_use.browser.events import SwitchTabEvent
+ await browser_session.event_bus.dispatch(SwitchTabEvent(target_id=first_tab_id))
await asyncio.sleep(0.5)
# assert agent focus is on first tab
@@ -233,16 +218,16 @@ class TestTabManagement:
assert f'{base_url}/page1' in current_tab.url == browser_session.page.url
# Find the correct tab index for the second tab (page2)
- second_tab_index = None
+ second_tab_id = None
for i, tab in enumerate(browser_session.tabs):
if f'{base_url}/page2' in tab.url:
- second_tab_index = i
+ second_tab_id = tab.target_id[-4:]
break
- assert second_tab_index is not None, f'Could not find tab with page2 URL in {[p.url for p in browser_session.tabs]}'
+ assert second_tab_id is not None, f'Could not find tab with page2 URL in {[p.url for p in browser_session.tabs]}'
# round-trip, switch agent back to second tab using correct index
- await browser_session.switch_to_tab(second_tab_index)
+ await browser_session.event_bus.dispatch(SwitchTabEvent(target_id=second_tab_id))
await asyncio.sleep(0.5)
# assert agent focus is back on second tab
@@ -377,7 +362,7 @@ class TestEventDrivenTabOperations:
await browser_session.create_new_tab(f'{base_url}/page3')
# Switch to tab 0 via direct event
- switch_event = browser_session.event_bus.dispatch(SwitchTabEvent(tab_index=0))
+ switch_event = browser_session.event_bus.dispatch(SwitchTabEvent(target_id=browser_session.tabs[0].target_id))
await switch_event
# Verify the switch worked
@@ -385,7 +370,7 @@ class TestEventDrivenTabOperations:
assert f'{base_url}/page1' in current_url
# Switch to tab 2 via direct event
- switch_event = browser_session.event_bus.dispatch(SwitchTabEvent(tab_index=2))
+ switch_event = browser_session.event_bus.dispatch(SwitchTabEvent(target_id=browser_session.tabs[2].target_id))
await switch_event
# Verify the switch worked
@@ -404,7 +389,7 @@ class TestEventDrivenTabOperations:
assert initial_tab_count == 2
# Close tab 1 via direct event
- close_event = browser_session.event_bus.dispatch(CloseTabEvent(tab_index=1))
+ close_event = browser_session.event_bus.dispatch(CloseTabEvent(target_id=browser_session.tabs[1].target_id))
await close_event
# Verify tab was closed
@@ -414,7 +399,7 @@ class TestEventDrivenTabOperations:
event_history = list(browser_session.event_bus.event_history.values())
closed_events = [e for e in event_history if isinstance(e, TabClosedEvent)]
assert len(closed_events) >= 1
- assert closed_events[-1].tab_index == 1
+ assert closed_events[-1].target_id == browser_session.tabs[1].target_id
async def test_concurrent_tab_operations_via_events(self, browser_session, base_url):
"""Test concurrent tab operations via event system."""
@@ -434,8 +419,8 @@ class TestEventDrivenTabOperations:
assert len(browser_session.tabs) >= 3
# Switch between tabs concurrently (this should be serialized)
- switch_event1 = browser_session.event_bus.dispatch(SwitchTabEvent(tab_index=0))
- switch_event2 = browser_session.event_bus.dispatch(SwitchTabEvent(tab_index=1))
+ switch_event1 = browser_session.event_bus.dispatch(SwitchTabEvent(target_id=browser_session.tabs[0].target_id))
+ switch_event2 = browser_session.event_bus.dispatch(SwitchTabEvent(target_id=browser_session.tabs[1].target_id))
await asyncio.gather(switch_event1, switch_event2)
diff --git a/tests/ci/test_browser_watchdog_aboutblank.py b/tests/ci/test_browser_watchdog_aboutblank.py
index 5900c8d87..a5905498d 100644
--- a/tests/ci/test_browser_watchdog_aboutblank.py
+++ b/tests/ci/test_browser_watchdog_aboutblank.py
@@ -200,18 +200,18 @@ async def test_aboutblank_watchdog_javascript_execution():
# Get the page and verify animation
# Get tab info instead of page
tabs1 = await session.get_tabs()
- tab1 = tabs1[dvd_event1.tab_index] if dvd_event1.tab_index < len(tabs1) else None
- assert tab1 is not None, f'Could not find tab at index {dvd_event1.tab_index}'
+ tab1 = tabs1[dvd_event1.target_id] if dvd_event1.target_id < len(tabs1) else None
+ assert tab1 is not None, f'Could not find tab at index {dvd_event1.target_id}'
# Verify the animation was created
# Note: We can't directly evaluate on the page without accessing internal APIs
# The test should verify through events instead
- assert dvd_event1.tab_index >= 0, 'DVD screensaver event should have valid tab index'
+ assert dvd_event1.target_id >= 0, 'DVD screensaver event should have valid tab index'
# Test 2: Close the tab and verify watchdog creates new about:blank tab with animation
from browser_use.browser.events import CloseTabEvent
- event = session.event_bus.dispatch(CloseTabEvent(tab_index=dvd_event1.tab_index))
+ event = session.event_bus.dispatch(CloseTabEvent(tab_id=dvd_event1.target_id))
await event
# Wait for new about:blank tab to be created and animation shown
@@ -221,13 +221,13 @@ async def test_aboutblank_watchdog_javascript_execution():
# Get the new page
# Get tab info instead of page
tabs2 = await session.get_tabs()
- tab2 = tabs2[dvd_event2.tab_index] if dvd_event2.tab_index < len(tabs2) else None
- assert tab2 is not None, f'Could not find tab at index {dvd_event2.tab_index}'
+ tab2 = tabs2[dvd_event2.target_id] if dvd_event2.target_id < len(tabs2) else None
+ assert tab2 is not None, f'Could not find tab at index {dvd_event2.target_id}'
assert CrashWatchdog._is_new_tab_page(tab2.url), f'Auto-created tab should be a new tab page, but got: {tab2.url}'
# Verify animation on the new tab through events
# Note: We can't directly evaluate on the page without accessing internal APIs
- assert dvd_event2.tab_index >= 0, 'Second DVD screensaver event should have valid tab index'
+ assert dvd_event2.target_id >= 0, 'Second DVD screensaver event should have valid tab index'
# Verify no JavaScript errors occurred (particularly arguments.callee)
console_errors = []
diff --git a/tests/ci/test_browser_watchdog_security.py b/tests/ci/test_browser_watchdog_security.py
index 49c8ad364..bc2d2c78f 100644
--- a/tests/ci/test_browser_watchdog_security.py
+++ b/tests/ci/test_browser_watchdog_security.py
@@ -42,7 +42,7 @@ async def test_navigation_tab_created_events():
# Wait for first TabCreatedEvent
first_event: TabCreatedEvent = cast(TabCreatedEvent, await session.event_bus.expect(TabCreatedEvent, timeout=3.0))
# The first event might be for about:blank or the target URL depending on timing
- assert first_event.tab_index >= 0
+ assert first_event.target_id >= 0
assert isinstance(first_event.url, str)
# Create second tab - should emit another TabCreatedEvent
@@ -50,15 +50,15 @@ async def test_navigation_tab_created_events():
# Wait for second TabCreatedEvent
second_event: TabCreatedEvent = cast(TabCreatedEvent, await session.event_bus.expect(TabCreatedEvent, timeout=3.0))
- assert second_event.tab_index >= 0
+ assert second_event.target_id >= 0
assert isinstance(second_event.url, str)
# Verify we have at least 2 TabCreatedEvents
assert len(tab_created_events) >= 2, f'Expected at least 2 TabCreatedEvents, got {len(tab_created_events)}'
# Verify the events have different tab indices (unless they're reusing the same tab)
- unique_tab_indexes = {event.tab_index for event in tab_created_events}
- assert len(unique_tab_indexes) >= 2, 'Should have at least two unique tab indices'
+ unique_tab_ides = {event.tab_id for event in tab_created_events}
+ assert len(unique_tab_ides) >= 2, 'Should have at least two unique tab indices'
finally:
# Stop browser
@@ -134,7 +134,7 @@ async def test_navigation_watchdog_agent_focus_tracking():
assert nav_watchdog is not None
# Initial tab should be tab 0
- assert nav_watchdog.agent_tab_index == 0
+ assert nav_watchdog.agent_tab_id == 0
# Create a new tab
session.event_bus.dispatch(NavigateToUrlEvent(url='data:text/html,<h1>New Tab</h1>', new_tab=True))
@@ -147,7 +147,7 @@ async def test_navigation_watchdog_agent_focus_tracking():
await asyncio.sleep(0.2)
# The agent focus should be on a tab index > 0
- assert nav_watchdog.agent_tab_index > 0
+ assert nav_watchdog.agent_tab_id > 0
finally:
# Stop browser
diff --git a/tests/ci/test_controller.py b/tests/ci/test_controller.py
index a84f4f7d3..5177e324a 100644
--- a/tests/ci/test_controller.py
+++ b/tests/ci/test_controller.py
@@ -317,7 +317,7 @@ class TestControllerIntegration:
assert urls[1] in page.url
# Switch back to first tab
- switch_tab_action = {'switch_tab': SwitchTabAction(page_id=0)}
+ switch_tab_action = {'switch_tab': SwitchTabAction(tab_id=0)}
class SwitchTabActionModel(ActionModel):
switch_tab: SwitchTabAction | None = None
@@ -329,7 +329,7 @@ class TestControllerIntegration:
assert urls[0] in page.url
# Close the second tab
- close_tab_action = {'close_tab': CloseTabAction(page_id=1)}
+ close_tab_action = {'close_tab': CloseTabAction(tab_id=1)}
class CloseTabActionModel(ActionModel):
close_tab: CloseTabAction | None = None
diff --git a/tests/ci/test_gif_filtering.py b/tests/ci/test_gif_filtering.py
index ecb6ab6dd..7ed07eaca 100644
--- a/tests/ci/test_gif_filtering.py
+++ b/tests/ci/test_gif_filtering.py
@@ -79,7 +79,7 @@ async def test_gif_filters_out_placeholder_screenshots(test_dir):
screenshot_path=None, # Placeholder doesn't have a file path
url='about:blank',
title='New Tab',
- tabs=[TabInfo(page_id=1, url='about:blank', title='New Tab')],
+ tabs=[TabInfo(target_id=1, url='about:blank', title='New Tab')],
interacted_element=[None],
),
)
@@ -99,7 +99,7 @@ async def test_gif_filters_out_placeholder_screenshots(test_dir):
screenshot_path=real_screenshot_1_path,
url='https://example.com',
title='Example',
- tabs=[TabInfo(page_id=1, url='https://example.com', title='Example')],
+ tabs=[TabInfo(target_id=1, url='https://example.com', title='Example')],
interacted_element=[None],
),
)
@@ -119,7 +119,7 @@ async def test_gif_filters_out_placeholder_screenshots(test_dir):
screenshot_path=None, # Placeholder doesn't have a file path
url='about:blank',
title='New Tab',
- tabs=[TabInfo(page_id=2, url='about:blank', title='New Tab')],
+ tabs=[TabInfo(target_id=2, url='about:blank', title='New Tab')],
interacted_element=[None],
),
)
@@ -139,7 +139,7 @@ async def test_gif_filters_out_placeholder_screenshots(test_dir):
screenshot_path=real_screenshot_2_path,
url='https://example.com/page2',
title='Page 2',
- tabs=[TabInfo(page_id=1, url='https://example.com/page2', title='Page 2')],
+ tabs=[TabInfo(target_id=1, url='https://example.com/page2', title='Page 2')],
interacted_element=[None],
),
)
@@ -206,7 +206,7 @@ async def test_gif_handles_all_placeholders(test_dir):
screenshot_path=None, # Placeholder doesn't have a file path
url='about:blank',
title='New Tab',
- tabs=[TabInfo(page_id=1, url='about:blank', title='New Tab')],
+ tabs=[TabInfo(target_id=1, url='about:blank', title='New Tab')],
interacted_element=[None],
),
)
diff --git a/tests/ci/test_navigation_events.py b/tests/ci/test_navigation_events.py
index 19c15f1f3..27c79c2e2 100644
--- a/tests/ci/test_navigation_events.py
+++ b/tests/ci/test_navigation_events.py
@@ -58,12 +58,12 @@ async def test_navigation_events_fast_page_load(httpserver):
assert len(navigation_started_events) >= 1, 'Should have NavigationStartedEvent'
nav_started = navigation_started_events[-1]
assert nav_started.url == fast_url
- assert nav_started.tab_index >= 0
+ assert nav_started.tab_id >= 0
# Verify NavigationCompleteEvent was emitted with success
assert len(navigation_complete_events) >= 1, 'Should have NavigationCompleteEvent'
assert nav_complete.url == fast_url
- assert nav_complete.tab_index >= 0
+ assert nav_complete.target_id >= 0
assert nav_complete.status == 200, 'Should have successful HTTP status'
assert nav_complete.error_message is None, 'Should have no error message'
assert nav_complete.loading_status is None, 'Should have no loading status issues'
diff --git a/tests/ci/test_sequential_agents_simple.py b/tests/ci/test_sequential_agents_simple.py
index 3e89c62a2..90b3341dd 100644
--- a/tests/ci/test_sequential_agents_simple.py
+++ b/tests/ci/test_sequential_agents_simple.py
@@ -202,7 +202,7 @@ class TestSequentialAgentsSimple:
"memory": "Need to switch to tab 0",
"next_goal": "Switch to tab 0",
"action": [
- {"switch_tab": {"page_id": 0}}
+ {"switch_tab": {"tab_id": 0}}
]
}"""
]