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 nav
Nick Sweeting50be4c3a94f0
diff --git a/browser_use/browser/aboutblank_watchdog.py b/browser_use/browser/aboutblank_watchdog.pyindex 8dd7c6924..681b31ebe 100644--- a/browser_use/browser/aboutblank_watchdog.py+++ b/browser_use/browser/aboutblank_watchdog.py@@ -1,11 +1,10 @@"""About:blank watchdog for managing about:blank tabs with DVD screensaver."""-from typing import TYPE_CHECKING, Any, ClassVar+from typing import TYPE_CHECKING, ClassVarfrom bubus import BaseEventfrom pydantic import PrivateAttr-from browser_use.browser.crash_watchdog import CrashWatchdogfrom browser_use.browser.events import (AboutBlankDVDScreensaverShownEvent,BrowserStopEvent,@@ -70,7 +69,9 @@ class AboutBlankWatchdog(BaseWatchdog):# Use _cdp_get_all_pages for quick check without fetching titlespage_targets = await self.browser_session._cdp_get_all_pages()if len(page_targets) <= 1:- self.logger.info('[AboutBlankWatchdog] Last tab closing, creating new about:blank tab to avoid closing entire browser')+ self.logger.info(+ '[AboutBlankWatchdog] Last tab closing, creating new about:blank tab to avoid closing entire browser'+ )# Create the animation tab since no tabs should remainnavigate_event = self.event_bus.dispatch(NavigateToUrlEvent(url='about:blank', new_tab=True))await navigate_event@@ -89,10 +90,10 @@ class AboutBlankWatchdog(BaseWatchdog):try:# For quick checks, just get page targets without titles to reduce noisepage_targets = await self.browser_session._cdp_get_all_pages()-+# Only get full tabs info if we actually need to check titlestabs_info = None-+# For AboutBlankWatchdog, we only care about tab count not titles# Only get full tabs info if we actually have animation tabs to checkif len(page_targets) == 0:@@ -100,7 +101,7 @@ class AboutBlankWatchdog(BaseWatchdog):else:# Skip the expensive get_tabs_info call - we just need tab counttabs_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 = []@@ -140,7 +141,7 @@ class AboutBlankWatchdog(BaseWatchdog):for page_target in page_targets:target_id = page_target['targetId']url = page_target['url']-+# Only target about:blank pages specificallyif url == 'about:blank':await self._show_dvd_screensaver_loading_animation_cdp(target_id, browser_session_id)@@ -159,7 +160,7 @@ class AboutBlankWatchdog(BaseWatchdog):params={'targetId': target_id, 'flatten': True})session_id = session['sessionId']-+# Inject the DVD screensaver scriptscript = f"""(function(browser_session_label) {{@@ -284,19 +285,15 @@ class AboutBlankWatchdog(BaseWatchdog):animate();}})('{browser_session_label}');"""-- await self.browser_session.cdp_client.send.Runtime.evaluate(- params={'expression': script},- session_id=session_id- )-++ await self.browser_session.cdp_client.send.Runtime.evaluate(params={'expression': script}, session_id=session_id)+# Detach from targetawait self.browser_session.cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})-+# Dispatch eventtab_index = await self.browser_session.get_tab_index(target_id)self.event_bus.dispatch(AboutBlankDVDScreensaverShownEvent(tab_index=tab_index))-+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.pyindex 1cd838bf1..dfdf173f1 100644--- a/browser_use/browser/crash_watchdog.py+++ b/browser_use/browser/crash_watchdog.py@@ -2,7 +2,7 @@import asyncioimport time-from typing import TYPE_CHECKING, Any, ClassVar+from typing import TYPE_CHECKING, ClassVarimport psutilfrom bubus import BaseEvent@@ -71,17 +71,15 @@ class CrashWatchdog(BaseWatchdog):"""Set up crash monitoring for a specific target using CDP."""try:cdp_client = self.browser_session.cdp_client-+# Attach to target and enable domains- 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']self._cdp_sessions[target_id] = session_id-+# Enable network domain for request trackingawait cdp_client.send.Network.enable(session_id=session_id)-+# Set up network event handlersdef on_request_will_be_sent(event):# Create and track the task@@ -89,25 +87,25 @@ class CrashWatchdog(BaseWatchdog):self._cdp_event_tasks.add(task)# Remove from set when donetask.add_done_callback(lambda t: self._cdp_event_tasks.discard(t))-+def on_response_received(event):self._on_response_cdp(event)-+def on_loading_failed(event):self._on_request_failed_cdp(event)-+def on_loading_finished(event):self._on_request_finished_cdp(event)-+# Register event handlerscdp_client.on('Network.requestWillBeSent', on_request_will_be_sent, session_id=session_id)cdp_client.on('Network.responseReceived', on_response_received, session_id=session_id)cdp_client.on('Network.loadingFailed', on_loading_failed, session_id=session_id)cdp_client.on('Network.loadingFinished', on_loading_finished, session_id=session_id)-+# Enable Inspector domain for crash detectionawait cdp_client.send.Inspector.enable(session_id=session_id)-+# Set up crash handlerdef on_target_crashed(event):# Create and track the task@@ -115,15 +113,15 @@ class CrashWatchdog(BaseWatchdog):self._cdp_event_tasks.add(task)# Remove from set when donetask.add_done_callback(lambda t: self._cdp_event_tasks.discard(t))-+cdp_client.on('Inspector.targetCrashed', on_target_crashed, session_id=session_id)-+# Get target info for loggingtargets = await cdp_client.send.Target.getTargets()target_info = next((t for t in targets['targetInfos'] if t['targetId'] == target_id), None)if target_info:self.logger.debug(f'[CrashWatchdog] Added target to monitoring: {target_info.get("url", "unknown")}')-+except Exception as e:self.logger.warning(f'[CrashWatchdog] Failed to attach to target {target_id}: {e}')@@ -131,7 +129,7 @@ class CrashWatchdog(BaseWatchdog):"""Track new network request from CDP event."""request_id = event.get('requestId', '')request = event.get('request', {})-+self._active_requests[request_id] = NetworkRequestTracker(request_id=request_id,start_time=time.time(),@@ -155,7 +153,9 @@ class CrashWatchdog(BaseWatchdog):request_id = event.get('requestId', '')if request_id in self._active_requests:elapsed = time.time() - self._active_requests[request_id].start_time- self.logger.debug(f'[CrashWatchdog] Request failed after {elapsed:.2f}s: {self._active_requests[request_id].url[:50]}...')+ self.logger.debug(+ f'[CrashWatchdog] Request failed after {elapsed:.2f}s: {self._active_requests[request_id].url[:50]}...'+ )del self._active_requests[request_id]def _on_request_finished_cdp(self, event: dict) -> None:@@ -169,7 +169,7 @@ class CrashWatchdog(BaseWatchdog):cdp_client = self.browser_session.cdp_clienttargets = await cdp_client.send.Target.getTargets()target_info = next((t for t in targets['targetInfos'] if t['targetId'] == target_id), None)-+target_url = target_info.get('url', 'unknown') if target_info else 'unknown'self.logger.error(f'[CrashWatchdog] Target crashed: {target_url}')@@ -209,29 +209,25 @@ class CrashWatchdog(BaseWatchdog):# Set up CDP session for browser-level crash detectiontry:cdp_client = self.browser_session.cdp_client-+# Enable browser-level crash detection# Note: Browser domain might not be available in all contextstry:await cdp_client.send.Browser.getVersion() # Test if Browser domain is available-+# Set up browser crash handlerdef on_browser_crash(event):self.logger.error('[CrashWatchdog] Browser crash detected via CDP')self.event_bus.dispatch(- BrowserErrorEvent(- error_type='BrowserCrash',- message='Browser process crashed',- details=event- )+ BrowserErrorEvent(error_type='BrowserCrash', message='Browser process crashed', details=event))-+# Note: Browser.crash event might not exist, using Inspector.targetCrashed insteadself.logger.debug('[CrashWatchdog] π₯ CDP crash detection enabled')except Exception:# Browser domain not available, rely on target-level monitoringpass-+except Exception as e:self.logger.warning(f'[CrashWatchdog] Failed to set up CDP crash detection: {e}')@@ -328,7 +324,7 @@ class CrashWatchdog(BaseWatchdog):cdp_client = self.browser_session.cdp_client# Try a simple CDP command to check connectionawait asyncio.wait_for(cdp_client.send.Target.getTargets(), timeout=2.0)- except (asyncio.TimeoutError, Exception) as e:+ except (TimeoutError, Exception) as e:self.logger.error(f'[CrashWatchdog] Browser connection check failed: {e}')self.event_bus.dispatch(BrowserErrorEvent(error_type='BrowserDisconnected', message='Browser disconnected unexpectedly', details={})@@ -360,18 +356,18 @@ class CrashWatchdog(BaseWatchdog):try:targets = await cdp_client.send.Target.getTargets()target_infos = targets.get('targetInfos', [])-+# Only check page-type targetstarget_list = [t for t in target_infos if t.get('type') == 'page']-+for target in target_list:target_id = target['targetId']target_url = target.get('url', '')-+# Skip new tab pagesif self._is_new_tab_page(target_url):continue-+# Check if target is still attached/alivetry:# Check responsiveness occasionally to avoid overhead@@ -412,23 +408,16 @@ class CrashWatchdog(BaseWatchdog):session_id = Nonetry:cdp_client = self.browser_session.cdp_client-+# Attach to target if not already attachedif target_id not in self._cdp_sessions:- 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']else:session_id = self._cdp_sessions[target_id]-+# Try to evaluate simple JavaScript- eval_task = asyncio.create_task(- cdp_client.send.Runtime.evaluate(- params={'expression': '1'},- session_id=session_id- )- )+ eval_task = asyncio.create_task(cdp_client.send.Runtime.evaluate(params={'expression': '1'}, session_id=session_id))done, pending = await asyncio.wait([eval_task], timeout=timeout)if eval_task in done:@@ -452,7 +441,7 @@ class CrashWatchdog(BaseWatchdog):await eval_taskexcept (asyncio.CancelledError, Exception):pass-+# Detach if we attached just for this checkif session_id and target_id not in self._cdp_sessions:try:@@ -487,24 +476,22 @@ class CrashWatchdog(BaseWatchdog):"""Trigger a target crash for testing."""try:cdp_client = self.browser_session.cdp_client-+# Get target info for loggingtargets = await cdp_client.send.Target.getTargets()target_info = next((t for t in targets['targetInfos'] if t['targetId'] == target_id), None)target_url = target_info.get('url', 'unknown') if target_info else 'unknown'-+self.logger.warning(f'[CrashWatchdog] Triggering target crash for testing on: {target_url}')-+# Attach to target- 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']-+# Crash the targetawait cdp_client.send.Page.crash(session_id=session_id)-+# Detachawait cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})except Exception as e:- self.logger.error(f'[CrashWatchdog] Failed to trigger target crash: {e}')\ No newline at end of file+ self.logger.error(f'[CrashWatchdog] Failed to trigger target crash: {e}')diff --git a/browser_use/browser/dom_watchdog.py b/browser_use/browser/dom_watchdog.pyindex a07bcf671..b3373c786 100644--- a/browser_use/browser/dom_watchdog.py+++ b/browser_use/browser/dom_watchdog.py@@ -63,7 +63,7 @@ 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 pathsself.logger.debug('Getting tabs info...')tabs_info = await self.browser_session.get_tabs_info()diff --git a/browser_use/browser/downloads_watchdog.py b/browser_use/browser/downloads_watchdog.pyindex 1881f6088..93b6f77df 100644--- a/browser_use/browser/downloads_watchdog.py+++ b/browser_use/browser/downloads_watchdog.py@@ -86,7 +86,7 @@ class DownloadsWatchdog(BaseWatchdog):if self._cdp_event_tasks:await asyncio.gather(*self._cdp_event_tasks, return_exceptions=True)self._cdp_event_tasks.clear()-+# Clean up CDP sessionif self._download_cdp_session:try:@@ -96,7 +96,7 @@ class DownloadsWatchdog(BaseWatchdog):passself._download_cdp_session = Noneself._download_cdp_session_setup = False-+# Clear other stateself._targets_with_listeners.clear()self._active_downloads.clear()@@ -141,17 +141,17 @@ 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-+# Set download behavior to allow downloads and enable eventsdownloads_path = self.browser_session.browser_profile.downloads_pathawait cdp_client.send.Browser.setDownloadBehavior(params={- 'behavior': 'allow',+ 'behavior': 'allow','downloadPath': str(downloads_path), # Convert Path to string- 'eventsEnabled': True+ 'eventsEnabled': True,})-+# Register download event handlersdef download_will_begin_handler(event: dict, session_id: str | None):self.logger.info(f'[DownloadsWatchdog] Download will begin: {event}')@@ -160,7 +160,7 @@ class DownloadsWatchdog(BaseWatchdog):self._cdp_event_tasks.add(task)# Remove from set when donetask.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 completeif event.get('state') == 'completed':@@ -169,11 +169,11 @@ class DownloadsWatchdog(BaseWatchdog):self.logger.info(f'[DownloadsWatchdog] Download completed: {file_path}')# Track the downloadself._track_download(file_path)-+# Register the handlers with CDPcdp_client.register.Browser.downloadWillBegin(download_will_begin_handler)cdp_client.register.Browser.downloadProgress(download_progress_handler)-+self._download_cdp_session_setup = Trueself.logger.debug('[DownloadsWatchdog] Set up CDP download listeners')@@ -183,10 +183,10 @@ 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"""@@ -196,15 +196,18 @@ class DownloadsWatchdog(BaseWatchdog):if path.exists():file_size = path.stat().st_sizeself.logger.info(f'[DownloadsWatchdog] Tracked download: {path.name} ({file_size} bytes)')-+# Dispatch download eventfrom 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- ))++ 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:diff --git a/browser_use/browser/local_browser_watchdog.py b/browser_use/browser/local_browser_watchdog.pyindex e02957256..037a43587 100644--- a/browser_use/browser/local_browser_watchdog.py+++ b/browser_use/browser/local_browser_watchdog.py@@ -244,19 +244,19 @@ class LocalBrowserWatchdog(BaseWatchdog):try:# Try graceful shutdown firstprocess.terminate()-+# Use async wait instead of blocking waitfor _ in range(50): # Wait up to 5 seconds (50 * 0.1)if not process.is_running():returnawait asyncio.sleep(0.1)-+# If still running after 5 seconds, force killif process.is_running():process.kill()# Give it a moment to dieawait asyncio.sleep(0.1)-+except psutil.NoSuchProcess:# Process already gonepassdiff --git a/browser_use/browser/navigation_watchdog.py b/browser_use/browser/navigation_watchdog.pyindex 05de8c2f2..49672c0dd 100644--- a/browser_use/browser/navigation_watchdog.py+++ b/browser_use/browser/navigation_watchdog.py@@ -499,24 +499,23 @@ class NavigationWatchdog(BaseWatchdog):# Get all targets and filter for valid page/tab targetsall_targets = await self.browser_session.cdp_client.send.Target.getTargets()targets = [- t for t in all_targets.get('targetInfos', [])+ 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:# Set initial focus to first target BEFORE dispatching eventsself.browser_session.current_target_id = targets[0]['targetId']-+# Dispatch TabCreatedEvent for all initial pages so watchdogs can process themfrom 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- ))-+ 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.browser_session.current_target_id)diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex cdc09eddf..cec5f4bf8 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -3,7 +3,7 @@import asyncioimport loggingfrom pathlib import Path-from typing import TYPE_CHECKING, Any, Self+from typing import TYPE_CHECKING, Anyfrom bubus import EventBusfrom bubus.helpers import retry@@ -159,7 +159,7 @@ class BrowserSession(BaseModel):async def on_BrowserStartEvent(self, event: BrowserStartEvent) -> dict[str, str]:"""Handle browser start request.-+Returns:Dict with 'cdp_url' key containing the CDP URL"""@@ -191,7 +191,7 @@ class BrowserSession(BaseModel):# Notify that browser is connected (single place)self.event_bus.dispatch(BrowserConnectedEvent(cdp_url=self.cdp_url))-+# Return the CDP URL for other componentsreturn {'cdp_url': self.cdp_url}@@ -313,7 +313,7 @@ class BrowserSession(BaseModel):async def setup_browser_via_cdp_url(self) -> None:"""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."""@@ -351,8 +351,13 @@ class BrowserSession(BaseModel):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)]+ 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@@ -361,7 +366,7 @@ class BrowserSession(BaseModel):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+ # Redirect chrome://newtab to about:blank to avoid JS issues preventing driving chrome://newtabtarget_id = target['targetId']self.logger.info(f'π Redirecting {target_url} to about:blank for target {target_id}')try:@@ -370,9 +375,7 @@ class BrowserSession(BaseModel):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.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}')@@ -393,9 +396,7 @@ class BrowserSession(BaseModel):# Enable Network domain on the target session for cookie accesstry:# Attach to the target to enable Network domain- 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']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]}...')@@ -403,7 +404,7 @@ class BrowserSession(BaseModel):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 connectionself.logger.error(f'β FATAL: Failed to setup CDP connection: {e}')@@ -498,7 +499,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']@@ -547,7 +548,7 @@ class BrowserSession(BaseModel):index=i,)tabs.append(tab_info)-+return tabs# DOM element methods@@ -855,9 +856,11 @@ class BrowserSession(BaseModel):for target in targets['targetInfos']:# 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):+ 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 frameframes = await self.frames_by_target(target['targetId'])if frame_id in frames:@@ -962,7 +965,7 @@ class BrowserSession(BaseModel):# Skip invalid targetsif not self._is_valid_target(target):continue-+if target['type'] != 'page':continue@@ -1248,8 +1251,7 @@ class BrowserSession(BaseModel):"""Get all browser pages/tabs using CDP Target.getTargets."""targets = await self.cdp_client.send.Target.getTargets()# 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')]+ 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."""@@ -1266,22 +1268,20 @@ class BrowserSession(BaseModel):async def _cdp_get_cookies(self, urls: list[str] | None = None) -> list[dict]:"""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 = 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 enabledawait self.cdp_client.send.Network.enable(session_id=session_id)-+# Get cookiesparams = {'urls': urls} if urls else {}result = await self.cdp_client.send.Network.getCookies(params=params, session_id=session_id)@@ -1294,17 +1294,15 @@ class BrowserSession(BaseModel):"""Set cookies using CDP Network.setCookies."""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 = 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 enabledawait self.cdp_client.send.Network.enable(session_id=session_id)-+# Set cookiesawait self.cdp_client.send.Network.setCookies(params={'cookies': cookies}, session_id=session_id)finally:@@ -1315,17 +1313,15 @@ class BrowserSession(BaseModel):"""Clear all cookies using CDP 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 = 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 enabledawait self.cdp_client.send.Network.enable(session_id=session_id)-+# Clear cookiesawait self.cdp_client.send.Network.clearBrowserCookies(session_id=session_id)finally:@@ -1336,17 +1332,15 @@ class BrowserSession(BaseModel):"""Set extra HTTP headers using CDP Network.setExtraHTTPHeaders."""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 = 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 enabledawait self.cdp_client.send.Network.enable(session_id=session_id)-+# Set extra headersawait self.cdp_client.send.Network.setExtraHTTPHeaders(params={'headers': headers}, session_id=session_id)finally:@@ -1415,7 +1409,17 @@ 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, 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:+ 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:@@ -1479,7 +1483,9 @@ class BrowserSession(BaseModel):continue# 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):+ 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@@ -1508,7 +1514,7 @@ class BrowserSession(BaseModel):# For iframe targets, check if the frame has a parentId field# This indicates it's an OOPIF with a parent in another targetactual_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: id, url, parentId, etc.diff --git a/browser_use/browser/storage_state_watchdog.py b/browser_use/browser/storage_state_watchdog.pyindex b982a9b6c..806186e3c 100644--- a/browser_use/browser/storage_state_watchdog.py+++ b/browser_use/browser/storage_state_watchdog.py@@ -120,7 +120,7 @@ class StorageStateWatchdog(BaseWatchdog):def _setup_target_monitoring(self, target_id: str) -> None:"""Set up storage change monitoring for a target.-+Note: CDP event listeners for cookie changes would need to be implementedvia Network.responseReceivedExtraInfo events."""@@ -129,7 +129,7 @@ class StorageStateWatchdog(BaseWatchdog):async def _check_for_cookie_changes_cdp(self, event: dict) -> None:"""Check if a CDP network event indicates cookie changes.-+This would be called by Network.responseReceivedExtraInfo eventsif we set up CDP event listeners."""@@ -289,7 +289,9 @@ class StorageStateWatchdog(BaseWatchdog):window.sessionStorage.setItem({json.dumps(item['name'])}, {json.dumps(item['value'])});"""await self.browser_session._cdp_add_init_script(script)- self.logger.info(f'[StorageStateWatchdog] Applied localStorage/sessionStorage from {len(storage["origins"])} origins')+ self.logger.info(+ f'[StorageStateWatchdog] Applied localStorage/sessionStorage from {len(storage["origins"])} origins'+ )self.event_bus.dispatch(StorageStateLoadedEvent(diff --git a/browser_use/controller/service.py b/browser_use/controller/service.pyindex b30362bd8..babca906c 100644--- a/browser_use/controller/service.py+++ b/browser_use/controller/service.py@@ -2,34 +2,26 @@ import asyncioimport enumimport jsonimport logging-import os-import re-from typing import Generic, TypeVar, cast+from typing import Generic, TypeVartry:from lmnr import Laminar # type: ignoreexcept ImportError:Laminar = None # type: ignore-from bubus.helpers import retryfrom pydantic import BaseModelfrom browser_use.agent.views import ActionModel, ActionResultfrom browser_use.browser import BrowserSessionfrom browser_use.browser.events import (ClickElementEvent,- NavigateToUrlEvent,+ CloseTabEvent,GoBackEvent,+ NavigateToUrlEvent,SwitchTabEvent,- CloseTabEvent,TypeTextEvent,- UploadFileEvent,- ScrollEvent,- SendKeysEvent,- ScrollToTextEvent,)from browser_use.browser.views import BrowserErrorfrom browser_use.controller.registry.service import Registry-from browser_use.dom.views import EnhancedDOMTreeNodefrom browser_use.controller.views import (ClickElementAction,CloseTabAction,@@ -37,16 +29,12 @@ from browser_use.controller.views import (GoToUrlAction,InputTextAction,NoParamsAction,- ScrollAction,SearchGoogleAction,- SendKeysAction,StructuredOutputAction,SwitchTabAction,- UploadFileAction,)from browser_use.filesystem.file_system import FileSystemfrom browser_use.llm.base import BaseChatModel-from browser_use.llm.messages import UserMessagefrom browser_use.observability import observe_debugfrom browser_use.utils import time_execution_sync@@ -84,7 +72,7 @@ class Controller(Generic[Context]):event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url=search_url,- new_tab=True # Always use new tab for Google searches+ new_tab=True, # Always use new tab for Google searches))await event@@ -101,28 +89,23 @@ class Controller(Generic[Context]):async def go_to_url(params: GoToUrlAction, browser_session: BrowserSession):try:# Dispatch navigation event- event = browser_session.event_bus.dispatch(- NavigateToUrlEvent(- url=params.url,- new_tab=params.new_tab- )- )+ event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url=params.url, new_tab=params.new_tab))await event-+if params.new_tab:memory = f'Opened new tab with URL {params.url}'msg = f'π Opened new tab with url {params.url}'else:memory = f'Navigated to {params.url}'msg = f'π {memory}'-+logger.info(msg)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 debuggingbrowser_session.logger.error(f'β Navigation failed: {error_msg}')-+# Check if it's specifically a RuntimeError about CDP clientif isinstance(e, RuntimeError) and 'CDP client not initialized' in error_msg:browser_session.logger.error('β Browser connection failed - CDP client not properly initialized')@@ -176,18 +159,14 @@ class Controller(Generic[Context]):# Look up the node from the selector mapnode = await browser_session.get_element_by_index(params.index)if node is None:- raise ValueError(f"Element index {params.index} not found in DOM")-+ raise ValueError(f'Element index {params.index} not found in DOM')+# Dispatch click event with nodeevent = browser_session.event_bus.dispatch(- ClickElementEvent(- node=node,- expect_download=params.expect_download,- new_tab=params.new_tab- )+ ClickElementEvent(node=node, expect_download=params.expect_download, new_tab=params.new_tab))await event-+# Get the result if any (e.g., download path)result = await event.event_result()if result:@@ -198,7 +177,7 @@ class Controller(Generic[Context]):msg = f'π±οΈ Clicked element with index {params.index}'else:msg = f'π±οΈ Clicked element with index {params.index}'-+logger.info(msg)return ActionResult(extracted_content=msg, include_in_memory=True, long_term_memory=msg)@@ -210,15 +189,10 @@ class Controller(Generic[Context]):# Look up the node from the selector mapnode = await browser_session.get_element_by_index(params.index)if node is None:- raise ValueError(f"Element index {params.index} not found in DOM")-+ raise ValueError(f'Element index {params.index} not found in DOM')+# Dispatch type text event with node- event = browser_session.event_bus.dispatch(- TypeTextEvent(- node=node,- text=params.text- )- )+ event = browser_session.event_bus.dispatch(TypeTextEvent(node=node, text=params.text))await eventif not has_sensitive_data:@@ -265,11 +239,9 @@ class Controller(Generic[Context]):@self.registry.action('Switch tab', param_model=SwitchTabAction)async def switch_tab(params: SwitchTabAction, browser_session: BrowserSession):# Dispatch switch tab event- event = browser_session.event_bus.dispatch(- SwitchTabEvent(tab_index=params.page_id)- )+ event = browser_session.event_bus.dispatch(SwitchTabEvent(tab_index=params.page_id))await event-+msg = f'π Switched to tab #{params.page_id}'logger.info(msg)return ActionResult(@@ -279,11 +251,9 @@ class Controller(Generic[Context]):@self.registry.action('Close an existing tab', param_model=CloseTabAction)async def close_tab(params: CloseTabAction, browser_session: BrowserSession):# Dispatch close tab event- event = browser_session.event_bus.dispatch(- CloseTabEvent(tab_index=params.page_id)- )+ event = browser_session.event_bus.dispatch(CloseTabEvent(tab_index=params.page_id))await event-+msg = f'β Closed tab #{params.page_id}'logger.info(msg)return ActionResult(@@ -296,674 +266,675 @@ class Controller(Generic[Context]):# TODO: Refactor to use events instead of direct page access# This action is temporarily disabled as it needs refactoring to use events-# @self.registry.action(-# """Extract structured, semantic data (e.g. product description, price, all information about XYZ) from the current webpage based on a textual query.-# This tool takes the entire markdown of the page and extracts the query from it.-# Set extract_links=True ONLY if your query requires extracting links/URLs from the page.-# Only use this for specific queries for information retrieval from the page. Don't use this to get interactive elements - the tool does not see HTML elements, only the markdown.-# """,-# )-# async def extract_structured_data(-# query: str,-# extract_links: bool,-# page: Page,-# page_extraction_llm: BaseChatModel,-# file_system: FileSystem,-# ):-# from functools import partial--# import markdownify--# strip = []--# if not extract_links:-# strip = ['a', 'img']--# # Run markdownify in a thread pool to avoid blocking the event loop-# loop = asyncio.get_event_loop()--# # Aggressive timeout for page content-# try:-# page_html_result = await asyncio.wait_for(page.content(), timeout=10.0) # 5 second aggressive timeout-# except TimeoutError:-# raise RuntimeError('Page content extraction timed out after 5 seconds')-# except Exception as e:-# raise RuntimeError(f"Couldn't extract page content: {e}")--# page_html = page_html_result--# markdownify_func = partial(markdownify.markdownify, strip=strip)--# try:-# content = await asyncio.wait_for(-# loop.run_in_executor(None, markdownify_func, page_html), timeout=5.0-# ) # 5 second aggressive timeout-# except Exception as e:-# logger.warning(f'Markdownify failed: {type(e).__name__}')-# raise RuntimeError(f'Could not convert html to markdown: {type(e).__name__}')--# # manually append iframe text into the content so it's readable by the LLM (includes cross-origin iframes)-# for iframe in page.frames:-# try:-# await iframe.wait_for_load_state(timeout=1000) # 1 second aggressive timeout for iframe load-# except Exception:-# pass--# if iframe.url != page.url and not iframe.url.startswith('data:') and not iframe.url.startswith('about:'):-# content += f'\n\nIFRAME {iframe.url}:\n'-# # Run markdownify in a thread pool for iframe content as well-# try:-# # Aggressive timeouts for iframe content-# iframe_html = await asyncio.wait_for(iframe.content(), timeout=2.0) # 2 second aggressive timeout-# iframe_markdown = await asyncio.wait_for(-# loop.run_in_executor(None, markdownify_func, iframe_html),-# timeout=2.0, # 2 second aggressive timeout for iframe markdownify-# )-# except Exception:-# iframe_markdown = '' # Skip failed iframes-# content += iframe_markdown-# # replace multiple sequential \n with a single \n-# content = re.sub(r'\n+', '\n', content)--# # limit to 30000 characters - remove text in the middle (β15000 tokens)-# max_chars = 30000-# if len(content) > max_chars:-# logger.info(f'Content is too long, removing middle {len(content) - max_chars} characters')-# content = (-# content[: max_chars // 2]-# + '\n... left out the middle because it was too long ...\n'-# + content[-max_chars // 2 :]-# )--# prompt = """You convert websites into structured information. Extract information from this webpage based on the query. Focus only on content relevant to the query. If-# 1. The query is vague-# 2. Does not make sense for the page-# 3. Some/all of the information is not available--# Explain the content of the page and that the requested information is not available in the page. Respond in JSON format.\nQuery: {query}\n Website:\n{page}"""-# try:-# formatted_prompt = prompt.format(query=query, page=content)-# # Aggressive timeout for LLM call-# response = await asyncio.wait_for(-# page_extraction_llm.ainvoke([UserMessage(content=formatted_prompt)]),-# timeout=120.0, # 120 second aggressive timeout for LLM call-# )--# extracted_content = f'Page Link: {page.url}\nQuery: {query}\nExtracted Content:\n{response.completion}'--# # if content is small include it to memory-# MAX_MEMORY_SIZE = 600-# if len(extracted_content) < MAX_MEMORY_SIZE:-# memory = extracted_content-# include_extracted_content_only_once = False-# else:-# # find lines until MAX_MEMORY_SIZE-# lines = extracted_content.splitlines()-# display = ''-# display_lines_count = 0-# for line in lines:-# if len(display) + len(line) < MAX_MEMORY_SIZE:-# display += line + '\n'-# display_lines_count += 1-# else:-# break-# save_result = await file_system.save_extracted_content(extracted_content)-# memory = f'Extracted content from {page.url}\n<query>{query}\n</query>\n<extracted_content>\n{display}{len(lines) - display_lines_count} more lines...\n</extracted_content>\n<file_system>{save_result}</file_system>'-# include_extracted_content_only_once = True-# logger.info(f'π {memory}')-# return ActionResult(-# extracted_content=extracted_content,-# include_extracted_content_only_once=include_extracted_content_only_once,-# long_term_memory=memory,-# )-# except TimeoutError:-# error_msg = f'LLM call timed out for query: {query}'-# logger.warning(error_msg)-# raise RuntimeError(error_msg)-# except Exception as e:-# logger.debug(f'Error extracting content: {e}')-# msg = f'π Extracted from page\n: {content}\n'-# logger.info(msg)-# raise RuntimeError(str(e))-- # @self.registry.action(- # 'Scroll the page by specified number of pages (set down=True to scroll down, down=False to scroll up, num_pages=number of pages to scroll like 0.5 for half page, 1.0 for one page, etc.). Optional index parameter to scroll within a specific element or its scroll container (works well for dropdowns and custom UI components).',- # param_model=ScrollAction,- # )- # async def scroll(params: ScrollAction, browser_session: BrowserSession):- # # Look up the node from the selector map if index is provided- # node = None- # if params.index is not None:- # node = EnhancedDOMTreeNode.from_element_index(browser_session, params.index)-- # # Dispatch scroll event with node - the complex logic is handled in the event handler- # event = browser_session.event_bus.dispatch(- # ScrollEvent(- # direction='down' if params.down else 'up',- # amount=params.num_pages, # Pass num_pages, handler will convert to pixels- # node=node- # )- # )- # await event-- # direction = 'down' if params.down else 'up'- # target = f'element {params.index}' if params.index is not None else 'the page'-- # if params.num_pages == 1.0:- # long_term_memory = f'Scrolled {direction} {target} by one page'- # else:- # long_term_memory = f'Scrolled {direction} {target} by {params.num_pages} pages'-- # msg = f'π {long_term_memory}'- # logger.info(msg)- # return ActionResult(extracted_content=msg, include_in_memory=True, long_term_memory=long_term_memory)-- # @self.registry.action(- # 'Send strings of special keys to use Playwright page.keyboard.press - examples include Escape, Backspace, Insert, PageDown, Delete, Enter, or Shortcuts such as `Control+o`, `Control+Shift+T`',- # param_model=SendKeysAction,- # )- # async def send_keys(params: SendKeysAction, browser_session: BrowserSession):- # # Dispatch send keys event- # event = browser_session.event_bus.dispatch(- # SendKeysEvent(keys=params.keys)- # )- # await event-- # msg = f'β¨οΈ Sent keys: {params.keys}'- # logger.info(msg)- # return ActionResult(extracted_content=msg, include_in_memory=True, long_term_memory=f'Sent keys: {params.keys}')- # @self.registry.action(- # description='Scroll to a text in the current page',- # )- # async def scroll_to_text(text: str, browser_session: BrowserSession): # type: ignore- # # Dispatch scroll to text event- # event = browser_session.event_bus.dispatch(- # ScrollToTextEvent(text=text)- # )- # await event-- # # Check result to see if text was found- # result = await event.event_result()- # if result and result.get('found'):- # msg = f'π Scrolled to text: {text}'- # logger.info(msg)- # return ActionResult(- # extracted_content=msg, include_in_memory=True, long_term_memory=f'Scrolled to text: {text}'- # )- # else:- # msg = f"Text '{text}' not found or not visible on page"- # logger.info(msg)- # return ActionResult(- # extracted_content=msg,- # include_in_memory=True,- # long_term_memory=f"Tried scrolling to text '{text}' but it was not found",- # )-- # # File System Actions- # @self.registry.action(- # 'Write or append content to file_name in file system. Allowed extensions are .md, .txt, .json, .csv, .pdf. For .pdf files, write the content in markdown format and it will automatically be converted to a properly formatted PDF document.'- # )- # async def write_file(- # file_name: str,- # content: str,- # file_system: FileSystem,- # append: bool = False,- # trailing_newline: bool = True,- # leading_newline: bool = False,- # ):- # if trailing_newline:- # content += '\n'- # if leading_newline:- # content = '\n' + content- # if append:- # result = await file_system.append_file(file_name, content)- # else:- # result = await file_system.write_file(file_name, content)- # logger.info(f'πΎ {result}')- # return ActionResult(extracted_content=result, include_in_memory=True, long_term_memory=result)-- # @self.registry.action(- # 'Replace old_str with new_str in file_name. old_str must exactly match the string to replace in original text. Recommended tool to mark completed items in todo.md or change specific contents in a file.'- # )- # async def replace_file_str(file_name: str, old_str: str, new_str: str, file_system: FileSystem):- # result = await file_system.replace_file_str(file_name, old_str, new_str)- # logger.info(f'πΎ {result}')- # return ActionResult(extracted_content=result, include_in_memory=True, long_term_memory=result)-- # @self.registry.action('Read file_name from file system')- # async def read_file(file_name: str, available_file_paths: list[str], file_system: FileSystem):- # if available_file_paths and file_name in available_file_paths:- # result = await file_system.read_file(file_name, external_file=True)- # else:- # result = await file_system.read_file(file_name)-- # MAX_MEMORY_SIZE = 1000- # if len(result) > MAX_MEMORY_SIZE:- # lines = result.splitlines()- # display = ''- # lines_count = 0- # for line in lines:- # if len(display) + len(line) < MAX_MEMORY_SIZE:- # display += line + '\n'- # lines_count += 1- # else:- # break- # remaining_lines = len(lines) - lines_count- # memory = f'{display}{remaining_lines} more lines...' if remaining_lines > 0 else display- # else:- # memory = result- # logger.info(f'πΎ {memory}')- # return ActionResult(- # extracted_content=result,- # include_in_memory=True,- # long_term_memory=memory,- # include_extracted_content_only_once=True,- # )-- # TODO: Refactor to use events instead of direct page/dom access- # @self.registry.action(- # description='Get all options from a native dropdown or ARIA menu',- # )- # async def get_dropdown_options(index: int, browser_session: BrowserSession) -> ActionResult:- # """Get all options from a native dropdown or ARIA menu"""- # page = await browser_session.get_current_page()- # dom_element = await browser_session.get_dom_element_by_index(index)- # if dom_element is None:- # raise Exception(f'Element index {index} does not exist - retry or use alternative actions')-- # try:- # # Frame-aware approach since we know it works- # all_options = []- # frame_index = 0-- # for frame in page.frames:- # try:- # # First check if it's a native select element- # options = await frame.evaluate(- # """- # (xpath) => {- # const element = document.evaluate(xpath, document, null,- # XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;- # if (!element) return null;-- # // Check if it's a native select element- # if (element.tagName.toLowerCase() === 'select') {- # return {- # type: 'select',- # options: Array.from(element.options).map(opt => ({- # text: opt.text, //do not trim, because we are doing exact match in select_dropdown_option- # value: opt.value,- # index: opt.index- # })),- # id: element.id,- # name: element.name- # };- # }-- # // Check if it's an ARIA menu- # if (element.getAttribute('role') === 'menu' ||- # element.getAttribute('role') === 'listbox' ||- # element.getAttribute('role') === 'combobox') {- # // Find all menu items- # const menuItems = element.querySelectorAll('[role="menuitem"], [role="option"]');- # const options = [];-- # menuItems.forEach((item, idx) => {- # // Get the text content of the menu item- # const text = item.textContent.trim();- # if (text) {- # options.push({- # text: text,- # value: text, // For ARIA menus, use text as value- # index: idx- # });- # }- # });-- # return {- # type: 'aria',- # options: options,- # id: element.id || '',- # name: element.getAttribute('aria-label') || ''- # };- # }-- # return null;- # }- # """,- # dom_element.xpath,- # )-- # if options:- # logger.debug(f'Found {options["type"]} dropdown in frame {frame_index}')- # logger.debug(f'Element ID: {options["id"]}, Name: {options["name"]}')-- # formatted_options = []- # for opt in options['options']:- # # encoding ensures AI uses the exact string in select_dropdown_option- # encoded_text = json.dumps(opt['text'])- # formatted_options.append(f'{opt["index"]}: text={encoded_text}')-- # all_options.extend(formatted_options)-- # except Exception as frame_e:- # logger.debug(f'Frame {frame_index} evaluation failed: {str(frame_e)}')-- # frame_index += 1-- # if all_options:- # msg = '\n'.join(all_options)- # msg += '\nUse the exact text string in select_dropdown_option'- # logger.info(msg)- # return ActionResult(- # extracted_content=msg,- # include_in_memory=True,- # long_term_memory=f'Found dropdown options for index {index}.',- # include_extracted_content_only_once=True,- # )- # else:- # msg = 'No options found in any frame for dropdown'- # logger.info(msg)- # return ActionResult(- # extracted_content=msg, include_in_memory=True, long_term_memory='No dropdown options found'- # )-- # except Exception as e:- # logger.error(f'Failed to get dropdown options: {str(e)}')- # msg = f'Error getting options: {str(e)}'- # logger.info(msg)- # return ActionResult(extracted_content=msg, include_in_memory=True)-- # TODO: Refactor to use events instead of direct page/dom access- # @self.registry.action(- # description='Select dropdown option or ARIA menu item for interactive element index by the text of the option you want to select',- # )- # async def select_dropdown_option(- # index: int,- # text: str,- # browser_session: BrowserSession,- # ) -> ActionResult:- # """Select dropdown option or ARIA menu item by the text of the option you want to select"""- # page = await browser_session.get_current_page()- # dom_element = await browser_session.get_dom_element_by_index(index)- # if dom_element is None:- # raise Exception(f'Element index {index} does not exist - retry or use alternative actions')-- # logger.debug(f"Attempting to select '{text}' using xpath: {dom_element.xpath}")- # logger.debug(f'Element attributes: {dom_element.attributes}')- # logger.debug(f'Element tag: {dom_element.tag_name}')-- # xpath = '//' + dom_element.xpath-- # try:- # frame_index = 0- # for frame in page.frames:- # try:- # logger.debug(f'Trying frame {frame_index} URL: {frame.url}')-- # # First check what type of element we're dealing with- # element_info_js = """- # (xpath) => {- # try {- # const element = document.evaluate(xpath, document, null,- # XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;- # if (!element) return null;-- # const tagName = element.tagName.toLowerCase();- # const role = element.getAttribute('role');-- # // Check if it's a native select- # if (tagName === 'select') {- # return {- # type: 'select',- # found: true,- # id: element.id,- # name: element.name,- # tagName: element.tagName,- # optionCount: element.options.length,- # currentValue: element.value,- # availableOptions: Array.from(element.options).map(o => o.text.trim())- # };- # }-- # // Check if it's an ARIA menu or similar- # if (role === 'menu' || role === 'listbox' || role === 'combobox') {- # const menuItems = element.querySelectorAll('[role="menuitem"], [role="option"]');- # return {- # type: 'aria',- # found: true,- # id: element.id || '',- # role: role,- # tagName: element.tagName,- # itemCount: menuItems.length,- # availableOptions: Array.from(menuItems).map(item => item.textContent.trim())- # };- # }-- # return {- # error: `Element is neither a select nor an ARIA menu (tag: ${tagName}, role: ${role})`,- # found: false- # };- # } catch (e) {- # return {error: e.toString(), found: false};- # }- # }- # """-- # element_info = await frame.evaluate(element_info_js, dom_element.xpath)-- # if element_info and element_info.get('found'):- # logger.debug(f'Found {element_info.get("type")} element in frame {frame_index}: {element_info}')-- # if element_info.get('type') == 'select':- # # Handle native select element- # # "label" because we are selecting by text- # # nth(0) to disable error thrown by strict mode- # # timeout=1000 because we are already waiting for all network events- # selected_option_values = (- # await frame.locator('//' + dom_element.xpath).nth(0).select_option(label=text, timeout=1000)- # )-- # msg = f'selected option {text} with value {selected_option_values}'- # logger.info(msg + f' in frame {frame_index}')-- # return ActionResult(- # extracted_content=msg, include_in_memory=True, long_term_memory=f"Selected option '{text}'"- # )-- # elif element_info.get('type') == 'aria':- # # Handle ARIA menu- # click_aria_item_js = """- # (params) => {- # const { xpath, targetText } = params;- # try {- # const element = document.evaluate(xpath, document, null,- # XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;- # if (!element) return {success: false, error: 'Element not found'};-- # // Find all menu items- # const menuItems = element.querySelectorAll('[role="menuitem"], [role="option"]');-- # for (const item of menuItems) {- # const itemText = item.textContent.trim();- # if (itemText === targetText) {- # // Simulate click on the menu item- # item.click();-- # // Also try dispatching a click event in case the click handler needs it- # const clickEvent = new MouseEvent('click', {- # view: window,- # bubbles: true,- # cancelable: true- # });- # item.dispatchEvent(clickEvent);-- # return {- # success: true,- # message: `Clicked menu item: ${targetText}`- # };- # }- # }-- # return {- # success: false,- # error: `Menu item with text '${targetText}' not found`- # };- # } catch (e) {- # return {success: false, error: e.toString()};- # }- # }- # """-- # result = await frame.evaluate(- # click_aria_item_js, {'xpath': dom_element.xpath, 'targetText': text}- # )-- # if result.get('success'):- # msg = result.get('message', f'Selected ARIA menu item: {text}')- # logger.info(msg + f' in frame {frame_index}')- # return ActionResult(- # extracted_content=msg,- # include_in_memory=True,- # long_term_memory=f"Selected menu item '{text}'",- # )- # else:- # logger.error(f'Failed to select ARIA menu item: {result.get("error")}')- # continue-- # elif element_info:- # logger.error(f'Frame {frame_index} error: {element_info.get("error")}')- # continue-- # except Exception as frame_e:- # logger.error(f'Frame {frame_index} attempt failed: {str(frame_e)}')- # logger.error(f'Frame type: {type(frame)}')- # logger.error(f'Frame URL: {frame.url}')-- # frame_index += 1-- # msg = f"Could not select option '{text}' in any frame"- # logger.info(msg)- # return ActionResult(extracted_content=msg, include_in_memory=True, long_term_memory=msg)-- # except Exception as e:- # msg = f'Selection failed: {str(e)}'- # logger.error(msg)- # raise BrowserError(msg)-- # @self.registry.action('Google Sheets: Get the contents of the entire sheet', domains=['https://docs.google.com'])- # async def read_sheet_contents(browser_session: BrowserSession):- # # Use send keys events to select and copy all cells- # for key in ['Enter', 'Escape', 'ControlOrMeta+A', 'ControlOrMeta+C']:- # event = browser_session.event_bus.dispatch(SendKeysEvent(keys=key))- # await event-- # # Get page to evaluate clipboard- # page = await browser_session.get_current_page()- # extracted_tsv = await page.evaluate('() => navigator.clipboard.readText()')- # return ActionResult(- # extracted_content=extracted_tsv,- # include_in_memory=True,- # long_term_memory='Retrieved sheet contents',- # include_extracted_content_only_once=True,- # )-- # @self.registry.action('Google Sheets: Get the contents of a cell or range of cells', domains=['https://docs.google.com'])- # async def read_cell_contents(cell_or_range: str, browser_session: BrowserSession):- # page = await browser_session.get_current_page()-- # await select_cell_or_range(cell_or_range=cell_or_range, page=page)-- # await page.keyboard.press('ControlOrMeta+C')- # await asyncio.sleep(0.1)- # extracted_tsv = await page.evaluate('() => navigator.clipboard.readText()')- # return ActionResult(- # extracted_content=extracted_tsv,- # include_in_memory=True,- # long_term_memory=f'Retrieved contents from {cell_or_range}',- # include_extracted_content_only_once=True,- # )-- # @self.registry.action(- # 'Google Sheets: Update the content of a cell or range of cells', domains=['https://docs.google.com']- # )- # async def update_cell_contents(cell_or_range: str, new_contents_tsv: str, browser_session: BrowserSession):- # page = await browser_session.get_current_page()-- # await select_cell_or_range(cell_or_range=cell_or_range, page=page)-- # # simulate paste event from clipboard with TSV content- # await page.evaluate(f"""- # const clipboardData = new DataTransfer();- # clipboardData.setData('text/plain', `{new_contents_tsv}`);- # document.activeElement.dispatchEvent(new ClipboardEvent('paste', {{clipboardData}}));- # """)-- # return ActionResult(- # extracted_content=f'Updated cells: {cell_or_range} = {new_contents_tsv}',- # include_in_memory=False,- # long_term_memory=f'Updated cells {cell_or_range} with {new_contents_tsv}',- # )-- # @self.registry.action('Google Sheets: Clear whatever cells are currently selected', domains=['https://docs.google.com'])- # async def clear_cell_contents(cell_or_range: str, browser_session: BrowserSession):- # page = await browser_session.get_current_page()-- # await select_cell_or_range(cell_or_range=cell_or_range, page=page)-- # await page.keyboard.press('Backspace')- # return ActionResult(- # extracted_content=f'Cleared cells: {cell_or_range}',- # include_in_memory=False,- # long_term_memory=f'Cleared cells {cell_or_range}',- # )-- # @self.registry.action('Google Sheets: Select a specific cell or range of cells', domains=['https://docs.google.com'])- # async def select_cell_or_range(cell_or_range: str, browser_session: BrowserSession):- # # Use send keys events for navigation- # for key in ['Enter', 'Escape']:- # event = browser_session.event_bus.dispatch(SendKeysEvent(keys=key))- # await event- # await asyncio.sleep(0.1)- # for key in ['Home', 'ArrowUp']:- # event = browser_session.event_bus.dispatch(SendKeysEvent(keys=key))- # await event- # await asyncio.sleep(0.1)- # event = browser_session.event_bus.dispatch(SendKeysEvent(keys='Control+G'))- # await event- # await asyncio.sleep(0.2)- # # Get page to type the cell range- # page = await browser_session.get_current_page()- # await page.keyboard.type(cell_or_range, delay=0.05)- # await asyncio.sleep(0.2)- # for key in ['Enter', 'Escape']:- # event = browser_session.event_bus.dispatch(SendKeysEvent(keys=key))- # await event- # await asyncio.sleep(0.2)- # return ActionResult(- # extracted_content=f'Selected cells: {cell_or_range}',- # include_in_memory=False,- # long_term_memory=f'Selected cells {cell_or_range}',- # )-- # @self.registry.action(- # 'Google Sheets: Fallback method to type text into (only one) currently selected cell',- # domains=['https://docs.google.com'],- # )- # async def fallback_input_into_single_selected_cell(text: str, browser_session: BrowserSession):- # # Get page to type text- # page = await browser_session.get_current_page()- # await page.keyboard.type(text, delay=0.1)- # # Use send keys for Enter and ArrowUp- # for key in ['Enter', 'ArrowUp']:- # event = browser_session.event_bus.dispatch(SendKeysEvent(keys=key))- # await event- # return ActionResult(- # extracted_content=f'Inputted text {text}',- # include_in_memory=False,- # long_term_memory=f"Inputted text '{text}' into cell",- # )+ # @self.registry.action(+ # """Extract structured, semantic data (e.g. product description, price, all information about XYZ) from the current webpage based on a textual query.+ # This tool takes the entire markdown of the page and extracts the query from it.+ # Set extract_links=True ONLY if your query requires extracting links/URLs from the page.+ # Only use this for specific queries for information retrieval from the page. Don't use this to get interactive elements - the tool does not see HTML elements, only the markdown.+ # """,+ # )+ # async def extract_structured_data(+ # query: str,+ # extract_links: bool,+ # page: Page,+ # page_extraction_llm: BaseChatModel,+ # file_system: FileSystem,+ # ):+ # from functools import partial++ # import markdownify++ # strip = []++ # if not extract_links:+ # strip = ['a', 'img']++ # # Run markdownify in a thread pool to avoid blocking the event loop+ # loop = asyncio.get_event_loop()++ # # Aggressive timeout for page content+ # try:+ # page_html_result = await asyncio.wait_for(page.content(), timeout=10.0) # 5 second aggressive timeout+ # except TimeoutError:+ # raise RuntimeError('Page content extraction timed out after 5 seconds')+ # except Exception as e:+ # raise RuntimeError(f"Couldn't extract page content: {e}")++ # page_html = page_html_result++ # markdownify_func = partial(markdownify.markdownify, strip=strip)++ # try:+ # content = await asyncio.wait_for(+ # loop.run_in_executor(None, markdownify_func, page_html), timeout=5.0+ # ) # 5 second aggressive timeout+ # except Exception as e:+ # logger.warning(f'Markdownify failed: {type(e).__name__}')+ # raise RuntimeError(f'Could not convert html to markdown: {type(e).__name__}')++ # # manually append iframe text into the content so it's readable by the LLM (includes cross-origin iframes)+ # for iframe in page.frames:+ # try:+ # await iframe.wait_for_load_state(timeout=1000) # 1 second aggressive timeout for iframe load+ # except Exception:+ # pass++ # if iframe.url != page.url and not iframe.url.startswith('data:') and not iframe.url.startswith('about:'):+ # content += f'\n\nIFRAME {iframe.url}:\n'+ # # Run markdownify in a thread pool for iframe content as well+ # try:+ # # Aggressive timeouts for iframe content+ # iframe_html = await asyncio.wait_for(iframe.content(), timeout=2.0) # 2 second aggressive timeout+ # iframe_markdown = await asyncio.wait_for(+ # loop.run_in_executor(None, markdownify_func, iframe_html),+ # timeout=2.0, # 2 second aggressive timeout for iframe markdownify+ # )+ # except Exception:+ # iframe_markdown = '' # Skip failed iframes+ # content += iframe_markdown+ # # replace multiple sequential \n with a single \n+ # content = re.sub(r'\n+', '\n', content)++ # # limit to 30000 characters - remove text in the middle (β15000 tokens)+ # max_chars = 30000+ # if len(content) > max_chars:+ # logger.info(f'Content is too long, removing middle {len(content) - max_chars} characters')+ # content = (+ # content[: max_chars // 2]+ # + '\n... left out the middle because it was too long ...\n'+ # + content[-max_chars // 2 :]+ # )++ # prompt = """You convert websites into structured information. Extract information from this webpage based on the query. Focus only on content relevant to the query. If+ # 1. The query is vague+ # 2. Does not make sense for the page+ # 3. Some/all of the information is not available++ # Explain the content of the page and that the requested information is not available in the page. Respond in JSON format.\nQuery: {query}\n Website:\n{page}"""+ # try:+ # formatted_prompt = prompt.format(query=query, page=content)+ # # Aggressive timeout for LLM call+ # response = await asyncio.wait_for(+ # page_extraction_llm.ainvoke([UserMessage(content=formatted_prompt)]),+ # timeout=120.0, # 120 second aggressive timeout for LLM call+ # )++ # extracted_content = f'Page Link: {page.url}\nQuery: {query}\nExtracted Content:\n{response.completion}'++ # # if content is small include it to memory+ # MAX_MEMORY_SIZE = 600+ # if len(extracted_content) < MAX_MEMORY_SIZE:+ # memory = extracted_content+ # include_extracted_content_only_once = False+ # else:+ # # find lines until MAX_MEMORY_SIZE+ # lines = extracted_content.splitlines()+ # display = ''+ # display_lines_count = 0+ # for line in lines:+ # if len(display) + len(line) < MAX_MEMORY_SIZE:+ # display += line + '\n'+ # display_lines_count += 1+ # else:+ # break+ # save_result = await file_system.save_extracted_content(extracted_content)+ # memory = f'Extracted content from {page.url}\n<query>{query}\n</query>\n<extracted_content>\n{display}{len(lines) - display_lines_count} more lines...\n</extracted_content>\n<file_system>{save_result}</file_system>'+ # include_extracted_content_only_once = True+ # logger.info(f'π {memory}')+ # return ActionResult(+ # extracted_content=extracted_content,+ # include_extracted_content_only_once=include_extracted_content_only_once,+ # long_term_memory=memory,+ # )+ # except TimeoutError:+ # error_msg = f'LLM call timed out for query: {query}'+ # logger.warning(error_msg)+ # raise RuntimeError(error_msg)+ # except Exception as e:+ # logger.debug(f'Error extracting content: {e}')+ # msg = f'π Extracted from page\n: {content}\n'+ # logger.info(msg)+ # raise RuntimeError(str(e))++ # @self.registry.action(+ # 'Scroll the page by specified number of pages (set down=True to scroll down, down=False to scroll up, num_pages=number of pages to scroll like 0.5 for half page, 1.0 for one page, etc.). Optional index parameter to scroll within a specific element or its scroll container (works well for dropdowns and custom UI components).',+ # param_model=ScrollAction,+ # )+ # async def scroll(params: ScrollAction, browser_session: BrowserSession):+ # # Look up the node from the selector map if index is provided+ # node = None+ # if params.index is not None:+ # node = EnhancedDOMTreeNode.from_element_index(browser_session, params.index)++ # # Dispatch scroll event with node - the complex logic is handled in the event handler+ # event = browser_session.event_bus.dispatch(+ # ScrollEvent(+ # direction='down' if params.down else 'up',+ # amount=params.num_pages, # Pass num_pages, handler will convert to pixels+ # node=node+ # )+ # )+ # await event++ # direction = 'down' if params.down else 'up'+ # target = f'element {params.index}' if params.index is not None else 'the page'++ # if params.num_pages == 1.0:+ # long_term_memory = f'Scrolled {direction} {target} by one page'+ # else:+ # long_term_memory = f'Scrolled {direction} {target} by {params.num_pages} pages'++ # msg = f'π {long_term_memory}'+ # logger.info(msg)+ # return ActionResult(extracted_content=msg, include_in_memory=True, long_term_memory=long_term_memory)++ # @self.registry.action(+ # 'Send strings of special keys to use Playwright page.keyboard.press - examples include Escape, Backspace, Insert, PageDown, Delete, Enter, or Shortcuts such as `Control+o`, `Control+Shift+T`',+ # param_model=SendKeysAction,+ # )+ # async def send_keys(params: SendKeysAction, browser_session: BrowserSession):+ # # Dispatch send keys event+ # event = browser_session.event_bus.dispatch(+ # SendKeysEvent(keys=params.keys)+ # )+ # await event++ # msg = f'β¨οΈ Sent keys: {params.keys}'+ # logger.info(msg)+ # return ActionResult(extracted_content=msg, include_in_memory=True, long_term_memory=f'Sent keys: {params.keys}')++ # @self.registry.action(+ # description='Scroll to a text in the current page',+ # )+ # async def scroll_to_text(text: str, browser_session: BrowserSession): # type: ignore+ # # Dispatch scroll to text event+ # event = browser_session.event_bus.dispatch(+ # ScrollToTextEvent(text=text)+ # )+ # await event++ # # Check result to see if text was found+ # result = await event.event_result()+ # if result and result.get('found'):+ # msg = f'π Scrolled to text: {text}'+ # logger.info(msg)+ # return ActionResult(+ # extracted_content=msg, include_in_memory=True, long_term_memory=f'Scrolled to text: {text}'+ # )+ # else:+ # msg = f"Text '{text}' not found or not visible on page"+ # logger.info(msg)+ # return ActionResult(+ # extracted_content=msg,+ # include_in_memory=True,+ # long_term_memory=f"Tried scrolling to text '{text}' but it was not found",+ # )++ # # File System Actions+ # @self.registry.action(+ # 'Write or append content to file_name in file system. Allowed extensions are .md, .txt, .json, .csv, .pdf. For .pdf files, write the content in markdown format and it will automatically be converted to a properly formatted PDF document.'+ # )+ # async def write_file(+ # file_name: str,+ # content: str,+ # file_system: FileSystem,+ # append: bool = False,+ # trailing_newline: bool = True,+ # leading_newline: bool = False,+ # ):+ # if trailing_newline:+ # content += '\n'+ # if leading_newline:+ # content = '\n' + content+ # if append:+ # result = await file_system.append_file(file_name, content)+ # else:+ # result = await file_system.write_file(file_name, content)+ # logger.info(f'πΎ {result}')+ # return ActionResult(extracted_content=result, include_in_memory=True, long_term_memory=result)++ # @self.registry.action(+ # 'Replace old_str with new_str in file_name. old_str must exactly match the string to replace in original text. Recommended tool to mark completed items in todo.md or change specific contents in a file.'+ # )+ # async def replace_file_str(file_name: str, old_str: str, new_str: str, file_system: FileSystem):+ # result = await file_system.replace_file_str(file_name, old_str, new_str)+ # logger.info(f'πΎ {result}')+ # return ActionResult(extracted_content=result, include_in_memory=True, long_term_memory=result)++ # @self.registry.action('Read file_name from file system')+ # async def read_file(file_name: str, available_file_paths: list[str], file_system: FileSystem):+ # if available_file_paths and file_name in available_file_paths:+ # result = await file_system.read_file(file_name, external_file=True)+ # else:+ # result = await file_system.read_file(file_name)++ # MAX_MEMORY_SIZE = 1000+ # if len(result) > MAX_MEMORY_SIZE:+ # lines = result.splitlines()+ # display = ''+ # lines_count = 0+ # for line in lines:+ # if len(display) + len(line) < MAX_MEMORY_SIZE:+ # display += line + '\n'+ # lines_count += 1+ # else:+ # break+ # remaining_lines = len(lines) - lines_count+ # memory = f'{display}{remaining_lines} more lines...' if remaining_lines > 0 else display+ # else:+ # memory = result+ # logger.info(f'πΎ {memory}')+ # return ActionResult(+ # extracted_content=result,+ # include_in_memory=True,+ # long_term_memory=memory,+ # include_extracted_content_only_once=True,+ # )++ # TODO: Refactor to use events instead of direct page/dom access+ # @self.registry.action(+ # description='Get all options from a native dropdown or ARIA menu',+ # )+ # async def get_dropdown_options(index: int, browser_session: BrowserSession) -> ActionResult:+ # """Get all options from a native dropdown or ARIA menu"""+ # page = await browser_session.get_current_page()+ # dom_element = await browser_session.get_dom_element_by_index(index)+ # if dom_element is None:+ # raise Exception(f'Element index {index} does not exist - retry or use alternative actions')++ # try:+ # # Frame-aware approach since we know it works+ # all_options = []+ # frame_index = 0++ # for frame in page.frames:+ # try:+ # # First check if it's a native select element+ # options = await frame.evaluate(+ # """+ # (xpath) => {+ # const element = document.evaluate(xpath, document, null,+ # XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;+ # if (!element) return null;++ # // Check if it's a native select element+ # if (element.tagName.toLowerCase() === 'select') {+ # return {+ # type: 'select',+ # options: Array.from(element.options).map(opt => ({+ # text: opt.text, //do not trim, because we are doing exact match in select_dropdown_option+ # value: opt.value,+ # index: opt.index+ # })),+ # id: element.id,+ # name: element.name+ # };+ # }++ # // Check if it's an ARIA menu+ # if (element.getAttribute('role') === 'menu' ||+ # element.getAttribute('role') === 'listbox' ||+ # element.getAttribute('role') === 'combobox') {+ # // Find all menu items+ # const menuItems = element.querySelectorAll('[role="menuitem"], [role="option"]');+ # const options = [];++ # menuItems.forEach((item, idx) => {+ # // Get the text content of the menu item+ # const text = item.textContent.trim();+ # if (text) {+ # options.push({+ # text: text,+ # value: text, // For ARIA menus, use text as value+ # index: idx+ # });+ # }+ # });++ # return {+ # type: 'aria',+ # options: options,+ # id: element.id || '',+ # name: element.getAttribute('aria-label') || ''+ # };+ # }++ # return null;+ # }+ # """,+ # dom_element.xpath,+ # )++ # if options:+ # logger.debug(f'Found {options["type"]} dropdown in frame {frame_index}')+ # logger.debug(f'Element ID: {options["id"]}, Name: {options["name"]}')++ # formatted_options = []+ # for opt in options['options']:+ # # encoding ensures AI uses the exact string in select_dropdown_option+ # encoded_text = json.dumps(opt['text'])+ # formatted_options.append(f'{opt["index"]}: text={encoded_text}')++ # all_options.extend(formatted_options)++ # except Exception as frame_e:+ # logger.debug(f'Frame {frame_index} evaluation failed: {str(frame_e)}')++ # frame_index += 1++ # if all_options:+ # msg = '\n'.join(all_options)+ # msg += '\nUse the exact text string in select_dropdown_option'+ # logger.info(msg)+ # return ActionResult(+ # extracted_content=msg,+ # include_in_memory=True,+ # long_term_memory=f'Found dropdown options for index {index}.',+ # include_extracted_content_only_once=True,+ # )+ # else:+ # msg = 'No options found in any frame for dropdown'+ # logger.info(msg)+ # return ActionResult(+ # extracted_content=msg, include_in_memory=True, long_term_memory='No dropdown options found'+ # )++ # except Exception as e:+ # logger.error(f'Failed to get dropdown options: {str(e)}')+ # msg = f'Error getting options: {str(e)}'+ # logger.info(msg)+ # return ActionResult(extracted_content=msg, include_in_memory=True)++ # TODO: Refactor to use events instead of direct page/dom access+ # @self.registry.action(+ # description='Select dropdown option or ARIA menu item for interactive element index by the text of the option you want to select',+ # )+ # async def select_dropdown_option(+ # index: int,+ # text: str,+ # browser_session: BrowserSession,+ # ) -> ActionResult:+ # """Select dropdown option or ARIA menu item by the text of the option you want to select"""+ # page = await browser_session.get_current_page()+ # dom_element = await browser_session.get_dom_element_by_index(index)+ # if dom_element is None:+ # raise Exception(f'Element index {index} does not exist - retry or use alternative actions')++ # logger.debug(f"Attempting to select '{text}' using xpath: {dom_element.xpath}")+ # logger.debug(f'Element attributes: {dom_element.attributes}')+ # logger.debug(f'Element tag: {dom_element.tag_name}')++ # xpath = '//' + dom_element.xpath++ # try:+ # frame_index = 0+ # for frame in page.frames:+ # try:+ # logger.debug(f'Trying frame {frame_index} URL: {frame.url}')++ # # First check what type of element we're dealing with+ # element_info_js = """+ # (xpath) => {+ # try {+ # const element = document.evaluate(xpath, document, null,+ # XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;+ # if (!element) return null;++ # const tagName = element.tagName.toLowerCase();+ # const role = element.getAttribute('role');++ # // Check if it's a native select+ # if (tagName === 'select') {+ # return {+ # type: 'select',+ # found: true,+ # id: element.id,+ # name: element.name,+ # tagName: element.tagName,+ # optionCount: element.options.length,+ # currentValue: element.value,+ # availableOptions: Array.from(element.options).map(o => o.text.trim())+ # };+ # }++ # // Check if it's an ARIA menu or similar+ # if (role === 'menu' || role === 'listbox' || role === 'combobox') {+ # const menuItems = element.querySelectorAll('[role="menuitem"], [role="option"]');+ # return {+ # type: 'aria',+ # found: true,+ # id: element.id || '',+ # role: role,+ # tagName: element.tagName,+ # itemCount: menuItems.length,+ # availableOptions: Array.from(menuItems).map(item => item.textContent.trim())+ # };+ # }++ # return {+ # error: `Element is neither a select nor an ARIA menu (tag: ${tagName}, role: ${role})`,+ # found: false+ # };+ # } catch (e) {+ # return {error: e.toString(), found: false};+ # }+ # }+ # """++ # element_info = await frame.evaluate(element_info_js, dom_element.xpath)++ # if element_info and element_info.get('found'):+ # logger.debug(f'Found {element_info.get("type")} element in frame {frame_index}: {element_info}')++ # if element_info.get('type') == 'select':+ # # Handle native select element+ # # "label" because we are selecting by text+ # # nth(0) to disable error thrown by strict mode+ # # timeout=1000 because we are already waiting for all network events+ # selected_option_values = (+ # await frame.locator('//' + dom_element.xpath).nth(0).select_option(label=text, timeout=1000)+ # )++ # msg = f'selected option {text} with value {selected_option_values}'+ # logger.info(msg + f' in frame {frame_index}')++ # return ActionResult(+ # extracted_content=msg, include_in_memory=True, long_term_memory=f"Selected option '{text}'"+ # )++ # elif element_info.get('type') == 'aria':+ # # Handle ARIA menu+ # click_aria_item_js = """+ # (params) => {+ # const { xpath, targetText } = params;+ # try {+ # const element = document.evaluate(xpath, document, null,+ # XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;+ # if (!element) return {success: false, error: 'Element not found'};++ # // Find all menu items+ # const menuItems = element.querySelectorAll('[role="menuitem"], [role="option"]');++ # for (const item of menuItems) {+ # const itemText = item.textContent.trim();+ # if (itemText === targetText) {+ # // Simulate click on the menu item+ # item.click();++ # // Also try dispatching a click event in case the click handler needs it+ # const clickEvent = new MouseEvent('click', {+ # view: window,+ # bubbles: true,+ # cancelable: true+ # });+ # item.dispatchEvent(clickEvent);++ # return {+ # success: true,+ # message: `Clicked menu item: ${targetText}`+ # };+ # }+ # }++ # return {+ # success: false,+ # error: `Menu item with text '${targetText}' not found`+ # };+ # } catch (e) {+ # return {success: false, error: e.toString()};+ # }+ # }+ # """++ # result = await frame.evaluate(+ # click_aria_item_js, {'xpath': dom_element.xpath, 'targetText': text}+ # )++ # if result.get('success'):+ # msg = result.get('message', f'Selected ARIA menu item: {text}')+ # logger.info(msg + f' in frame {frame_index}')+ # return ActionResult(+ # extracted_content=msg,+ # include_in_memory=True,+ # long_term_memory=f"Selected menu item '{text}'",+ # )+ # else:+ # logger.error(f'Failed to select ARIA menu item: {result.get("error")}')+ # continue++ # elif element_info:+ # logger.error(f'Frame {frame_index} error: {element_info.get("error")}')+ # continue++ # except Exception as frame_e:+ # logger.error(f'Frame {frame_index} attempt failed: {str(frame_e)}')+ # logger.error(f'Frame type: {type(frame)}')+ # logger.error(f'Frame URL: {frame.url}')++ # frame_index += 1++ # msg = f"Could not select option '{text}' in any frame"+ # logger.info(msg)+ # return ActionResult(extracted_content=msg, include_in_memory=True, long_term_memory=msg)++ # except Exception as e:+ # msg = f'Selection failed: {str(e)}'+ # logger.error(msg)+ # raise BrowserError(msg)++ # @self.registry.action('Google Sheets: Get the contents of the entire sheet', domains=['https://docs.google.com'])+ # async def read_sheet_contents(browser_session: BrowserSession):+ # # Use send keys events to select and copy all cells+ # for key in ['Enter', 'Escape', 'ControlOrMeta+A', 'ControlOrMeta+C']:+ # event = browser_session.event_bus.dispatch(SendKeysEvent(keys=key))+ # await event++ # # Get page to evaluate clipboard+ # page = await browser_session.get_current_page()+ # extracted_tsv = await page.evaluate('() => navigator.clipboard.readText()')+ # return ActionResult(+ # extracted_content=extracted_tsv,+ # include_in_memory=True,+ # long_term_memory='Retrieved sheet contents',+ # include_extracted_content_only_once=True,+ # )++ # @self.registry.action('Google Sheets: Get the contents of a cell or range of cells', domains=['https://docs.google.com'])+ # async def read_cell_contents(cell_or_range: str, browser_session: BrowserSession):+ # page = await browser_session.get_current_page()++ # await select_cell_or_range(cell_or_range=cell_or_range, page=page)++ # await page.keyboard.press('ControlOrMeta+C')+ # await asyncio.sleep(0.1)+ # extracted_tsv = await page.evaluate('() => navigator.clipboard.readText()')+ # return ActionResult(+ # extracted_content=extracted_tsv,+ # include_in_memory=True,+ # long_term_memory=f'Retrieved contents from {cell_or_range}',+ # include_extracted_content_only_once=True,+ # )++ # @self.registry.action(+ # 'Google Sheets: Update the content of a cell or range of cells', domains=['https://docs.google.com']+ # )+ # async def update_cell_contents(cell_or_range: str, new_contents_tsv: str, browser_session: BrowserSession):+ # page = await browser_session.get_current_page()++ # await select_cell_or_range(cell_or_range=cell_or_range, page=page)++ # # simulate paste event from clipboard with TSV content+ # await page.evaluate(f"""+ # const clipboardData = new DataTransfer();+ # clipboardData.setData('text/plain', `{new_contents_tsv}`);+ # document.activeElement.dispatchEvent(new ClipboardEvent('paste', {{clipboardData}}));+ # """)++ # return ActionResult(+ # extracted_content=f'Updated cells: {cell_or_range} = {new_contents_tsv}',+ # include_in_memory=False,+ # long_term_memory=f'Updated cells {cell_or_range} with {new_contents_tsv}',+ # )++ # @self.registry.action('Google Sheets: Clear whatever cells are currently selected', domains=['https://docs.google.com'])+ # async def clear_cell_contents(cell_or_range: str, browser_session: BrowserSession):+ # page = await browser_session.get_current_page()++ # await select_cell_or_range(cell_or_range=cell_or_range, page=page)++ # await page.keyboard.press('Backspace')+ # return ActionResult(+ # extracted_content=f'Cleared cells: {cell_or_range}',+ # include_in_memory=False,+ # long_term_memory=f'Cleared cells {cell_or_range}',+ # )++ # @self.registry.action('Google Sheets: Select a specific cell or range of cells', domains=['https://docs.google.com'])+ # async def select_cell_or_range(cell_or_range: str, browser_session: BrowserSession):+ # # Use send keys events for navigation+ # for key in ['Enter', 'Escape']:+ # event = browser_session.event_bus.dispatch(SendKeysEvent(keys=key))+ # await event+ # await asyncio.sleep(0.1)+ # for key in ['Home', 'ArrowUp']:+ # event = browser_session.event_bus.dispatch(SendKeysEvent(keys=key))+ # await event+ # await asyncio.sleep(0.1)+ # event = browser_session.event_bus.dispatch(SendKeysEvent(keys='Control+G'))+ # await event+ # await asyncio.sleep(0.2)+ # # Get page to type the cell range+ # page = await browser_session.get_current_page()+ # await page.keyboard.type(cell_or_range, delay=0.05)+ # await asyncio.sleep(0.2)+ # for key in ['Enter', 'Escape']:+ # event = browser_session.event_bus.dispatch(SendKeysEvent(keys=key))+ # await event+ # await asyncio.sleep(0.2)+ # return ActionResult(+ # extracted_content=f'Selected cells: {cell_or_range}',+ # include_in_memory=False,+ # long_term_memory=f'Selected cells {cell_or_range}',+ # )++ # @self.registry.action(+ # 'Google Sheets: Fallback method to type text into (only one) currently selected cell',+ # domains=['https://docs.google.com'],+ # )+ # async def fallback_input_into_single_selected_cell(text: str, browser_session: BrowserSession):+ # # Get page to type text+ # page = await browser_session.get_current_page()+ # await page.keyboard.type(text, delay=0.1)+ # # Use send keys for Enter and ArrowUp+ # for key in ['Enter', 'ArrowUp']:+ # event = browser_session.event_bus.dispatch(SendKeysEvent(keys=key))+ # await event+ # return ActionResult(+ # extracted_content=f'Inputted text {text}',+ # include_in_memory=False,+ # long_term_memory=f"Inputted text '{text}' into cell",+ # )# Custom done action for structured outputdef _register_done_action(self, output_model: type[T] | None, display_files_in_done_text: bool = True):diff --git a/browser_use/dom/service.py b/browser_use/dom/service.pyindex 528af4908..206074016 100644--- a/browser_use/dom/service.py+++ b/browser_use/dom/service.py@@ -61,7 +61,7 @@ class DomService:async def _get_targets_for_page(self, target_id: str | None = None) -> CurrentPageTargets:"""Get the target info for a specific page.-+Args:target_id: The target ID to get info for. If None, uses current_target_id."""@@ -81,7 +81,7 @@ class DomService:# Get all frames using the new method to find iframe targets for this pageall_frames, _ = await self.browser_session.get_all_frames()-+# Find iframe targets that are children of this targetiframe_targets = []for frame_info in all_frames.values():@@ -92,8 +92,7 @@ class DomService:if parent_target == target_id:# Find the target info for this iframeiframe_target = next(- (t for t in targets['targetInfos'] if t['targetId'] == frame_info['frameTargetId']),- None+ (t for t in targets['targetInfos'] if t['targetId'] == frame_info['frameTargetId']), None)if iframe_target:iframe_targets.append(iframe_target)@@ -142,7 +141,7 @@ class DomService:# Set auto-attach with proper filter for iframe targets# This will automatically attach to immediate child frames- # IMPORTANT: This is NOT recursive - we need to call setAutoAttach+ # IMPORTANT: This is NOT recursive - we need to call setAutoAttach# on each newly attached frame to get its childrenawait self.browser_session.cdp_client.send.Target.setAutoAttach(params={@@ -150,10 +149,7 @@ class DomService:'waitForDebuggerOnStart': False,'flatten': True,# Include filter to ensure iframe targets are attached- 'filter': [- {'type': 'page', 'exclude': False},- {'type': 'iframe', 'exclude': False}- ]+ 'filter': [{'type': 'page', 'exclude': False}, {'type': 'iframe', 'exclude': False}],},session_id=session_id,)@@ -387,7 +383,7 @@ class DomService:initial_total_frame_offset: DOMRect | None = None,) -> EnhancedDOMTreeNode:"""Get the DOM tree for a specific target.-+Args:target_id: Optional target ID. If None, uses current target.initial_html_frames: List of HTML frame nodes encountered so far@@ -397,7 +393,7 @@ class DomService:page_session_info = await self._get_targets_for_page(target_id)target = page_session_info.page_sessionactual_target_id = target['targetId'] # Store the actual target ID being used-+# Get viewport dimensions first for visibility calculationsession_id = await self._attach_target_activate_domains_get_session_id(target)@@ -565,8 +561,7 @@ class DomService:# Get the target info for this iframetargets = await self.browser_session.cdp_client.send.Target.getTargets()iframe_document_target = next(- (t for t in targets['targetInfos'] if t['targetId'] == frame_info['frameTargetId']),- None+ (t for t in targets['targetInfos'] if t['targetId'] == frame_info['frameTargetId']), None)else:iframe_document_target = Nonediff --git a/test_frame_hierarchy.py b/test_frame_hierarchy.pyindex 84be92d75..1a1ac1b62 100644--- a/test_frame_hierarchy.py+++ b/test_frame_hierarchy.py@@ -3,252 +3,256 @@import asyncioimport sys+from browser_use.browser import BrowserSession-from browser_use.browser.profile import BrowserProfilefrom browser_use.browser.events import BrowserStartEvent+from browser_use.browser.profile import BrowserProfile+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")+ """Analyze and display complete frame hierarchy for a URL."""++ profile = BrowserProfile(headless=True, user_data_dir=None)+ session = BrowserSession(browser_profile=profile)++ try:+ print('π 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('\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('\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('\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('\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(' β οΈ 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('\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('\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(' β 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(' β Correctly identified as root frame')++ if is_cross:+ print(' πΈ This is a cross-origin frame (OOPIF)')++ # Show parent-child relationships+ print('\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('\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 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+ 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()