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
working events for launch and navigate
Nick Sweeting93d6fe209bf1
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex dc2eca1f4..a1d9bca6c 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -361,16 +361,9 @@ class Agent(Generic[Context, AgentStructuredOutput]):browser_profile = browser_profile or DEFAULT_BROWSER_PROFILEif browser_session:- # Always copy sessions that are passed in to avoid agents overwriting each other's page and page by accident- # The model_copy() method now handles copying all necessary fields and setting up ownership- if browser_session._local_browser_watchdog and browser_session._local_browser_watchdog._owns_browser_resources:- self.browser_session = browser_session- else:- # TODO: Only warn when multiple agents are running in parallel, not sequentially- # self.logger.warning(- # '⚠️ Attempting to use multiple Agents with the same BrowserSession! This is not supported yet and will likely lead to strange behavior, use separate BrowserSessions for each Agent.'- # )- self.browser_session = browser_session.model_copy()+ # Use the browser session directly without copying+ # This ensures the CDP client and watchdogs are properly accessible+ self.browser_session = browser_session# Browser session was provided externally, don't own itself._owns_browser_session = Falseelse:diff --git a/browser_use/browser/aboutblank_watchdog.py b/browser_use/browser/aboutblank_watchdog.pyindex 59f8da81e..8dd7c6924 100644--- a/browser_use/browser/aboutblank_watchdog.py+++ b/browser_use/browser/aboutblank_watchdog.py@@ -53,11 +53,9 @@ class AboutBlankWatchdog(BaseWatchdog):"""Check tabs when a new tab is created."""# logger.debug(f'[AboutBlankWatchdog] ➕ New tab created: {event.url}')- # If a new tab target was created, show DVD screensaver on it- if CrashWatchdog._is_new_tab_page(event.url):+ # If an about:blank tab was created, show DVD screensaver on all about:blank tabs+ if event.url == 'about:blank':await self._show_dvd_screensaver_on_about_blank_tabs()- else:- await self._check_and_ensure_about_blank_tab()async def on_TabClosedEvent(self, event: TabClosedEvent) -> None:"""Check tabs when a tab is closed and proactively create about:blank if needed."""@@ -89,23 +87,29 @@ class AboutBlankWatchdog(BaseWatchdog):async def _check_and_ensure_about_blank_tab(self) -> None:"""Check current tabs and ensure exactly one about:blank tab with animation exists."""try:- # Use existing helper to get all tabs info with titles- tabs_info = await self.browser_session.get_tabs_info()+ # For quick checks, just get page targets without titles to reduce noise+ page_targets = await self.browser_session._cdp_get_all_pages()++ # Only get full tabs info if we actually need to check titles+ tabs_info = None- # Only look for tabs that have our animation (check by title)+ # For AboutBlankWatchdog, we only care about tab count not titles+ # Only get full tabs info if we actually have animation tabs to check+ if len(page_targets) == 0:+ tabs_info = []+ else:+ # Skip the expensive get_tabs_info call - we just need tab count+ tabs_info = None++ # We don't need to track animation tabs anymore since we're only ensuring+ # that there's at least one tab openanimation_tabs = []- browser_session_id = str(self.browser_session.id)[-4:]- expected_title = f'Starting agent {browser_session_id}...'- for tab in tabs_info:- if CrashWatchdog._is_new_tab_page(tab.url) and tab.title == expected_title:- animation_tabs.append(tab)-- # logger.debug(f'[AboutBlankWatchdog] Found {len(animation_tabs)} animation tabs out of {len(tabs_info)} total tabs')+ # logger.debug(f'[AboutBlankWatchdog] Found {len(animation_tabs)} animation tabs out of {len(page_targets)} total tabs')# If no animation tabs exist, create one only if there are no tabs at allif not animation_tabs:- if len(tabs_info) == 0:+ if len(page_targets) == 0:# Only create a new tab if there are no tabs at all# logger.info('[AboutBlankWatchdog] No tabs exist, creating new about:blank DVD screensaver tab')navigate_event = self.event_bus.dispatch(NavigateToUrlEvent(url='about:blank', new_tab=True))@@ -127,26 +131,18 @@ class AboutBlankWatchdog(BaseWatchdog):self.logger.error(f'[AboutBlankWatchdog] Error ensuring about:blank tab: {e}')async def _show_dvd_screensaver_on_about_blank_tabs(self) -> None:- """Show DVD screensaver on all new tab pages."""+ """Show DVD screensaver on all about:blank pages only."""try:- # Use existing helper to get all tabs- tabs_info = await self.browser_session.get_tabs_info()+ # Get just the page targets without expensive title fetching+ page_targets = await self.browser_session._cdp_get_all_pages()browser_session_id = str(self.browser_session.id)[-4:]- for tab in tabs_info:- if CrashWatchdog._is_new_tab_page(tab.url):- target_id = tab.target_id- # If it's a chrome:// new tab target, redirect to about:blank to avoid CSP issues- if tab.url.startswith('chrome://'):- # Navigate using CDP- session = await self.browser_session.cdp_client.send.Target.attachToTarget(- params={'targetId': target_id, 'flatten': True}- )- session_id = session['sessionId']- await self.browser_session.cdp_client.send.Page.navigate(- params={'url': 'about:blank'}, session_id=session_id- )- await self.browser_session.cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})+ for page_target in page_targets:+ target_id = page_target['targetId']+ url = page_target['url']++ # Only target about:blank pages specifically+ if url == 'about:blank':await self._show_dvd_screensaver_loading_animation_cdp(target_id, browser_session_id)except Exception as e:@@ -167,9 +163,16 @@ class AboutBlankWatchdog(BaseWatchdog):# Inject the DVD screensaver scriptscript = f"""(function(browser_session_label) {{+ // Check if animation is already running using window property+ if (window.__dvdAnimationRunning) {{+ return; // Already running, don't add another+ }}+ window.__dvdAnimationRunning = true;+// Ensure document.body exists before proceedingif (!document.body) {{// Try again after DOM is ready+ window.__dvdAnimationRunning = false; // Reset flag to retryif (document.readyState === 'loading') {{document.addEventListener('DOMContentLoaded', function() {{ arguments.callee(browser_session_label); }});}}@@ -177,9 +180,6 @@ class AboutBlankWatchdog(BaseWatchdog):}}const animated_title = `Starting agent ${{browser_session_label}}...`;- if (document.title === animated_title) {{- return; // already run on this tab, dont run again- }}document.title = animated_title;// Create the main overlaydiff --git a/browser_use/browser/crash_watchdog.py b/browser_use/browser/crash_watchdog.pyindex 1ff79a286..1cd838bf1 100644--- a/browser_use/browser/crash_watchdog.py+++ b/browser_use/browser/crash_watchdog.py@@ -46,13 +46,14 @@ class CrashWatchdog(BaseWatchdog):# Configurationnetwork_timeout_seconds: float = Field(default=10.0)- check_interval_seconds: float = Field(default=10.0)+ check_interval_seconds: float = Field(default=30.0) # Reduced frequency to reduce noise# Private state_active_requests: dict[str, NetworkRequestTracker] = PrivateAttr(default_factory=dict)_monitoring_task: asyncio.Task | None = PrivateAttr(default=None)_cdp_sessions: dict[str, str] = PrivateAttr(default_factory=dict) # target_id -> session_id_last_responsive_checks: dict[str, float] = PrivateAttr(default_factory=dict) # target_url -> timestamp+ _cdp_event_tasks: set[asyncio.Task] = PrivateAttr(default_factory=set) # Track CDP event handler tasksasync def on_BrowserConnectedEvent(self, event: BrowserConnectedEvent) -> None:"""Start monitoring when browser is connected."""@@ -83,7 +84,11 @@ class CrashWatchdog(BaseWatchdog):# Set up network event handlersdef on_request_will_be_sent(event):- asyncio.create_task(self._on_request_cdp(event))+ # Create and track the task+ task = asyncio.create_task(self._on_request_cdp(event))+ self._cdp_event_tasks.add(task)+ # Remove from set when done+ task.add_done_callback(lambda t: self._cdp_event_tasks.discard(t))def on_response_received(event):self._on_response_cdp(event)@@ -105,7 +110,11 @@ class CrashWatchdog(BaseWatchdog):# Set up crash handlerdef on_target_crashed(event):- asyncio.create_task(self._on_target_crash_cdp(target_id))+ # Create and track the task+ task = asyncio.create_task(self._on_target_crash_cdp(target_id))+ self._cdp_event_tasks.add(task)+ # Remove from set when done+ task.add_done_callback(lambda t: self._cdp_event_tasks.discard(t))cdp_client.on('Inspector.targetCrashed', on_target_crashed, session_id=session_id)@@ -236,6 +245,15 @@ class CrashWatchdog(BaseWatchdog):passself.logger.debug('[CrashWatchdog] Monitoring loop stopped')+ # Cancel all CDP event handler tasks+ for task in list(self._cdp_event_tasks):+ if not task.done():+ task.cancel()+ # Wait for all tasks to complete cancellation+ if self._cdp_event_tasks:+ await asyncio.gather(*self._cdp_event_tasks, return_exceptions=True)+ self._cdp_event_tasks.clear()+# Clean up CDP sessionsif self._cdp_sessions:cdp_client = self.browser_session.cdp_clientdiff --git a/browser_use/browser/dom_watchdog.py b/browser_use/browser/dom_watchdog.pyindex 7eff986ed..a07bcf671 100644--- a/browser_use/browser/dom_watchdog.py+++ b/browser_use/browser/dom_watchdog.py@@ -63,6 +63,11 @@ class DOMWatchdog(BaseWatchdog):# Check if this is a new tab or chrome:// target early for optimizationis_empty_page = is_new_tab_page(page_url) or page_url.startswith('chrome://')++ # Get tabs info once at the beginning for all paths+ self.logger.debug('Getting tabs info...')+ tabs_info = await self.browser_session.get_tabs_info()+ self.logger.debug(f'Got {len(tabs_info)} tabs')try:# Fast path for empty pages@@ -72,9 +77,6 @@ class DOMWatchdog(BaseWatchdog):# Create minimal DOM statecontent = SerializedDOMState(_root=None, selector_map={})- # Get tabs info- tabs_info = await self.browser_session.get_tabs_info()-# Skip screenshot for empty pagesscreenshot_b64 = None@@ -116,7 +118,7 @@ class DOMWatchdog(BaseWatchdog):if self.browser_session._cached_browser_state_summaryelse None)-+try:# Call the DOM building method directlycontent = await self._build_dom_tree(previous_state)@@ -143,13 +145,15 @@ class DOMWatchdog(BaseWatchdog):except Exception as e:self.logger.warning(f'Screenshot failed: {e}')- # Get target info and tabs- tabs_info = await self.browser_session.get_tabs_info()+ # Tabs info already fetched at the beginning# Get target title safelytry:+ self.logger.debug('Getting page title...')title = await asyncio.wait_for(self.browser_session.get_current_page_title(), timeout=2.0)- except Exception:+ self.logger.debug(f'Got title: {title}')+ except Exception as e:+ self.logger.debug(f'Failed to get title: {e}')title = 'Page'# TODO: Get proper target info from CDP@@ -187,6 +191,7 @@ class DOMWatchdog(BaseWatchdog):# Cache the stateself.browser_session._cached_browser_state_summary = browser_state+ self.logger.debug('Returning browser state from on_BrowserStateRequestEvent')return browser_stateexcept Exception as e:@@ -219,10 +224,10 @@ class DOMWatchdog(BaseWatchdog):async def _build_dom_tree(self, previous_state: SerializedDOMState | None = None) -> SerializedDOMState:"""Internal method to build and serialize DOM tree.-+This is the actual implementation that does the work, called by bothon_BrowserStateRequestEvent.-+Returns:SerializedDOMState with serialized DOM and selector map"""diff --git a/browser_use/browser/downloads_watchdog.py b/browser_use/browser/downloads_watchdog.pyindex 4f1940280..1881f6088 100644--- a/browser_use/browser/downloads_watchdog.py+++ b/browser_use/browser/downloads_watchdog.py@@ -6,7 +6,6 @@ import osfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, ClassVarfrom urllib.parse import urlparse-from weakref import WeakSetimport anyiofrom bubus import BaseEvent@@ -14,6 +13,7 @@ from pydantic import PrivateAttrfrom browser_use.browser.events import (BrowserLaunchEvent,+ BrowserStoppedEvent,FileDownloadedEvent,NavigationCompleteEvent,TabClosedEvent,@@ -31,6 +31,7 @@ class DownloadsWatchdog(BaseWatchdog):# Events this watchdog listens to (for documentation)LISTENS_TO: ClassVar[list[type[BaseEvent[Any]]]] = [BrowserLaunchEvent,+ BrowserStoppedEvent,TabCreatedEvent,TabClosedEvent,NavigationCompleteEvent,@@ -42,13 +43,12 @@ class DownloadsWatchdog(BaseWatchdog):]# Private state- _targets_with_listeners: set[str] = PrivateAttr(- default_factory=set- ) # Track targets that already have download listeners+ _targets_with_listeners: set[str] = PrivateAttr(default_factory=set) # Track targets that already have download listeners_active_downloads: dict[str, Any] = PrivateAttr(default_factory=dict)_pdf_viewer_cache: dict[str, bool] = PrivateAttr(default_factory=dict) # Cache PDF viewer status by target URL_download_cdp_session_setup: bool = PrivateAttr(default=False) # Track if CDP session is set up_download_cdp_session: Any = PrivateAttr(default=None) # Store CDP session reference+ _cdp_event_tasks: set[asyncio.Task] = PrivateAttr(default_factory=set) # Track CDP event handler tasksasync def on_BrowserLaunchEvent(self, event: BrowserLaunchEvent) -> None:self.logger.info(f'[DownloadsWatchdog] Received BrowserLaunchEvent, EventBus ID: {id(self.event_bus)}')@@ -76,6 +76,32 @@ class DownloadsWatchdog(BaseWatchdog):"""Stop monitoring closed tabs."""pass # No cleanup needed, browser context handles target lifecycle+ async def on_BrowserStoppedEvent(self, event: BrowserStoppedEvent) -> None:+ """Clean up when browser stops."""+ # Cancel all CDP event handler tasks+ for task in list(self._cdp_event_tasks):+ if not task.done():+ task.cancel()+ # Wait for all tasks to complete cancellation+ if self._cdp_event_tasks:+ await asyncio.gather(*self._cdp_event_tasks, return_exceptions=True)+ self._cdp_event_tasks.clear()++ # Clean up CDP session+ if self._download_cdp_session:+ try:+ cdp_client = self.browser_session.cdp_client+ await cdp_client.send.Target.detachFromTarget(params={'sessionId': self._download_cdp_session})+ except Exception:+ pass+ self._download_cdp_session = None+ self._download_cdp_session_setup = False++ # Clear other state+ self._targets_with_listeners.clear()+ self._active_downloads.clear()+ self._pdf_viewer_cache.clear()+async def on_NavigationCompleteEvent(self, event: NavigationCompleteEvent) -> None:"""Check for PDFs after navigation completes."""# Clear PDF cache for the navigated URL since content may have changed@@ -115,22 +141,41 @@ class DownloadsWatchdog(BaseWatchdog):if not self._download_cdp_session_setup:# Set up CDP session for downloads (only once per browser session)cdp_client = self.browser_session.cdp_client- session = await cdp_client.send.Target.attachToTarget(- params={'targetId': target_id, 'flatten': True}++ # Set download behavior to allow downloads and enable events+ downloads_path = self.browser_session.browser_profile.downloads_path+ await cdp_client.send.Browser.setDownloadBehavior(+ params={+ 'behavior': 'allow',+ 'downloadPath': str(downloads_path), # Convert Path to string+ 'eventsEnabled': True+ })- session_id = session['sessionId']- await cdp_client.send.Page.enable(session_id=session_id)-- # Set up download event listener- def download_handler(event):- self.logger.info(f'[DownloadsWatchdog] Download event triggered: {event}')- # Pass target_id for this download- asyncio.create_task(self._handle_cdp_download(event, target_id, session_id))-- cdp_client.on('Page.downloadWillBegin', download_handler, session_id=session_id)++ # Register download event handlers+ def download_will_begin_handler(event: dict, session_id: str | 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))+ self._cdp_event_tasks.add(task)+ # Remove from set when done+ task.add_done_callback(lambda t: self._cdp_event_tasks.discard(t))++ def download_progress_handler(event: dict, session_id: str | None):+ # Check if download is complete+ if event.get('state') == 'completed':+ file_path = event.get('filePath')+ if file_path:+ self.logger.info(f'[DownloadsWatchdog] Download completed: {file_path}')+ # Track the download+ self._track_download(file_path)++ # Register the handlers with CDP+ cdp_client.register.Browser.downloadWillBegin(download_will_begin_handler)+ cdp_client.register.Browser.downloadProgress(download_progress_handler)+self._download_cdp_session_setup = True- self._download_cdp_session = session_id- self.logger.debug('[DownloadsWatchdog] Set up CDP download listener')+ self.logger.debug('[DownloadsWatchdog] Set up CDP download listeners')# Track that we've added a listener to prevent duplicatesself._targets_with_listeners.add(target_id)@@ -138,6 +183,32 @@ class DownloadsWatchdog(BaseWatchdog):except Exception as e:self.logger.warning(f'[DownloadsWatchdog] Failed to set up CDP download listener for target {target_id}: {e}')++ def _track_download(self, file_path: str) -> None:+ """Track a completed download and dispatch the appropriate event.++ Args:+ file_path: The path to the downloaded file+ """+ try:+ # Get file info+ path = Path(file_path)+ if path.exists():+ file_size = path.stat().st_size+ self.logger.info(f'[DownloadsWatchdog] Tracked download: {path.name} ({file_size} bytes)')++ # Dispatch download event+ from browser_use.browser.events import FileDownloadedEvent+ self.event_bus.dispatch(FileDownloadedEvent(+ url=str(path), # Use the file path as URL for local files+ file_path=str(path),+ file_name=path.name,+ file_size=file_size+ ))+ else:+ self.logger.warning(f'[DownloadsWatchdog] Downloaded file not found: {file_path}')+ except Exception as e:+ self.logger.error(f'[DownloadsWatchdog] Error tracking download: {e}')async def _handle_cdp_download(self, event: dict, target_id: str, session_id: str) -> None:"""Handle a CDP Page.downloadWillBegin event."""@@ -200,9 +271,9 @@ class DownloadsWatchdog(BaseWatchdog):}})()""",'awaitPromise': True,- 'returnByValue': True+ 'returnByValue': True,},- session_id=session_id+ session_id=session_id,)download_result = result.get('result', {}).get('value')@@ -357,7 +428,9 @@ class DownloadsWatchdog(BaseWatchdog):self.logger.error(f'[DownloadsWatchdog] Error handling download at step "{locals().get("current_step", "unknown")}", error: {e}')- self.logger.error(f'[DownloadsWatchdog] Download state - URL: {download.url}, filename: {download.suggested_filename}')+ self.logger.error(+ f'[DownloadsWatchdog] Download state - URL: {download.url}, filename: {download.suggested_filename}'+ )finally:# Clean up trackingif download_id in self._active_downloads:@@ -374,18 +447,16 @@ class DownloadsWatchdog(BaseWatchdog):target_info = next((t for t in targets['targetInfos'] if t['targetId'] == target_id), None)if not target_info:return False-+page_url = target_info.get('url', '')-+# Check cache firstif page_url in self._pdf_viewer_cache:return self._pdf_viewer_cache[page_url]try:# Attach to target for evaluation- session = await cdp_client.send.Target.attachToTarget(- params={'targetId': target_id, 'flatten': True}- )+ session = await cdp_client.send.Target.attachToTarget(params={'targetId': target_id, 'flatten': True})session_id = session['sessionId']# Add timeout to prevent hanging on unresponsive pages@@ -447,16 +518,16 @@ class DownloadsWatchdog(BaseWatchdog):return { isPdf: false };})()""",- 'returnByValue': True+ 'returnByValue': True,},- session_id=session_id+ session_id=session_id,),timeout=5.0, # 5 second timeout to prevent hanging)-+# Detach from targetawait cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})-+is_pdf_viewer = result.get('result', {}).get('value', {})if is_pdf_viewer.get('isPdf', False):@@ -485,15 +556,13 @@ class DownloadsWatchdog(BaseWatchdog):Returns the download path if successful, None otherwise."""if not self.browser_session.browser_profile.downloads_path:- self.logger.warning(f'[DownloadsWatchdog] ❌ No downloads path configured, cannot save PDF download')+ self.logger.warning('[DownloadsWatchdog] ❌ No downloads path configured, cannot save PDF download')return Nonetry:# Get CDP client and attach to targetcdp_client = self.browser_session.cdp_client- session = await cdp_client.send.Target.attachToTarget(- params={'targetId': target_id, 'flatten': True}- )+ session = await cdp_client.send.Target.attachToTarget(params={'targetId': target_id, 'flatten': True})session_id = session['sessionId']# Try to get the PDF URL with timeout@@ -512,9 +581,9 @@ class DownloadsWatchdog(BaseWatchdog):return { url: window.location.href };})()""",- 'returnByValue': True+ 'returnByValue': True,},- session_id=session_id+ session_id=session_id,),timeout=5.0, # 5 second timeout to prevent hanging)@@ -584,9 +653,9 @@ class DownloadsWatchdog(BaseWatchdog):}})()""",'awaitPromise': True,- 'returnByValue': True+ 'returnByValue': True,},- session_id=session_id+ session_id=session_id,),timeout=10.0, # 10 second timeout for download operation)diff --git a/browser_use/browser/local_browser_watchdog.py b/browser_use/browser/local_browser_watchdog.pyindex b8b0d6a89..e02957256 100644--- a/browser_use/browser/local_browser_watchdog.py+++ b/browser_use/browser/local_browser_watchdog.py@@ -51,7 +51,7 @@ class LocalBrowserWatchdog(BaseWatchdog):self.logger.debug('[LocalBrowserWatchdog] Calling _launch_browser...')process, cdp_url = await self._launch_browser()self.logger.debug(f'[LocalBrowserWatchdog] _launch_browser returned: process={process}, cdp_url={cdp_url}')-+self._subprocess = processself.logger.info(f'[LocalBrowserWatchdog] Browser launched successfully at {cdp_url}, PID: {process.pid}')@@ -123,7 +123,7 @@ class LocalBrowserWatchdog(BaseWatchdog):# Use async playwright properly with timeoutplaywright = await asyncio.wait_for(async_playwright().start(),- timeout=5.0 # 5 second timeout+ timeout=5.0, # 5 second timeout)try:browser_path = playwright.chromium.executable_path@@ -244,17 +244,25 @@ class LocalBrowserWatchdog(BaseWatchdog):try:# Try graceful shutdown firstprocess.terminate()- # Wait up to 5 seconds for process to exit- process.wait(timeout=5)- except psutil.TimeoutExpired:- # Force kill if needed- try:++ # Use async wait instead of blocking wait+ for _ in range(50): # Wait up to 5 seconds (50 * 0.1)+ if not process.is_running():+ return+ await asyncio.sleep(0.1)++ # If still running after 5 seconds, force kill+ if process.is_running():process.kill()- except psutil.NoSuchProcess:- pass+ # Give it a moment to die+ await asyncio.sleep(0.1)+except psutil.NoSuchProcess:# Process already gonepass+ except Exception:+ # Ignore any other errors during cleanup+ pass@staticmethoddef _cleanup_temp_dir(temp_dir: Path | str) -> None:diff --git a/browser_use/browser/navigation_watchdog.py b/browser_use/browser/navigation_watchdog.pyindex 7da8f7ccc..05de8c2f2 100644--- a/browser_use/browser/navigation_watchdog.py+++ b/browser_use/browser/navigation_watchdog.py@@ -67,7 +67,7 @@ class NavigationWatchdog(BaseWatchdog):"""Clear agent focus when browser stops."""# Clear target handlersself._target_close_handlers.clear()- self.current_target_id = None+ self.browser_session.current_target_id = None# ========== Tab Lifecycle Events ==========@@ -194,8 +194,6 @@ class NavigationWatchdog(BaseWatchdog):)# Update agent focus to the new tab immediately- self.current_target_id = target_id- # Also update the browser session's current targetself.browser_session.current_target_id = target_idawait self._dispatch_focus_changed()@@ -237,11 +235,16 @@ class NavigationWatchdog(BaseWatchdog):target_id = Nonetry:target_id = await self.get_or_create_target()- except Exception:+ except Exception as e:+ self.logger.warning(f'[NavigationWatchdog] get_or_create_target failed: {e}')# Fallback to first target- targets = await self.browser_session._cdp_get_all_pages()- if targets:- target_id = targets[0]['targetId']+ try:+ targets = await self.browser_session._cdp_get_all_pages()+ if targets:+ target_id = targets[0]['targetId']+ except Exception as e2:+ self.logger.error(f'[NavigationWatchdog] Failed to get any targets: {e2}')+ raiseif not target_id:raise ValueError('Failed to get or create a target for navigation')@@ -451,7 +454,7 @@ class NavigationWatchdog(BaseWatchdog):@propertydef current_agent_target(self) -> str | None:"""Get the current target ID the agent is focused on."""- return self.current_target_id+ return self.browser_session.current_target_id if self.browser_session else None@propertydef current_agent_tab_index(self) -> int:@@ -465,9 +468,9 @@ class NavigationWatchdog(BaseWatchdog):async def _get_current_tab_index(self) -> int:"""Get the current tab index from target position."""- if self.current_target_id is None:+ if self.browser_session.current_target_id is None:return 0- return await self._get_tab_index_for_target(self.current_target_id)+ return await self._get_tab_index_for_target(self.browser_session.current_target_id)async def _get_tab_index_for_target(self, target_id: str) -> int:"""Get tab index for a specific target ID."""@@ -492,13 +495,31 @@ class NavigationWatchdog(BaseWatchdog):return Noneasync def _initialize_agent_focus(self) -> None:- """Initialize agent focus to first available target."""- targets = await self.browser_session._cdp_get_all_pages()+ """Initialize agent focus to first available target and dispatch TabCreatedEvent for initial pages."""+ # Get all targets and filter for valid page/tab targets+ all_targets = await self.browser_session.cdp_client.send.Target.getTargets()+ targets = [+ t for t in all_targets.get('targetInfos', [])+ if self.browser_session._is_valid_target(t) and t.get('type') in ('page', 'tab')+ ]+if targets:- self.current_target_id = targets[0]['targetId']- self.browser_session.current_target_id = self.current_target_id+ # Set initial focus to first target BEFORE dispatching events+ self.browser_session.current_target_id = targets[0]['targetId']++ # Dispatch TabCreatedEvent for all initial pages so watchdogs can process them+ from browser_use.browser.events import TabCreatedEvent+ for i, target in enumerate(targets):+ target_url = target.get('url', '')+ self.logger.debug(f'[NavigationWatchdog] Dispatching TabCreatedEvent for initial tab {i}: {target_url}')+ self.event_bus.dispatch(TabCreatedEvent(+ tab_index=i,+ url=target_url+ ))++ # Dispatch focus changed eventawait self._dispatch_focus_changed()- target_url = await self._get_target_url(self.current_target_id)+ target_url = await self._get_target_url(self.browser_session.current_target_id)self.logger.info(f'[NavigationWatchdog] Initial agent focus set to tab 0: {target_url}')async def _update_agent_focus_to_latest_tab(self) -> None:@@ -506,10 +527,9 @@ class NavigationWatchdog(BaseWatchdog):targets = await self.browser_session._cdp_get_all_pages()if targets:# Focus on the last target (most recently created)- self.current_target_id = targets[-1]['targetId']- self.browser_session.current_target_id = self.current_target_id+ self.browser_session.current_target_id = targets[-1]['targetId']await self._dispatch_focus_changed()- target_url = await self._get_target_url(self.current_target_id)+ target_url = await self._get_target_url(self.browser_session.current_target_id)tab_index = await self._get_current_tab_index()self.logger.info(f'[NavigationWatchdog] 👀 Agent focus moved to new tab {tab_index}: {target_url}')@@ -517,10 +537,9 @@ class NavigationWatchdog(BaseWatchdog):"""Switch agent focus to a specific tab index."""targets = await self.browser_session._cdp_get_all_pages()if 0 <= tab_index < len(targets):- self.current_target_id = targets[tab_index]['targetId']- self.browser_session.current_target_id = self.current_target_id+ self.browser_session.current_target_id = targets[tab_index]['targetId']await self._dispatch_focus_changed()- target_url = await self._get_target_url(self.current_target_id)+ target_url = await self._get_target_url(self.browser_session.current_target_id)self.logger.info(f'[NavigationWatchdog] Agent focus switched to tab {tab_index}: {target_url}')async def _find_new_agent_target(self) -> None:@@ -530,22 +549,20 @@ class NavigationWatchdog(BaseWatchdog):# Try to stay at the same index, or go to the previous onecurrent_index = await self._get_current_tab_index()new_index = min(current_index, len(targets) - 1)- self.current_target_id = targets[new_index]['targetId']- self.browser_session.current_target_id = self.current_target_id+ self.browser_session.current_target_id = targets[new_index]['targetId']await self._dispatch_focus_changed()- target_url = await self._get_target_url(self.current_target_id)+ target_url = await self._get_target_url(self.browser_session.current_target_id)self.logger.info(f'[NavigationWatchdog] Agent focus moved to tab {new_index}: {target_url}')else:- self.current_target_id = Noneif self.browser_session:self.browser_session.current_target_id = Noneasync def _dispatch_focus_changed(self) -> None:"""Dispatch event when agent focus changes."""- if self.current_target_id:+ if self.browser_session.current_target_id:try:# Get URL asynchronously- target_url = await self._get_target_url(self.current_target_id)+ target_url = await self._get_target_url(self.browser_session.current_target_id)tab_index = await self._get_current_tab_index()self.event_bus.dispatch(AgentFocusChangedEvent(@@ -558,31 +575,33 @@ class NavigationWatchdog(BaseWatchdog):async def get_or_create_target(self) -> str:"""Get current agent target or create a new one if none exists."""- if self.current_target_id:+ if self.browser_session.current_target_id:# Check if current target URL is still allowed- target_url = await self._get_target_url(self.current_target_id)+ target_url = await self._get_target_url(self.browser_session.current_target_id)if target_url and not self._is_url_allowed(target_url):self.logger.warning(f'⛔️ Current target URL no longer allowed: {target_url}')# Close the current target and find/create a new onetry:- await self.browser_session._cdp_close_page(self.current_target_id)+ await self.browser_session._cdp_close_page(self.browser_session.current_target_id)except Exception:pass- self.current_target_id = None+ self.browser_session.current_target_id = Noneelse:- return self.current_target_id+ return self.browser_session.current_target_idtry:targets = await self.browser_session._cdp_get_all_pages()for target in targets:target_url = target.get('url', '')if self._is_url_allowed(target_url):- self.current_target_id = target['targetId']- self.browser_session.current_target_id = self.current_target_id+ self.browser_session.current_target_id = target['targetId']await self._dispatch_focus_changed()- return self.current_target_id- except TimeoutError:- pass+ return self.browser_session.current_target_id+ except Exception as e:+ self.logger.warning(f'[NavigationWatchdog] Failed to get targets: {e}')+ # Don't pass TimeoutError, re-raise other exceptions+ if not isinstance(e, TimeoutError):+ raise# No tabs available or no allowed tabs, create a new one with about:blankself.logger.info('[NavigationWatchdog] No active target, creating new tab')@@ -593,9 +612,8 @@ class NavigationWatchdog(BaseWatchdog):# Try to get the new targettargets = await self.browser_session._cdp_get_all_pages()if targets:- self.current_target_id = targets[-1]['targetId']- self.browser_session.current_target_id = self.current_target_id+ self.browser_session.current_target_id = targets[-1]['targetId']await self._dispatch_focus_changed()- return self.current_target_id+ return self.browser_session.current_target_id- raise ValueError('Failed to create or find an active target')\ No newline at end of file+ raise ValueError('Failed to create or find an active target')diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex 7c3248fd8..cdc09eddf 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -124,9 +124,7 @@ class BrowserSession(BaseModel):@propertydef logger(self) -> Any:"""Get instance-specific logger with session ID in the name"""- if (- self._logger is None- ): # keep updating the name pre-init because our id and str(self) can change+ if self._logger is None: # keep updating the name pre-init because our id and str(self) can changeimport loggingself._logger = logging.getLogger(f'browser_use.{self}')@@ -140,7 +138,7 @@ class BrowserSession(BaseModel):Returns:The CDP client instance-+Raises:RuntimeError: If CDP client is not initialized yet"""@@ -159,36 +157,43 @@ class BrowserSession(BaseModel):f'BrowserSession🆂 {self.id[-4:]}:{port_number} #{str(id(self))[-2:]}' # ' 🅟 {str(id(self.current_target_id))[-2:]}')- async def on_BrowserStartEvent(self, event: BrowserStartEvent) -> None:- """Handle browser start request."""+ async def on_BrowserStartEvent(self, event: BrowserStartEvent) -> dict[str, str]:+ """Handle browser start request.++ Returns:+ Dict with 'cdp_url' key containing the CDP URL+ """# Initialize and attach all watchdogs FIRST so LocalBrowserWatchdog can handle BrowserLaunchEventawait self.attach_all_watchdogs()- if self.cdp_url:- self.event_bus.dispatch(BrowserConnectedEvent(cdp_url=self.cdp_url))- return-try:- if self.is_local and not self.cdp_url:- # Launch local browser using event-driven approach- launch_event = self.event_bus.dispatch(BrowserLaunchEvent())- await launch_event-- # Get the CDP URL from LocalBrowserWatchdog handler result- results = await launch_event.event_results_flat_dict()- self.cdp_url = results.get('cdp_url')-- if not self.cdp_url:- raise Exception('No CDP URL returned from LocalBrowserWatchdog')+ # If no CDP URL, launch local browser+ if not self.cdp_url:+ if self.is_local:+ # Launch local browser using event-driven approach+ launch_event = self.event_bus.dispatch(BrowserLaunchEvent())+ await launch_event++ # Get the CDP URL from LocalBrowserWatchdog handler result+ results = await launch_event.event_results_flat_dict()+ self.cdp_url = results.get('cdp_url')++ if not self.cdp_url:+ raise Exception('No CDP URL returned from LocalBrowserWatchdog')+ else:+ raise Exception('No CDP URL provided for remote browser connection')assert self.cdp_url and '://' in self.cdp_url- # Setup browser via CDP without Playwright+ # Setup browser via CDP (for both local and remote cases)await self.setup_browser_via_cdp_url()- # Notify that browser is connected+ # Notify that browser is connected (single place)self.event_bus.dispatch(BrowserConnectedEvent(cdp_url=self.cdp_url))++ # Return the CDP URL for other components+ return {'cdp_url': self.cdp_url}except Exception as e:self.event_bus.dispatch(@@ -204,14 +209,18 @@ class BrowserSession(BaseModel):"""Handle browser stop request."""try:- # TODO: close all pages here or tell the browser to close gracefully? is there any point?- # we might need to give the browser time to save trace files, recordings, etc. during shutdown-# Check if we should keep the browser aliveif self.browser_profile.keep_alive and not event.force:self.event_bus.dispatch(BrowserStoppedEvent(reason='Kept alive due to keep_alive=True'))return+ # TODO: We may want to gracefully tell the browser to shut down via CDP here+ # so it can properly save traces, recordings, user_data_dir changes, etc.+ # For example:+ # - Browser.close() to trigger graceful browser shutdown+ # - Target.closeTarget() for each page+ # - Give browser time to flush data before process kill+# Reset stateif self.is_local:self.cdp_url = None@@ -302,76 +311,108 @@ class BrowserSession(BaseModel):# Watchdog already exists, don't re-initialize to avoid duplicate handlerslogger.debug(f'[Session] {watchdog_class.__name__} already initialized, skipping')- def model_copy(self, **kwargs) -> Self:- """Create a copy of this BrowserSession that shares the browser resources but doesn't own them.-- This method creates a copy that:- - Shares the same browser, browser_context, and playwright objects- - Doesn't own the browser resources (won't close them when garbage collected)- - Keeps a reference to the original to prevent premature garbage collection- """- # Create the copy using the parent class method- copy = super().model_copy(**kwargs)-- # The copy doesn't own the browser resources- copy._owns_browser_resources = False-- # Note: _original_browser_session tracking moved to Agent class- # Keep the copy without reference to avoid circular dependencies-- # Manually copy over the excluded fields that are needed for browser connection- # These fields are excluded in the model config but need to be shared- copy.current_target_id = self.current_target_id-- return copy-async def setup_browser_via_cdp_url(self) -> None:- """Connect to a remote chromium-based browser via CDP using cdp-use."""+ """Connect to a remote chromium-based browser via CDP using cdp-use.++ This MUST succeed or the browser is unusable. Fails hard on any error.+ """if not self.cdp_url:- return # no cdp_url provided, nothing to do+ raise RuntimeError('Cannot setup CDP connection without CDP URL')self.logger.info(f'🌎 Connecting to existing chromium-based browser via CDP: {self.cdp_url} -> (remote browser)')- # Import cdp-use client- import httpx- from cdp_use import CDPClient-- # Convert HTTP URL to WebSocket URL if needed- ws_url = self.cdp_url- if not ws_url.startswith('ws'):- # If it's an HTTP URL, fetch the WebSocket URL from /json/version endpoint- url = ws_url.rstrip('/')- if not url.endswith('/json/version'):- url = url + '/json/version'- async with httpx.AsyncClient() as client:- version_info = await client.get(url)- ws_url = version_info.json()['webSocketDebuggerUrl']-- # Create and store the CDP client for direct CDP communication- if self._cdp_client is None:- self._cdp_client = CDPClient(ws_url)- await self._cdp_client.start()-- # Get browser targets to find available contexts/pages- targets = await self._cdp_client.send.Target.getTargets()-- # Find main browser pages (not iframes or workers)- page_targets = [t for t in targets['targetInfos'] if t['type'] == 'page']+ try:+ # Import cdp-use client+ import httpx+ from cdp_use import CDPClient- if not page_targets:- # No pages found, create a new one- new_target = await self._cdp_client.send.Target.createTarget(params={'url': 'about:blank'})- target_id = new_target['targetId']- else:- # Use the first available page- target_id = page_targets[0]['targetId']+ # Convert HTTP URL to WebSocket URL if needed+ ws_url = self.cdp_url+ if not ws_url.startswith('ws'):+ # If it's an HTTP URL, fetch the WebSocket URL from /json/version endpoint+ url = ws_url.rstrip('/')+ if not url.endswith('/json/version'):+ url = url + '/json/version'+ async with httpx.AsyncClient() as client:+ version_info = await client.get(url)+ ws_url = version_info.json()['webSocketDebuggerUrl']++ # Create and store the CDP client for direct CDP communication+ if self._cdp_client is None:+ self._cdp_client = CDPClient(ws_url)+ assert self._cdp_client is not None+ await self._cdp_client.start()+ self.logger.info('✅ CDP client connected successfully')++ assert self._cdp_client is not None++ # Get browser targets to find available contexts/pages+ targets = await self._cdp_client.send.Target.getTargets()++ # Find main browser pages (avoiding iframes, workers, extensions, etc.)+ page_targets = [t for t in targets['targetInfos']+ if self._is_valid_target(t, include_http=True, include_about=True, include_pages=True, include_iframes=False, include_workers=False)]++ # Check for chrome://newtab pages and immediately redirect them+ # to about:blank to avoid JS issues from CDP on chrome://* urls+ from browser_use.utils import is_new_tab_page++ for target in page_targets:+ target_url = target.get('url', '')+ if is_new_tab_page(target_url) and target_url != 'about:blank':+ # Redirect chrome://newtab to about:blank to avoid JS issues preventing driving chrome://newtab+ target_id = target['targetId']+ self.logger.info(f'🔄 Redirecting {target_url} to about:blank for target {target_id}')+ try:+ # Attach to target and navigate to about:blank+ session = await self._cdp_client.send.Target.attachToTarget(+ params={'targetId': target_id, 'flatten': True}+ )+ session_id = session['sessionId']+ await self._cdp_client.send.Page.navigate(+ params={'url': 'about:blank'}, session_id=session_id+ )+ await self._cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})+ except Exception as e:+ self.logger.warning(f'Failed to redirect {target_url} to about:blank: {e}')++ if not page_targets:+ # No pages found, create a new one+ new_target = await self._cdp_client.send.Target.createTarget(params={'url': 'about:blank'})+ target_id = new_target['targetId']+ self.logger.info(f'📄 Created new blank page with target ID: {target_id}')+ else:+ # Use the first available page+ target_id = page_targets[0]['targetId']+ self.logger.info(f'📄 Using existing page with target ID: {target_id}')- # Store the current page target ID- self.current_target_id = target_id+ # Store the current page target ID+ self.current_target_id = target_id- # Mark that we're connected via CDP (no playwright browser object)- self._cdp_connected = True+ # Enable Network domain on the target session for cookie access+ try:+ # Attach to the target to enable Network domain+ session = await self._cdp_client.send.Target.attachToTarget(+ params={'targetId': target_id, 'flatten': True}+ )+ session_id = session['sessionId']+ await self._cdp_client.send.Network.enable(session_id=session_id)+ self.logger.info(f'🌐 Network domain enabled for cookie access on target {target_id[:8]}...')+ # Detach from target after enabling+ await self._cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})+ except Exception as e:+ self.logger.warning(f'Failed to enable Network domain: {e}')++ except Exception as e:+ # Fatal error - browser is not usable without CDP connection+ self.logger.error(f'❌ FATAL: Failed to setup CDP connection: {e}')+ self.logger.error('❌ Browser cannot continue without CDP connection')+ # Clean up any partial state+ self._cdp_client = None+ self.current_target_id = None+ # Re-raise as a fatal error+ raise RuntimeError(f'Failed to establish CDP connection to browser: {e}') from easync def setup_domservice_init_scripts(self, retry_count: int = 0) -> None:# self.logger.debug('Setting up init scripts in browser')@@ -457,6 +498,7 @@ class BrowserSession(BaseModel):# Get all page targets using CDPpages = await self._cdp_get_all_pages()+for i, page_target in enumerate(pages):target_id = page_target['targetId']url = page_target['url']@@ -472,10 +514,10 @@ class BrowserSession(BaseModel):else:# Normal pages - try to get title with CDP for reliabilitytry:- # Use helper to get document title+ # Use helper to get document title with very short timeouttitle_result = await asyncio.wait_for(self._cdp_execute_on_target(target_id, commands=[('Runtime.evaluate', {'expression': 'document.title'})]),- timeout=2.0,+ timeout=0.2, # Very short timeout to prevent hanging)title = title_result.get('result', {}).get('value', '') if title_result else ''@@ -492,20 +534,9 @@ class BrowserSession(BaseModel):passexcept Exception as e:- # Page might be crashed or unresponsive- self.logger.debug(f'⚠️ Failed to get tab info for tab #{i}: {_log_pretty_url(url)} - {type(e).__name__}')-- # Only mark as unusable if it's actually a new tab page- if is_new_tab_page(url):- title = 'ignore this tab and do not use it'- else:- # For crashed pages, close them as they're not useful- try:- await self._cdp_close_page(target_id)- self.logger.debug(f"🪓 Force-closed page because it's unresponsive: {_log_pretty_url(url)}")- continue- except Exception:- title = '(Error)'+ # Page might be crashed or unresponsive - just use empty title+ self.logger.debug(f'⚠️ Failed to get tab title for tab #{i}: {_log_pretty_url(url)} - {type(e).__name__}')+ title = ''tab_info = TabInfo(page_id=i,@@ -516,6 +547,7 @@ class BrowserSession(BaseModel):index=i,)tabs.append(tab_info)+return tabs# DOM element methods@@ -822,11 +854,14 @@ class BrowserSession(BaseModel):targets = await self.cdp_client.send.Target.getTargets()for target in targets['targetInfos']:- if target['type'] in ['page', 'iframe']:- # Check if this target contains the frame- frames = await self.frames_by_target(target['targetId'])- if frame_id in frames:- return target['targetId']+ # Skip invalid targets+ if not self._is_valid_target(target, include_http=True, include_about=True, include_pages=True, include_iframes=True, include_workers=False):+ continue++ # Check if this target contains the frame+ frames = await self.frames_by_target(target['targetId'])+ if frame_id in frames:+ return target['targetId']return None@@ -924,6 +959,10 @@ class BrowserSession(BaseModel):# Search through page targets to find which one contains the framefor target in targets['targetInfos']:+ # Skip invalid targets+ if not self._is_valid_target(target):+ continue+if target['type'] != 'page':continue@@ -1005,6 +1044,7 @@ class BrowserSession(BaseModel):targets = await self.cdp_client.send.Target.getTargets()for target in targets.get('targetInfos', []):if target.get('targetId') == self.current_target_id:+ # Still return even if it's not a "valid" target since we're looking for a specific IDreturn targetreturn None@@ -1124,14 +1164,12 @@ class BrowserSession(BaseModel):# Check if we have a CDP client and targetif not self.current_target_id:return-+# This will raise RuntimeError if CDP client not initializedcdp_client = self.cdp_client-+# Attach to current target- session = await cdp_client.send.Target.attachToTarget(- params={'targetId': self.current_target_id, 'flatten': True}- )+ session = await cdp_client.send.Target.attachToTarget(params={'targetId': self.current_target_id, 'flatten': True})session_id = session['sessionId']# Remove highlights via JavaScript - matches the highlighting system from debug/highlights.py@@ -1209,8 +1247,9 @@ class BrowserSession(BaseModel):async def _cdp_get_all_pages(self) -> list[dict]:"""Get all browser pages/tabs using CDP Target.getTargets."""targets = await self.cdp_client.send.Target.getTargets()- # Filter for page targets only- return [t for t in targets.get('targetInfos', []) if t.get('type') == 'page']+ # Filter for valid page/tab targets only+ return [t for t in targets.get('targetInfos', [])+ if self._is_valid_target(t) and t.get('type') in ('page', 'tab')]async def _cdp_create_new_page(self, url: str = 'about:blank') -> str:"""Create a new page/tab using CDP Target.createTarget. Returns target ID."""@@ -1226,22 +1265,93 @@ class BrowserSession(BaseModel):await self.cdp_client.send.Target.activateTarget(params={'targetId': target_id})async def _cdp_get_cookies(self, urls: list[str] | None = None) -> list[dict]:- """Get cookies using CDP Network.getCookies."""- params = {'urls': urls} if urls else {}- result = await self.cdp_client.send.Network.getCookies(**params)- return result.get('cookies', [])+ """Get cookies using CDP Network.getCookies.++ Note: Network domain must be enabled on a target before calling this.+ """+ if not self.current_target_id:+ return []++ # Attach to current target to get cookies+ session = await self.cdp_client.send.Target.attachToTarget(+ params={'targetId': self.current_target_id, 'flatten': True}+ )+ session_id = session['sessionId']++ try:+ # Enable Network domain if not already enabled+ await self.cdp_client.send.Network.enable(session_id=session_id)++ # Get cookies+ params = {'urls': urls} if urls else {}+ result = await self.cdp_client.send.Network.getCookies(params=params, session_id=session_id)+ return result.get('cookies', [])+ finally:+ # Always detach from target+ await self.cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})async def _cdp_set_cookies(self, cookies: list[dict]) -> None:"""Set cookies using CDP Network.setCookies."""- await self.cdp_client.send.Network.setCookies(params={'cookies': cookies})+ if not self.current_target_id or not cookies:+ return++ # Attach to current target to set cookies+ session = await self.cdp_client.send.Target.attachToTarget(+ params={'targetId': self.current_target_id, 'flatten': True}+ )+ session_id = session['sessionId']++ try:+ # Enable Network domain if not already enabled+ await self.cdp_client.send.Network.enable(session_id=session_id)++ # Set cookies+ await self.cdp_client.send.Network.setCookies(params={'cookies': cookies}, session_id=session_id)+ finally:+ # Always detach from target+ await self.cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})async def _cdp_clear_cookies(self) -> None:"""Clear all cookies using CDP Network.clearBrowserCookies."""- await self.cdp_client.send.Network.clearBrowserCookies()+ if not self.current_target_id:+ return++ # Attach to current target to clear cookies+ session = await self.cdp_client.send.Target.attachToTarget(+ params={'targetId': self.current_target_id, 'flatten': True}+ )+ session_id = session['sessionId']++ try:+ # Enable Network domain if not already enabled+ await self.cdp_client.send.Network.enable(session_id=session_id)++ # Clear cookies+ await self.cdp_client.send.Network.clearBrowserCookies(session_id=session_id)+ finally:+ # Always detach from target+ await self.cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})async def _cdp_set_extra_headers(self, headers: dict[str, str]) -> None:"""Set extra HTTP headers using CDP Network.setExtraHTTPHeaders."""- await self.cdp_client.send.Network.setExtraHTTPHeaders(params={'headers': headers})+ if not self.current_target_id:+ return++ # Attach to current target to set headers+ session = await self.cdp_client.send.Target.attachToTarget(+ params={'targetId': self.current_target_id, 'flatten': True}+ )+ session_id = session['sessionId']++ try:+ # Enable Network domain if not already enabled+ await self.cdp_client.send.Network.enable(session_id=session_id)++ # Set extra headers+ await self.cdp_client.send.Network.setExtraHTTPHeaders(params={'headers': headers}, session_id=session_id)+ finally:+ # Always detach from target+ await self.cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})async def _cdp_grant_permissions(self, permissions: list[str], origin: str | None = None) -> None:"""Grant permissions using CDP Browser.grantPermissions."""@@ -1277,9 +1387,8 @@ class BrowserSession(BaseModel):async def _cdp_get_storage_state(self) -> dict:"""Get storage state (cookies, localStorage, sessionStorage) using CDP."""- # Get cookies- cookies_result = await self.cdp_client.send.Network.getCookies()- cookies = cookies_result.get('cookies', [])+ # Use the _cdp_get_cookies helper which handles session attachment+ cookies = await self._cdp_get_cookies()# Get localStorage and sessionStorage would require evaluating JavaScript# on each origin, which is more complex. For now, return cookies only.@@ -1306,33 +1415,50 @@ class BrowserSession(BaseModel):await self._cdp_execute_on_target(target_to_use, commands=[('Page.enable', {}), ('Page.navigate', {'url': url})])@staticmethod- def _is_valid_target(target_info: dict) -> bool:+ def _is_valid_target(target_info: dict, include_http: bool = True, include_chrome: bool = False, include_chrome_extensions: bool = False, include_chrome_error: bool = False, include_about: bool = True, include_iframes: bool = True, include_pages: bool = True, include_workers: bool = False) -> bool:"""Check if a target should be processed.-+Args:target_info: Target info dict from CDP-+Returns:True if target should be processed, False if it should be skipped"""target_type = target_info.get('type', '')url = target_info.get('url', '')-- # Exclude chrome extension and error pages- if url.startswith('chrome-extension://') or url.startswith('chrome-error://'):- return False-- # Exclude any worker targets- if 'worker' in target_type.lower():- return False-- # Include specific target types- valid_types = {'page', 'tab', 'iframe', 'webview', 'browser'}- return target_type in valid_types++ url_allowed, type_allowed = False, False++ if url.startswith('chrome-error://') and include_chrome_error:+ url_allowed = True++ if url.startswith('chrome://') and include_chrome:+ url_allowed = True++ if url.startswith('chrome-extension://') and include_chrome_extensions:+ url_allowed = True++ # dont allow about:srcdoc! there are also other rare about: pages that we want to avoid+ if url == 'about:blank' and include_about:+ url_allowed = True++ if (url.startswith('http://') or url.startswith('https://')) and include_http:+ url_allowed = True++ if target_type in ('service_worker', 'shared_worker', 'worker') and include_workers:+ type_allowed = True++ if target_type in ('page', 'tab') and include_pages:+ type_allowed = True++ if target_type in ('iframe', 'webview') and include_iframes:+ type_allowed = True++ return url_allowed and type_allowedasync def get_all_frames(self) -> tuple[dict[str, dict], dict[str, str]]:"""Get a complete frame hierarchy from all browser targets.-+Returns:Tuple of (all_frames, target_sessions) where:- all_frames: dict mapping frame_id -> frame info dict with all metadata@@ -1340,70 +1466,68 @@ class BrowserSession(BaseModel):"""all_frames = {} # frame_id -> FrameInfo dicttarget_sessions = {} # target_id -> session_id (keep sessions alive during collection)-+# Get all targetstargets = await self.cdp_client.send.Target.getTargets()all_targets = targets.get('targetInfos', [])-+# First pass: collect frame trees from ALL targetsfor target in all_targets:target_id = target.get('targetId')-+if not target_id:continue-+# Skip invalid targets- if not self._is_valid_target(target):+ if not self._is_valid_target(target, include_http=True, include_about=True,include_pages=True, include_iframes=True, include_workers=False):continue-+# Attach to target- session = await self.cdp_client.send.Target.attachToTarget(- params={'targetId': target_id, 'flatten': True}- )+ session = await self.cdp_client.send.Target.attachToTarget(params={'targetId': target_id, 'flatten': True})session_id = session['sessionId']target_sessions[target_id] = session_id-+try:# Set auto-attach to get related targetsawait self.cdp_client.send.Target.setAutoAttach(- params={- 'autoAttach': True,- 'waitForDebuggerOnStart': False,- 'flatten': True- },- session_id=session_id+ params={'autoAttach': True, 'waitForDebuggerOnStart': False, 'flatten': True}, session_id=session_id)-+# Try to get frame tree (not all target types support this)try:await self.cdp_client.send.Page.enable(session_id=session_id)frame_tree_result = await self.cdp_client.send.Page.getFrameTree(session_id=session_id)-+# Process the frame tree recursivelydef process_frame_tree(node, parent_frame_id=None):"""Recursively process frame tree and add to all_frames."""frame = node.get('frame', {})current_frame_id = frame.get('id')-+if current_frame_id:+ # For iframe targets, check if the frame has a parentId field+ # This indicates it's an OOPIF with a parent in another target+ actual_parent_id = frame.get('parentId') or parent_frame_id+# Create frame info with all CDP response data plus our additionsframe_info = {- **frame, # Include all original frame data+ **frame, # Include all original frame data: id, url, parentId, etc.'frameTargetId': target_id, # Target that can access this frame- 'parentFrameId': parent_frame_id, # Parent frame ID if any+ 'parentFrameId': actual_parent_id, # Use parentId from frame if available'childFrameIds': [], # Will be populated below'isCrossOrigin': False, # Will be determined based on context+ 'isUrlValid': _is_url_valid(frame.get('url', '')),}-+# Check if frame is cross-origin based on crossOriginIsolatedContextTypecross_origin_type = frame.get('crossOriginIsolatedContextType')if cross_origin_type and cross_origin_type != 'NotIsolated':frame_info['isCrossOrigin'] = True-+# For iframe targets, the frame itself is likely cross-originif target.get('type') == 'iframe':frame_info['isCrossOrigin'] = True-+# Add child frame IDs (note: OOPIFs won't appear here)child_frames = node.get('childFrames', [])for child in child_frames:@@ -1411,7 +1535,7 @@ class BrowserSession(BaseModel):child_frame_id = child_frame.get('id')if child_frame_id:frame_info['childFrameIds'].append(child_frame_id)-+# Store or merge frame infoif current_frame_id in all_frames:# Frame already seen from another target, merge info@@ -1422,83 +1546,82 @@ class BrowserSession(BaseModel):existing['isCrossOrigin'] = Trueelse:all_frames[current_frame_id] = frame_info-+# Process child frames recursivelyfor child in child_frames:process_frame_tree(child, current_frame_id)-+# Process the entire frame treeprocess_frame_tree(frame_tree_result.get('frameTree', {}))-+except Exception:# Target doesn't support Page domain or has no framespass-+except Exception:# Error processing this targetpass-+# Second pass: populate backend node IDs and parent target IDsawait self._populate_frame_metadata(all_frames, target_sessions)-+return all_frames, target_sessionsasync def _populate_frame_metadata(self, all_frames: dict[str, dict], target_sessions: dict[str, str]) -> None:"""Populate additional frame metadata like backend node IDs and parent target IDs.-+Args:all_frames: Frame hierarchy dict to populatetarget_sessions: Active target sessions"""for frame_id_iter, frame_info in all_frames.items():parent_frame_id = frame_info.get('parentFrameId')-+if parent_frame_id and parent_frame_id in all_frames:parent_frame_info = all_frames[parent_frame_id]parent_target_id = parent_frame_info.get('frameTargetId')-+# Store parent target IDframe_info['parentTargetId'] = parent_target_id-+# Try to get backend node ID from parent contextif parent_target_id in target_sessions:parent_session_id = target_sessions[parent_target_id]try:# Enable DOM domainawait self.cdp_client.send.DOM.enable(session_id=parent_session_id)-+# Get frame owner info to find backend node IDframe_owner = await self.cdp_client.send.DOM.getFrameOwner(- params={'frameId': frame_id_iter},- session_id=parent_session_id+ params={'frameId': frame_id_iter}, session_id=parent_session_id)-+if frame_owner:frame_info['backendNodeId'] = frame_owner.get('backendNodeId')frame_info['nodeId'] = frame_owner.get('nodeId')-+except Exception:# Frame owner not available (likely cross-origin)passasync def find_frame_target(self, frame_id: str, all_frames: dict[str, dict] | None = None) -> dict | None:"""Find the frame info for a specific frame ID.-+Args:frame_id: The frame ID to search forall_frames: Optional pre-built frame hierarchy. If None, will call get_all_frames()-+Returns:Frame info dict if found, None otherwise"""if all_frames is None:all_frames, _ = await self.get_all_frames()-+return all_frames.get(frame_id)async def cleanup_target_sessions(self, target_sessions: dict[str, str], keep_target_id: str | None = None) -> None:"""Clean up CDP sessions by detaching from targets.-+Args:target_sessions: Dict of target_id -> session_id to clean upkeep_target_id: Optional target ID to keep attached (won't detach this one)@@ -1506,9 +1629,7 @@ class BrowserSession(BaseModel):for target_id, session_id in target_sessions.items():if target_id != keep_target_id:try:- await self.cdp_client.send.Target.detachFromTarget(- params={'sessionId': session_id}- )+ await self.cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})except Exception:pass@@ -1529,26 +1650,26 @@ class BrowserSession(BaseModel):"""# Get complete frame hierarchyall_frames, target_sessions = await self.get_all_frames()-+# Find the requested frameframe_info = await self.find_frame_target(frame_id, all_frames)-+if frame_info:target_id = frame_info.get('frameTargetId')-+if target_id in target_sessions:# Use existing sessionsession_id = target_sessions[target_id]-+# Clean up other sessions before returningawait self.cleanup_target_sessions(target_sessions, keep_target_id=target_id)-+# Return the client with session attached (caller must detach)return self.cdp_client, session_id, target_id-+# Clean up all sessions before raising errorawait self.cleanup_target_sessions(target_sessions)-+# Frame not foundraise ValueError(f"Frame with ID '{frame_id}' not found in any target")diff --git a/browser_use/browser/storage_state_watchdog.py b/browser_use/browser/storage_state_watchdog.pyindex a5a822d97..b982a9b6c 100644--- a/browser_use/browser/storage_state_watchdog.py+++ b/browser_use/browser/storage_state_watchdog.py@@ -137,13 +137,13 @@ class StorageStateWatchdog(BaseWatchdog):# Check for Set-Cookie headers in the responseheaders = event.get('headers', {})if 'set-cookie' in headers or 'Set-Cookie' in headers:- logger.debug('[StorageStateWatchdog] Cookie change detected via CDP')+ self.logger.debug('[StorageStateWatchdog] Cookie change detected via CDP')# If save on change is enabled, trigger save immediatelyif self.save_on_change:await self._save_storage_state()except Exception as e:- logger.warning(f'[StorageStateWatchdog] Error checking for cookie changes: {e}')+ self.logger.warning(f'[StorageStateWatchdog] Error checking for cookie changes: {e}')async def _monitor_storage_changes(self) -> None:"""Periodically check for storage changes and auto-save."""@@ -153,13 +153,13 @@ class StorageStateWatchdog(BaseWatchdog):# Check if cookies have changedif await self._have_cookies_changed():- logger.info('[StorageStateWatchdog] Detected changes to sync with storage_state.json')+ self.logger.info('[StorageStateWatchdog] Detected changes to sync with storage_state.json')await self._save_storage_state()except asyncio.CancelledError:breakexcept Exception as e:- logger.error(f'[StorageStateWatchdog] Error in monitoring loop: {e}')+ self.logger.error(f'[StorageStateWatchdog] Error in monitoring loop: {e}')async def _have_cookies_changed(self) -> bool:"""Check if cookies have changed since last save."""@@ -181,14 +181,14 @@ class StorageStateWatchdog(BaseWatchdog):return current_cookie_set != last_cookie_setexcept Exception as e:- logger.debug(f'[StorageStateWatchdog] Error comparing cookies: {e}')+ self.logger.debug(f'[StorageStateWatchdog] Error comparing cookies: {e}')return Falseasync def _save_storage_state(self, path: str | None = None) -> None:"""Save browser storage state to file."""async with self._save_lock:if not self.browser_session.cdp_client:- logger.warning('[StorageStateWatchdog] No CDP client available for saving')+ self.logger.warning('[StorageStateWatchdog] No CDP client available for saving')returnsave_path = path or self.browser_session.browser_profile.storage_state@@ -198,7 +198,7 @@ class StorageStateWatchdog(BaseWatchdog):# Skip saving if the storage state is already a dict (indicates it was loaded from memory)# We only save to file if it started as a file pathif isinstance(save_path, dict):- logger.debug('[StorageStateWatchdog] Storage state is already a dict, skipping file save')+ self.logger.debug('[StorageStateWatchdog] Storage state is already a dict, skipping file save')returntry:@@ -219,7 +219,7 @@ class StorageStateWatchdog(BaseWatchdog):existing_state = json.loads(json_path.read_text())merged_state = self._merge_storage_states(existing_state, dict(storage_state))except Exception as e:- logger.error(f'[StorageStateWatchdog] Failed to merge with existing state: {e}')+ self.logger.error(f'[StorageStateWatchdog] Failed to merge with existing state: {e}')# Write atomicallytemp_path = json_path.with_suffix('.json.tmp')diff --git a/browser_use/controller/service.py b/browser_use/controller/service.pyindex c1f03b907..b30362bd8 100644--- a/browser_use/controller/service.py+++ b/browser_use/controller/service.py@@ -120,8 +120,15 @@ class Controller(Generic[Context]):return ActionResult(extracted_content=msg, include_in_memory=True, long_term_memory=memory)except Exception as e:error_msg = str(e)+ # Always log the actual error first for debugging+ browser_session.logger.error(f'❌ Navigation failed: {error_msg}')++ # Check if it's specifically a RuntimeError about CDP client+ if isinstance(e, RuntimeError) and 'CDP client not initialized' in error_msg:+ browser_session.logger.error('❌ Browser connection failed - CDP client not properly initialized')+ raise BrowserError(f'Browser connection error: {error_msg}')# Check for network-related errors- if any(+ elif any(err in error_msgfor err in ['ERR_NAME_NOT_RESOLVED',@@ -132,10 +139,10 @@ class Controller(Generic[Context]):]):site_unavailable_msg = f'Site unavailable: {params.url} - {error_msg}'- logger.warning(site_unavailable_msg)+ browser_session.logger.warning(f'⚠️ {site_unavailable_msg}')raise BrowserError(site_unavailable_msg)else:- # Re-raise non-network errors (including URLNotAllowedError for unauthorized domains)+ # Re-raise the original errorraise@self.registry.action('Go back', param_model=NoParamsAction)diff --git a/browser_use/dom/debug/highlights.py b/browser_use/dom/debug/highlights.pyindex b38dd3492..4ce7a8056 100644--- a/browser_use/dom/debug/highlights.py+++ b/browser_use/dom/debug/highlights.py@@ -53,7 +53,7 @@ async def remove_highlighting_script(dom_service: DomService) -> None:"""Remove all browser-use highlighting elements from the page."""try:# Get CDP client and session ID- targets = await dom_service._get_targets_for_current_page()+ targets = await dom_service._get_targets_for_page()session_id = await dom_service._attach_target_activate_domains_get_session_id(targets.page_session)print('🧹 Removing browser-use highlighting elements')@@ -90,7 +90,7 @@ async def inject_highlighting_script(dom_service: DomService, interactive_elemenconverted_elements = convert_dom_selector_map_to_highlight_format(interactive_elements)# Get CDP client and session ID- targets = await dom_service._get_targets_for_current_page()+ targets = await dom_service._get_targets_for_page()session_id = await dom_service._attach_target_activate_domains_get_session_id(targets.page_session)print(f'📍 Creating CSP-safe highlighting for {len(converted_elements)} elements')diff --git a/browser_use/dom/service.py b/browser_use/dom/service.pyindex 3bc17bdec..528af4908 100644--- a/browser_use/dom/service.py+++ b/browser_use/dom/service.py@@ -45,7 +45,7 @@ class DomService:def __init__(self, browser_session: 'BrowserSession', logger: logging.Logger | None = None):self.browser_session = browser_session- self.logger = logger or logging.getLogger(__name__)+ self.logger = logger or browser_session.logger# Cache for session domains that have been enabledself.session_id_domains_enabled_cache: dict[str, bool] = {}@@ -217,7 +217,7 @@ class DomService:return float(device_pixel_ratio)except Exception as e:- print(f'⚠️ Viewport size detection failed: {e}')+ self.logger.debug(f'Viewport size detection failed: {e}')# Fallback to default viewport sizereturn 1.0@@ -572,7 +572,7 @@ class DomService:iframe_document_target = None# if target actually exists in one of the frames, just recursively build the dom tree for itif iframe_document_target:- print(f'🔍 Getting content document for iframe {node.get("frameId", None)}')+ self.logger.debug(f'Getting content document for iframe {node.get("frameId", None)}')content_document = await self.get_dom_tree(target_id=iframe_document_target.get('targetId'),# TODO: experiment with this values -> not sure whether the whole cross origin iframe should be ALWAYS included as soon as some part of it is visible or not.diff --git a/test_frame_hierarchy.py b/test_frame_hierarchy.pynew file mode 100644index 000000000..84be92d75--- /dev/null+++ b/test_frame_hierarchy.py@@ -0,0 +1,254 @@+#!/usr/bin/env python3+"""Test frame hierarchy for any URL passed as argument."""++import asyncio+import sys+from browser_use.browser import BrowserSession+from browser_use.browser.profile import BrowserProfile+from browser_use.browser.events import BrowserStartEvent++async def analyze_frame_hierarchy(url):+ """Analyze and display complete frame hierarchy for a URL."""++ profile = BrowserProfile(headless=True, user_data_dir=None)+ session = BrowserSession(browser_profile=profile)++ try:+ print(f"🚀 Starting browser...")+ await session.on_BrowserStartEvent(BrowserStartEvent())++ print(f"📍 Navigating to: {url}")+ await session._cdp_navigate(url)+ await asyncio.sleep(3)++ print("\n" + "="*80)+ print("FRAME HIERARCHY ANALYSIS")+ print("="*80)++ # Get all targets+ targets = await session.cdp_client.send.Target.getTargets()+ all_targets = targets.get('targetInfos', [])++ # Separate by type+ page_targets = [t for t in all_targets if t.get('type') == 'page']+ iframe_targets = [t for t in all_targets if t.get('type') == 'iframe']++ print(f"\n📊 Target Summary:")+ print(f" Total targets: {len(all_targets)}")+ print(f" Page targets: {len(page_targets)}")+ print(f" Iframe targets (OOPIFs): {len(iframe_targets)}")++ # Show all targets+ print(f"\n📋 All Targets:")+ for i, target in enumerate(all_targets):+ t_type = target.get('type')+ t_url = target.get('url', 'none')+ t_id = target.get('targetId', 'unknown')++ if t_type in ['page', 'iframe']:+ print(f"\n [{i+1}] Type: {t_type}")+ print(f" URL: {t_url}")+ print(f" Target ID: {t_id[:30]}...")+ print(f" Attached: {target.get('attached', False)}")++ # Get main page frame tree+ main_target = next((t for t in page_targets if url in t.get('url', '')), page_targets[0] if page_targets else None)++ if main_target:+ print(f"\n📐 Main Page Frame Tree:")+ print(f" Target: {main_target['url']}")+ print(f" Target ID: {main_target['targetId'][:30]}...")++ s = await session.cdp_client.send.Target.attachToTarget(+ params={'targetId': main_target['targetId'], 'flatten': True}+ )+ sid = s['sessionId']++ try:+ await session.cdp_client.send.Page.enable(session_id=sid)+ tree = await session.cdp_client.send.Page.getFrameTree(session_id=sid)++ print("\n Frame Tree Structure:")++ def print_tree(node, indent=0, parent_id=None):+ frame = node['frame']+ frame_id = frame.get('id', 'unknown')+ frame_url = frame.get('url', 'none')++ prefix = " " * indent + ("└─ " if indent > 0 else "")+ print(f"{prefix}Frame: {frame_url}")+ print(f"{' ' * (indent+1)}ID: {frame_id[:30]}...")++ if parent_id:+ print(f"{' ' * (indent+1)}Parent: {parent_id[:30]}...")++ # Check cross-origin status+ cross_origin = frame.get('crossOriginIsolatedContextType', 'unknown')+ if cross_origin != 'NotIsolated':+ print(f"{' ' * (indent+1)}⚠️ Cross-Origin: {cross_origin}")++ # Process children+ for child in node.get('childFrames', []):+ print_tree(child, indent + 1, frame_id)++ print_tree(tree['frameTree'])++ finally:+ await session.cdp_client.send.Target.detachFromTarget(params={'sessionId': sid})++ # Show iframe target trees+ if iframe_targets:+ print(f"\n🔸 OOPIF Target Frame Trees:")++ for iframe_target in iframe_targets:+ print(f"\n OOPIF Target: {iframe_target['url']}")+ print(f" Target ID: {iframe_target['targetId'][:30]}...")++ s = await session.cdp_client.send.Target.attachToTarget(+ params={'targetId': iframe_target['targetId'], 'flatten': True}+ )+ sid = s['sessionId']++ try:+ await session.cdp_client.send.Page.enable(session_id=sid)+ tree = await session.cdp_client.send.Page.getFrameTree(session_id=sid)++ frame = tree['frameTree']['frame']+ print(f" Frame ID: {frame.get('id', 'unknown')[:30]}...")+ print(f" Frame URL: {frame.get('url', 'none')}")+ print(f" ⚠️ This frame runs in a separate process (OOPIF)")++ except Exception as e:+ print(f" Error: {e}")+ finally:+ await session.cdp_client.send.Target.detachFromTarget(params={'sessionId': sid})++ # Now show unified view from get_all_frames+ print("\n" + "="*80)+ print("UNIFIED FRAME HIERARCHY (get_all_frames method)")+ print("="*80)++ all_frames, target_sessions = await session.get_all_frames()++ # Clean up sessions+ for tid, sess_id in target_sessions.items():+ try:+ await session.cdp_client.send.Target.detachFromTarget(params={'sessionId': sess_id})+ except:+ pass++ print(f"\n📊 Frame Statistics:")+ print(f" Total frames discovered: {len(all_frames)}")++ # Separate root and child frames+ root_frames = []+ child_frames = []++ for frame_id, frame_info in all_frames.items():+ if not frame_info.get('parentFrameId'):+ root_frames.append((frame_id, frame_info))+ else:+ child_frames.append((frame_id, frame_info))++ print(f" Root frames: {len(root_frames)}")+ print(f" Child frames: {len(child_frames)}")++ # Display all frames with details+ print(f"\n📋 All Frames:")++ for i, (frame_id, frame_info) in enumerate(all_frames.items()):+ url = frame_info.get('url', 'none')+ parent = frame_info.get('parentFrameId')+ target_id = frame_info.get('frameTargetId', 'unknown')+ is_cross = frame_info.get('isCrossOrigin', False)++ print(f"\n [{i+1}] Frame URL: {url}")+ print(f" Frame ID: {frame_id[:30]}...")+ print(f" Parent Frame ID: {parent[:30] + '...' if parent else 'None (ROOT)'}")+ print(f" Target ID: {target_id[:30]}...")+ print(f" Cross-Origin: {is_cross}")++ # Highlight problems+ if not parent and 'v0-simple-landing' in url:+ print(f" ❌ PROBLEM: Cross-origin frame incorrectly marked as root!")+ elif not parent and url != 'about:blank' and url not in ['chrome://newtab/', 'about:blank']:+ # Check if this should be the main frame+ if any(url in t.get('url', '') for t in page_targets):+ print(f" ✅ Correctly identified as root frame")++ if is_cross:+ print(f" 🔸 This is a cross-origin frame (OOPIF)")++ # Show parent-child relationships+ print(f"\n🌳 Frame Relationships:")++ # Build a tree structure+ def print_frame_tree(frame_id, frame_info, indent=0, visited=None):+ if visited is None:+ visited = set()++ if frame_id in visited:+ return+ visited.add(frame_id)++ url = frame_info.get('url', 'none')+ prefix = " " * indent + ("└─ " if indent > 0 else "")++ print(f"{prefix}{url[:60]}...")+ print(f"{' ' * (indent+1)}[{frame_id[:20]}...]")++ # Find children+ for child_id, child_info in all_frames.items():+ if child_info.get('parentFrameId') == frame_id:+ print_frame_tree(child_id, child_info, indent + 1, visited)++ # Print trees starting from roots+ for frame_id, frame_info in root_frames:+ print(f"\n Tree starting from root:")+ print_frame_tree(frame_id, frame_info)++ print("\n" + "="*80)+ print("✅ Analysis complete!")+ print("="*80)++ except Exception as e:+ print(f"❌ Error: {e}")+ import traceback+ traceback.print_exc()+ finally:+ # Stop the CDP client first before killing the browser+ print("\n🛑 Shutting down...")++ # Close CDP connection first while browser is still alive+ if session._cdp_client:+ try:+ await session._cdp_client.stop()+ except:+ pass # Ignore errors if already disconnected++ # Then stop the browser process+ from browser_use.browser.events import BrowserStopEvent+ stop_event = session.event_bus.dispatch(BrowserStopEvent())+ try:+ await asyncio.wait_for(stop_event, timeout=2.0)+ except asyncio.TimeoutError:+ print("⚠️ Browser stop timed out")++def main():+ if len(sys.argv) != 2:+ print("Usage: python test_frame_hierarchy.py <URL>")+ print("\nExample URLs to test:")+ print(" https://v0-website-with-clickable-elements.vercel.app/nested-iframe")+ print(" https://v0-website-with-clickable-elements.vercel.app/cross-origin")+ print(" https://v0-website-with-clickable-elements.vercel.app/shadow-dom")+ sys.exit(1)++ url = sys.argv[1]+ asyncio.run(analyze_frame_hierarchy(url))++ # Ensure clean exit+ print("✅ Script completed")+ sys.exit(0)++if __name__ == "__main__":+ main()\ No newline at end of file