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
add target checking before using
Nick Sweetinge95629ecdb82
diff --git a/browser_use/browser/dom_watchdog.py b/browser_use/browser/dom_watchdog.pyindex 11798a88b..7eff986ed 100644--- a/browser_use/browser/dom_watchdog.py+++ b/browser_use/browser/dom_watchdog.py@@ -15,7 +15,7 @@ from browser_use.dom.views import (EnhancedDOMTreeNode,SerializedDOMState,)-from browser_use.utils import is_new_tab_page, logger+from browser_use.utils import is_new_tab_pageif TYPE_CHECKING:from browser_use.browser.views import BrowserStateSummary@@ -67,7 +67,7 @@ class DOMWatchdog(BaseWatchdog):try:# Fast path for empty pagesif is_empty_page:- logger.debug(f'⚡ Fast path for empty target: {page_url}')+ self.logger.debug(f'⚡ Fast path for empty target: {page_url}')# Create minimal DOM statecontent = SerializedDOMState(_root=None, selector_map={})@@ -108,7 +108,7 @@ class DOMWatchdog(BaseWatchdog):# Normal path: Build DOM tree if requestedif event.include_dom:- logger.debug('🌳 Building DOM tree...')+ self.logger.debug('🌳 Building DOM tree...')# Build the DOM directly using the internal methodprevious_state = (@@ -121,12 +121,12 @@ class DOMWatchdog(BaseWatchdog):# Call the DOM building method directlycontent = await self._build_dom_tree(previous_state)except Exception as e:- logger.warning(f'DOM build failed: {e}, using minimal state')+ self.logger.warning(f'DOM build failed: {e}, using minimal state')content = SerializedDOMState(_root=None, selector_map={})if not content:# Fallback to minimal DOM state- logger.warning('DOM build returned no content, using minimal state')+ self.logger.warning('DOM build returned no content, using minimal state')content = SerializedDOMState(_root=None, selector_map={})else:# Skip DOM building if not requested@@ -141,7 +141,7 @@ class DOMWatchdog(BaseWatchdog):if screenshot_result:screenshot_b64 = screenshot_result.get('screenshot')except Exception as e:- logger.warning(f'Screenshot failed: {e}')+ self.logger.warning(f'Screenshot failed: {e}')# Get target info and tabstabs_info = await self.browser_session.get_tabs_info()@@ -190,7 +190,7 @@ class DOMWatchdog(BaseWatchdog):return browser_stateexcept Exception as e:- logger.error(f'Failed to get browser state: {e}')+ self.logger.error(f'Failed to get browser state: {e}')# Return minimal recovery statereturn BrowserStateSummary(@@ -231,11 +231,11 @@ class DOMWatchdog(BaseWatchdog):try:await self.browser_session.remove_highlights()except Exception as e:- logger.debug(f'Failed to remove existing highlights: {e}')+ self.logger.debug(f'Failed to remove existing highlights: {e}')# Create or reuse DOM serviceif self._dom_service is None:- self._dom_service = DomService(browser_session=self.browser_session, logger=logger)+ self._dom_service = DomService(browser_session=self.browser_session, logger=self.logger)# Get serialized DOM tree using the servicestart = time.time()@@ -244,8 +244,8 @@ class DOMWatchdog(BaseWatchdog):)end = time.time()- logger.debug(f'Time taken to get DOM tree: {end - start} seconds')- logger.debug(f'Timing breakdown: {timing_info}')+ self.logger.debug(f'Time taken to get DOM tree: {end - start} seconds')+ self.logger.debug(f'Timing breakdown: {timing_info}')# Update selector map for other watchdogsself.selector_map = self.current_dom_state.selector_map@@ -256,9 +256,9 @@ class DOMWatchdog(BaseWatchdog):from browser_use.dom.debug.highlights import inject_highlighting_scriptawait inject_highlighting_script(self._dom_service, self.selector_map)- logger.debug(f'Injected highlighting for {len(self.selector_map)} elements')+ self.logger.debug(f'Injected highlighting for {len(self.selector_map)} elements')except Exception as e:- logger.debug(f'Failed to inject highlighting: {e}')+ self.logger.debug(f'Failed to inject highlighting: {e}')# Update BrowserSession's cached selector mapif self.browser_session:@@ -274,7 +274,7 @@ class DOMWatchdog(BaseWatchdog):return self.current_dom_stateexcept Exception as e:- logger.error(f'Failed to build DOM tree: {e}')+ self.logger.error(f'Failed to build DOM tree: {e}')self.event_bus.dispatch(BrowserErrorEvent(error_type='DOMBuildFailed',diff --git a/browser_use/browser/downloads_watchdog.py b/browser_use/browser/downloads_watchdog.pyindex 0e6287ca5..4f1940280 100644--- a/browser_use/browser/downloads_watchdog.py+++ b/browser_use/browser/downloads_watchdog.py@@ -20,7 +20,6 @@ from browser_use.browser.events import (TabCreatedEvent,)from browser_use.browser.watchdog_base import BaseWatchdog-from browser_use.utils import loggerif TYPE_CHECKING:pass@@ -52,12 +51,12 @@ class DownloadsWatchdog(BaseWatchdog):_download_cdp_session: Any = PrivateAttr(default=None) # Store CDP session referenceasync def on_BrowserLaunchEvent(self, event: BrowserLaunchEvent) -> None:- logger.info(f'[DownloadsWatchdog] Received BrowserLaunchEvent, EventBus ID: {id(self.event_bus)}')+ self.logger.info(f'[DownloadsWatchdog] Received BrowserLaunchEvent, EventBus ID: {id(self.event_bus)}')# Ensure downloads directory existsdownloads_path = self.browser_session.browser_profile.downloads_pathif downloads_path:Path(downloads_path).mkdir(parents=True, exist_ok=True)- logger.info(f'[DownloadsWatchdog] Ensured downloads directory exists: {downloads_path}')+ self.logger.info(f'[DownloadsWatchdog] Ensured downloads directory exists: {downloads_path}')async def on_TabCreatedEvent(self, event: TabCreatedEvent) -> None:"""Monitor new tabs for downloads."""@@ -71,7 +70,7 @@ class DownloadsWatchdog(BaseWatchdog):# logger.info(f'[DownloadsWatchdog] Found target for tab {event.tab_index}, calling attach_to_target')await self.attach_to_target(target_id)else:- logger.warning(f'[DownloadsWatchdog] No target found for tab {event.tab_index}')+ self.logger.warning(f'[DownloadsWatchdog] No target found for tab {event.tab_index}')async def on_TabClosedEvent(self, event: TabClosedEvent) -> None:"""Stop monitoring closed tabs."""@@ -89,7 +88,7 @@ class DownloadsWatchdog(BaseWatchdog):target_id = await self.browser_session.get_target_id_by_tab_index(event.tab_index)if target_id and await self.check_for_pdf_viewer(target_id):- logger.info(f'[DownloadsWatchdog] PDF detected after navigation to {event.url}')+ self.logger.info(f'[DownloadsWatchdog] PDF detected after navigation to {event.url}')await self.trigger_pdf_download(target_id)def _is_auto_download_enabled(self) -> bool:@@ -107,7 +106,7 @@ class DownloadsWatchdog(BaseWatchdog):# Check if we already have a download listener on this target# to prevent duplicate listeners from being addedif target_id in self._targets_with_listeners:- logger.debug(f'[DownloadsWatchdog] Download listener already exists for target: {target_id}')+ self.logger.debug(f'[DownloadsWatchdog] Download listener already exists for target: {target_id}')return# logger.debug(f'[DownloadsWatchdog] Setting up CDP download listener for target: {target_id}')@@ -124,21 +123,21 @@ class DownloadsWatchdog(BaseWatchdog):# Set up download event listenerdef download_handler(event):- logger.info(f'[DownloadsWatchdog] Download event triggered: {event}')+ self.logger.info(f'[DownloadsWatchdog] Download event triggered: {event}')# Pass target_id for this downloadasyncio.create_task(self._handle_cdp_download(event, target_id, session_id))cdp_client.on('Page.downloadWillBegin', download_handler, session_id=session_id)self._download_cdp_session_setup = Trueself._download_cdp_session = session_id- logger.debug('[DownloadsWatchdog] Set up CDP download listener')+ self.logger.debug('[DownloadsWatchdog] Set up CDP download listener')# Track that we've added a listener to prevent duplicatesself._targets_with_listeners.add(target_id)# logger.debug(f'[DownloadsWatchdog] Successfully set up CDP download listener for target: {target_id}')except Exception as e:- logger.warning(f'[DownloadsWatchdog] Failed to set up CDP download listener for target {target_id}: {e}')+ self.logger.warning(f'[DownloadsWatchdog] Failed to set up CDP download listener for target {target_id}: {e}')async def _handle_cdp_download(self, event: dict, target_id: str, session_id: str) -> None:"""Handle a CDP Page.downloadWillBegin event."""@@ -147,8 +146,8 @@ class DownloadsWatchdog(BaseWatchdog):suggested_filename = event.get('suggestedFilename', 'download')guid = event.get('guid', '')- logger.info(f'[DownloadsWatchdog] ⬇️ File download starting: {suggested_filename} from {download_url[:100]}...')- logger.debug(f'[DownloadsWatchdog] Full CDP event: {event}')+ self.logger.info(f'[DownloadsWatchdog] ⬇️ File download starting: {suggested_filename} from {download_url[:100]}...')+ self.logger.debug(f'[DownloadsWatchdog] Full CDP event: {event}')# Get download directorydownloads_dir = self.browser_session.browser_profile.downloads_path@@ -162,14 +161,14 @@ class DownloadsWatchdog(BaseWatchdog):expected_path = Path(downloads_dir) / suggested_filename# Debug: List current directory contents- logger.info(f'[DownloadsWatchdog] Downloads directory: {downloads_dir}')+ self.logger.info(f'[DownloadsWatchdog] Downloads directory: {downloads_dir}')if Path(downloads_dir).exists():files_before = list(Path(downloads_dir).iterdir())- logger.info(f'[DownloadsWatchdog] Files before download: {[f.name for f in files_before]}')+ self.logger.info(f'[DownloadsWatchdog] Files before download: {[f.name for f in files_before]}')# Browser.setDownloadBehavior doesn't work reliably with CDP connections# So we'll download the file manually using JavaScript fetch- logger.info(f'[DownloadsWatchdog] Downloading file manually via fetch: {download_url}')+ self.logger.info(f'[DownloadsWatchdog] Downloading file manually via fetch: {download_url}')try:# Escape the URL for JavaScript@@ -222,14 +221,14 @@ class DownloadsWatchdog(BaseWatchdog):async with await anyio.open_file(final_path, 'wb') as f:await f.write(file_data)- logger.info(f'[DownloadsWatchdog] ✅ Downloaded and saved file: {final_path} ({file_size} bytes)')+ self.logger.info(f'[DownloadsWatchdog] ✅ Downloaded and saved file: {final_path} ({file_size} bytes)')expected_path = final_pathelse:- logger.error('[DownloadsWatchdog] ❌ No data received from fetch')+ self.logger.error('[DownloadsWatchdog] ❌ No data received from fetch')returnexcept Exception as fetch_error:- logger.error(f'[DownloadsWatchdog] ❌ Failed to download file via fetch: {fetch_error}')+ self.logger.error(f'[DownloadsWatchdog] ❌ Failed to download file via fetch: {fetch_error}')return# Determine file type from extension@@ -250,24 +249,24 @@ class DownloadsWatchdog(BaseWatchdog):))- logger.info(+ self.logger.info(f'[DownloadsWatchdog] ✅ File download completed via CDP: {suggested_filename} ({file_size} bytes) saved to {expected_path}')except Exception as e:- logger.error(f'[DownloadsWatchdog] ❌ Error handling CDP download: {e}')+ self.logger.error(f'[DownloadsWatchdog] ❌ Error handling CDP download: {e}')async def _handle_download(self, download: Any) -> None:"""Handle a download event."""download_id = f'{id(download)}'self._active_downloads[download_id] = download- logger.info(f'[DownloadsWatchdog] ⬇️ Handling download: {download.suggested_filename} from {download.url[:100]}...')+ self.logger.info(f'[DownloadsWatchdog] ⬇️ Handling download: {download.suggested_filename} from {download.url[:100]}...')# Debug: Check if download is already being handled elsewherefailure = (await download.failure()) # TODO: it always fails for some reason, figure out why connect_over_cdp makes accept_downloads not work- logger.warning(f'[DownloadsWatchdog] ❌ Download state - canceled: {failure}, url: {download.url}')+ self.logger.warning(f'[DownloadsWatchdog] ❌ Download state - canceled: {failure}, url: {download.url}')# logger.info(f'[DownloadsWatchdog] Active downloads count: {len(self._active_downloads)}')try:@@ -287,7 +286,7 @@ class DownloadsWatchdog(BaseWatchdog):# Check if Playwright already auto-downloaded the file (due to CDP setup)original_path = Path(downloads_dir) / suggested_filenameif original_path.exists() and original_path.stat().st_size > 0:- logger.info(+ self.logger.info(f'[DownloadsWatchdog] File already downloaded by Playwright: {original_path} ({original_path.stat().st_size} bytes)')@@ -301,21 +300,21 @@ class DownloadsWatchdog(BaseWatchdog):unique_filename = await self._get_unique_filename(downloads_dir, suggested_filename)download_path = Path(downloads_dir) / unique_filename- logger.info(f'[DownloadsWatchdog] Download started: {unique_filename} from {url[:100]}...')+ self.logger.info(f'[DownloadsWatchdog] Download started: {unique_filename} from {url[:100]}...')current_step = 'calling_save_as'# Save the download using Playwright's save_as method- logger.info(f'[DownloadsWatchdog] Saving download to: {download_path}')- logger.info(f'[DownloadsWatchdog] Download path exists: {download_path.parent.exists()}')- logger.info(f'[DownloadsWatchdog] Download path writable: {os.access(download_path.parent, os.W_OK)}')+ self.logger.info(f'[DownloadsWatchdog] Saving download to: {download_path}')+ self.logger.info(f'[DownloadsWatchdog] Download path exists: {download_path.parent.exists()}')+ self.logger.info(f'[DownloadsWatchdog] Download path writable: {os.access(download_path.parent, os.W_OK)}')try:- logger.info('[DownloadsWatchdog] About to call download.save_as()...')+ self.logger.info('[DownloadsWatchdog] About to call download.save_as()...')await download.save_as(str(download_path))- logger.info(f'[DownloadsWatchdog] Successfully saved download to: {download_path}')+ self.logger.info(f'[DownloadsWatchdog] Successfully saved download to: {download_path}')current_step = 'save_as_completed'except Exception as save_error:- logger.error(f'[DownloadsWatchdog] save_as() failed with error: {save_error}')+ self.logger.error(f'[DownloadsWatchdog] save_as() failed with error: {save_error}')raise save_error# Get file info@@ -348,17 +347,17 @@ class DownloadsWatchdog(BaseWatchdog):))- logger.info(+ self.logger.info(f'[DownloadsWatchdog] Download completed: {suggested_filename} ({file_size} bytes) saved to {download_path}')# File is now tracked on filesystem, no need to track in memoryexcept Exception as e:- logger.error(+ self.logger.error(f'[DownloadsWatchdog] Error handling download at step "{locals().get("current_step", "unknown")}", error: {e}')- logger.error(f'[DownloadsWatchdog] Download state - URL: {download.url}, filename: {download.suggested_filename}')+ self.logger.error(f'[DownloadsWatchdog] Download state - URL: {download.url}, filename: {download.suggested_filename}')finally:# Clean up trackingif download_id in self._active_downloads:@@ -461,7 +460,7 @@ class DownloadsWatchdog(BaseWatchdog):is_pdf_viewer = result.get('result', {}).get('value', {})if is_pdf_viewer.get('isPdf', False):- logger.info(+ self.logger.info(f'[DownloadsWatchdog] 📄 PDF detected: {is_pdf_viewer.get("url", "unknown")} 'f'(type: {"Chrome viewer" if is_pdf_viewer.get("isChromePdfViewer") else "direct PDF"})')@@ -472,11 +471,11 @@ class DownloadsWatchdog(BaseWatchdog):return Falseexcept TimeoutError:- logger.warning(f'[DownloadsWatchdog] ❌ PDF check timed out for target: {page_url}')+ self.logger.warning(f'[DownloadsWatchdog] ❌ PDF check timed out for target: {page_url}')self._pdf_viewer_cache[page_url] = Falsereturn Falseexcept Exception as e:- logger.warning(f'[DownloadsWatchdog] ❌ Error checking for PDF viewer: {e}')+ self.logger.warning(f'[DownloadsWatchdog] ❌ Error checking for PDF viewer: {e}')self._pdf_viewer_cache[page_url] = Falsereturn False@@ -486,7 +485,7 @@ class DownloadsWatchdog(BaseWatchdog):Returns the download path if successful, None otherwise."""if not self.browser_session.browser_profile.downloads_path:- logger.warning(f'[DownloadsWatchdog] ❌ No downloads path configured, cannot save PDF download')+ self.logger.warning(f'[DownloadsWatchdog] ❌ No downloads path configured, cannot save PDF download')return Nonetry:@@ -523,7 +522,7 @@ class DownloadsWatchdog(BaseWatchdog):pdf_url = pdf_info.get('url', '')if not pdf_url:- logger.warning(f'[DownloadsWatchdog] ❌ Could not determine PDF URL for download {pdf_info}')+ self.logger.warning(f'[DownloadsWatchdog] ❌ Could not determine PDF URL for download {pdf_info}')return None# Generate filename from URL@@ -539,10 +538,10 @@ class DownloadsWatchdog(BaseWatchdog):if os.path.exists(downloads_dir):existing_files = os.listdir(downloads_dir)if pdf_filename in existing_files:- logger.debug(f'[DownloadsWatchdog] ✅ PDF already downloaded: {pdf_filename}')+ self.logger.debug(f'[DownloadsWatchdog] ✅ PDF already downloaded: {pdf_filename}')return None- logger.info(f'[DownloadsWatchdog] ⬇️ Downloading PDF file from: {pdf_url[:100]}...')+ self.logger.info(f'[DownloadsWatchdog] ⬇️ Downloading PDF file from: {pdf_url[:100]}...')# Download using JavaScript fetch to leverage browser cachetry:@@ -608,7 +607,7 @@ class DownloadsWatchdog(BaseWatchdog):# Log cache informationcache_status = 'from cache' if download_result.get('fromCache') else 'from network'response_size = download_result.get('responseSize', 0)- logger.info(+ self.logger.info(f'[DownloadsWatchdog] ✅ Auto-downloaded PDF ({cache_status}, {response_size:,} bytes): {download_path}')@@ -630,13 +629,13 @@ class DownloadsWatchdog(BaseWatchdog):await cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})return download_pathelse:- logger.warning(f'[DownloadsWatchdog] No data received when downloading PDF from {pdf_url}')+ self.logger.warning(f'[DownloadsWatchdog] No data received when downloading PDF from {pdf_url}')# Detach from targetawait cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})return Noneexcept Exception as e:- logger.warning(f'[DownloadsWatchdog] Failed to auto-download PDF from {pdf_url}: {type(e).__name__}: {e}')+ self.logger.warning(f'[DownloadsWatchdog] Failed to auto-download PDF from {pdf_url}: {type(e).__name__}: {e}')# Try to detach from target if possibletry:await cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})@@ -645,10 +644,10 @@ class DownloadsWatchdog(BaseWatchdog):return Noneexcept TimeoutError:- logger.debug('[DownloadsWatchdog] PDF download operation timed out')+ self.logger.debug('[DownloadsWatchdog] PDF download operation timed out')return Noneexcept Exception as e:- logger.error(f'[DownloadsWatchdog] Error in PDF download: {type(e).__name__}: {e}')+ self.logger.error(f'[DownloadsWatchdog] Error in PDF download: {type(e).__name__}: {e}')return None@staticmethoddiff --git a/browser_use/browser/local_browser_watchdog.py b/browser_use/browser/local_browser_watchdog.pyindex e1a346811..b8b0d6a89 100644--- a/browser_use/browser/local_browser_watchdog.py+++ b/browser_use/browser/local_browser_watchdog.py@@ -17,7 +17,6 @@ from browser_use.browser.events import (BrowserStopEvent,)from browser_use.browser.watchdog_base import BaseWatchdog-from browser_use.utils import loggerif TYPE_CHECKING:pass@@ -45,25 +44,25 @@ class LocalBrowserWatchdog(BaseWatchdog):async def on_BrowserLaunchEvent(self, event: BrowserLaunchEvent) -> dict[str, str]:"""Launch a local browser process."""try:- logger.info(+ self.logger.info(f'[LocalBrowserWatchdog] Received BrowserLaunchEvent, EventBus ID: {id(self.event_bus)}, launching local browser')- logger.debug('[LocalBrowserWatchdog] Calling _launch_browser...')+ self.logger.debug('[LocalBrowserWatchdog] Calling _launch_browser...')process, cdp_url = await self._launch_browser()- logger.debug(f'[LocalBrowserWatchdog] _launch_browser returned: process={process}, cdp_url={cdp_url}')+ self.logger.debug(f'[LocalBrowserWatchdog] _launch_browser returned: process={process}, cdp_url={cdp_url}')self._subprocess = process- logger.info(f'[LocalBrowserWatchdog] Browser launched successfully at {cdp_url}, PID: {process.pid}')+ self.logger.info(f'[LocalBrowserWatchdog] Browser launched successfully at {cdp_url}, PID: {process.pid}')return {'cdp_url': cdp_url}except Exception as e:- logger.error(f'[LocalBrowserWatchdog] Exception in on_BrowserLaunchEvent: {e}', exc_info=True)+ self.logger.error(f'[LocalBrowserWatchdog] Exception in on_BrowserLaunchEvent: {e}', exc_info=True)raiseasync def on_BrowserKillEvent(self, event: BrowserKillEvent) -> None:"""Kill the local browser subprocess."""- logger.info('[LocalBrowserWatchdog] Killing local browser process')+ self.logger.info('[LocalBrowserWatchdog] Killing local browser process')if self._subprocess:await self._cleanup_process(self._subprocess)@@ -79,12 +78,12 @@ class LocalBrowserWatchdog(BaseWatchdog):self.browser_session.browser_profile.user_data_dir = self._original_user_data_dirself._original_user_data_dir = None- logger.info('[LocalBrowserWatchdog] Browser cleanup completed')+ self.logger.info('[LocalBrowserWatchdog] Browser cleanup completed')async def on_BrowserStopEvent(self, event: BrowserStopEvent) -> None:"""Listen for BrowserStopEvent and dispatch BrowserKillEvent without awaiting it."""if self.browser_session.is_local and self._subprocess:- logger.info('[LocalBrowserWatchdog] BrowserStopEvent received, dispatching BrowserKillEvent')+ self.logger.info('[LocalBrowserWatchdog] BrowserStopEvent received, dispatching BrowserKillEvent')# Dispatch BrowserKillEvent without awaiting so it gets processed after all BrowserStopEvent handlersself.event_bus.dispatch(BrowserKillEvent())@@ -118,9 +117,9 @@ class LocalBrowserWatchdog(BaseWatchdog):# Use custom executable if provided, otherwise use playwright'sif profile.executable_path:browser_path = profile.executable_path- logger.debug(f'[LocalBrowserWatchdog] Using custom executable: {browser_path}')+ self.logger.debug(f'[LocalBrowserWatchdog] Using custom executable: {browser_path}')else:- logger.debug('[LocalBrowserWatchdog] Getting browser path from playwright...')+ self.logger.debug('[LocalBrowserWatchdog] Getting browser path from playwright...')# Use async playwright properly with timeoutplaywright = await asyncio.wait_for(async_playwright().start(),@@ -128,21 +127,21 @@ class LocalBrowserWatchdog(BaseWatchdog):)try:browser_path = playwright.chromium.executable_path- logger.debug(f'[LocalBrowserWatchdog] Got browser path: {browser_path}')+ self.logger.debug(f'[LocalBrowserWatchdog] Got browser path: {browser_path}')finally:# Always stop playwright after getting the pathawait playwright.stop()- logger.debug('[LocalBrowserWatchdog] Playwright stopped')+ self.logger.debug('[LocalBrowserWatchdog] Playwright stopped')# Launch browser subprocess directly- logger.debug(f'[LocalBrowserWatchdog] Launching browser subprocess with {len(launch_args)} args...')+ self.logger.debug(f'[LocalBrowserWatchdog] Launching browser subprocess with {len(launch_args)} args...')subprocess = await asyncio.create_subprocess_exec(browser_path,*launch_args,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE,)- logger.debug(f'[LocalBrowserWatchdog] Browser subprocess launched with PID: {subprocess.pid}')+ self.logger.debug(f'[LocalBrowserWatchdog] Browser subprocess launched with PID: {subprocess.pid}')# Convert to psutil.Processprocess = psutil.Process(subprocess.pid)@@ -164,7 +163,7 @@ class LocalBrowserWatchdog(BaseWatchdog):# Check if this is a user_data_dir related errorif any(err in error_str for err in ['singletonlock', 'user data directory', 'cannot create', 'already in use']):- logger.warning(f'Browser launch failed (attempt {attempt + 1}/{max_retries}): {e}')+ self.logger.warning(f'Browser launch failed (attempt {attempt + 1}/{max_retries}): {e}')if attempt < max_retries - 1:# Create a temporary directory for next attempt@@ -173,7 +172,7 @@ class LocalBrowserWatchdog(BaseWatchdog):# Update profile to use temp directoryprofile.user_data_dir = str(tmp_dir)- logger.info(f'Retrying with temporary user_data_dir: {tmp_dir}')+ self.logger.info(f'Retrying with temporary user_data_dir: {tmp_dir}')# Small delay before retryawait asyncio.sleep(0.5)@@ -273,7 +272,7 @@ class LocalBrowserWatchdog(BaseWatchdog):if 'browseruse-tmp-' in str(temp_path):shutil.rmtree(temp_path, ignore_errors=True)except Exception as e:- logger.debug(f'Failed to cleanup temp dir {temp_dir}: {e}')+ self.logger.debug(f'Failed to cleanup temp dir {temp_dir}: {e}')@propertydef browser_pid(self) -> int | None:diff --git a/browser_use/browser/navigation_watchdog.py b/browser_use/browser/navigation_watchdog.pyindex b7119b990..7da8f7ccc 100644--- a/browser_use/browser/navigation_watchdog.py+++ b/browser_use/browser/navigation_watchdog.py@@ -19,7 +19,6 @@ from browser_use.browser.events import (TabCreatedEvent,)from browser_use.browser.watchdog_base import BaseWatchdog-from browser_use.utils import loggerif TYPE_CHECKING:pass@@ -61,7 +60,7 @@ class NavigationWatchdog(BaseWatchdog):async def on_BrowserConnectedEvent(self, event: BrowserConnectedEvent) -> None:"""Initialize agent focus when browser is connected."""- logger.debug('[NavigationWatchdog] Browser connected, initializing agent focus')+ self.logger.debug('[NavigationWatchdog] Browser connected, initializing agent focus')await self._initialize_agent_focus()async def on_BrowserStoppedEvent(self, event: BrowserStoppedEvent) -> None:@@ -74,7 +73,7 @@ class NavigationWatchdog(BaseWatchdog):async def on_TabCreatedEvent(self, event: TabCreatedEvent) -> None:"""Handle new tab creation - track target and possibly move agent focus."""- # logger.debug(f'[NavigationWatchdog] Tab created: {event.url}')+ # self.logger.debug(f'[NavigationWatchdog] Tab created: {event.url}')# Get all targets and track the new onetry:@@ -83,14 +82,14 @@ class NavigationWatchdog(BaseWatchdog):target_id = targets[event.tab_index]['targetId']self._track_target(target_id)except Exception as e:- logger.error(f'[NavigationWatchdog] Error tracking new target: {e}')+ self.logger.error(f'[NavigationWatchdog] Error tracking new target: {e}')# When a new tab is created, agent typically focuses on it immediatelyawait self._update_agent_focus_to_latest_tab()async def on_TabClosedEvent(self, event: TabClosedEvent) -> None:"""Handle tab closure."""- logger.debug(f'[NavigationWatchdog] Tab closed at index {event.tab_index}')+ self.logger.debug(f'[NavigationWatchdog] Tab closed at index {event.tab_index}')# If the closed tab was the agent's current target, find a new onecurrent_tab_index = await self._get_current_tab_index()@@ -100,7 +99,7 @@ class NavigationWatchdog(BaseWatchdog):async def on_SwitchTabEvent(self, event: SwitchTabEvent) -> None:"""Handle explicit tab switches by the agent."""- logger.debug(f'[NavigationWatchdog] Agent switching to tab {event.tab_index}')+ self.logger.debug(f'[NavigationWatchdog] Agent switching to tab {event.tab_index}')await self._switch_agent_focus_to_tab(event.tab_index)async def on_NavigateToUrlEvent(self, event: NavigateToUrlEvent) -> None:@@ -108,12 +107,12 @@ class NavigationWatchdog(BaseWatchdog):# Check if browser session is still availableif not self.browser_session:- logger.debug('[NavigationWatchdog] No browser session available, ignoring navigation')+ self.logger.debug('[NavigationWatchdog] No browser session available, ignoring navigation')return# SECURITY CHECK: Block disallowed URLs before navigation startsif not self._is_url_allowed(event.url):- logger.warning(f'⛔️ Blocking navigation to disallowed URL: {event.url}')+ self.logger.warning(f'⛔️ Blocking navigation to disallowed URL: {event.url}')self.event_bus.dispatch(BrowserErrorEvent(error_type='NavigationBlocked',@@ -166,7 +165,7 @@ class NavigationWatchdog(BaseWatchdog):# Handle navigation timeout for new taberror_message = 'Navigation timed out after 30 seconds'loading_status = 'Navigation timeout: 30 seconds'- logger.warning(f'[NavigationWatchdog] Navigation to {event.url} timed out in new tab')+ self.logger.warning(f'[NavigationWatchdog] Navigation to {event.url} timed out in new tab')self.event_bus.dispatch(NavigationCompleteEvent(@@ -220,7 +219,7 @@ class NavigationWatchdog(BaseWatchdog):try:await asyncio.wait_for(nav_event, timeout=event.timeout_ms / 1000.0)except TimeoutError:- logger.warning(f'Navigation to {event.url} timed out after {event.timeout_ms}ms')+ self.logger.warning(f'Navigation to {event.url} timed out after {event.timeout_ms}ms')# Dispatch NavigationCompleteEvent for timeout errorself.event_bus.dispatch(NavigationCompleteEvent(@@ -282,7 +281,7 @@ class NavigationWatchdog(BaseWatchdog):# Handle navigation timeout for standard navigationerror_message = 'Navigation timed out after 30 seconds'loading_status = 'Navigation timeout: 30 seconds'- logger.warning(f'[NavigationWatchdog] Navigation to {event.url} timed out in standard navigation')+ self.logger.warning(f'[NavigationWatchdog] Navigation to {event.url} timed out in standard navigation')# Get tab index for timeout error reportingtab_index = await self._get_tab_index_for_target(target_id) if target_id else 0@@ -324,7 +323,7 @@ class NavigationWatchdog(BaseWatchdog):"""Update agent focus when navigation completes and enforce security."""# Check if the navigated URL is allowedif not self._is_url_allowed(event.url):- logger.warning(f'⛔️ Navigation to non-allowed URL detected: {event.url}')+ self.logger.warning(f'⛔️ Navigation to non-allowed URL detected: {event.url}')# Dispatch browser errorself.event_bus.dispatch(BrowserErrorEvent(@@ -339,9 +338,9 @@ class NavigationWatchdog(BaseWatchdog):if 0 <= event.tab_index < len(targets):target_id = targets[event.tab_index]['targetId']await self.browser_session._cdp_close_page(target_id)- logger.info(f'⛔️ Closed target with non-allowed URL: {event.url}')+ self.logger.info(f'⛔️ Closed target with non-allowed URL: {event.url}')except Exception as e:- logger.error(f'⛔️ Failed to close target with non-allowed URL: {str(e)}')+ self.logger.error(f'⛔️ Failed to close target with non-allowed URL: {str(e)}')return# Agent focus stays on the tab that navigated@@ -353,7 +352,7 @@ class NavigationWatchdog(BaseWatchdog):def _track_target(self, target_id: str) -> None:"""Track a target for lifecycle events."""- # logger.debug(f'[NavigationWatchdog] Started tracking target: {target_id}')+ # self.logger.debug(f'[NavigationWatchdog] Started tracking target: {target_id}')self._target_close_handlers[target_id] = Truedef _handle_target_close(self, target_id: str) -> None:@@ -366,13 +365,13 @@ class NavigationWatchdog(BaseWatchdog):# Emit TabClosedEventself.event_bus.dispatch(TabClosedEvent(tab_index=tab_index))- logger.info(f'[NavigationWatchdog] Target closed, emitted TabClosedEvent for tab {tab_index}')+ self.logger.info(f'[NavigationWatchdog] Target closed, emitted TabClosedEvent for tab {tab_index}')# Clean up the handler from our tracking dictself._target_close_handlers.pop(target_id, None)except Exception as e:- logger.error(f'[NavigationWatchdog] Error handling target close: {e}')+ self.logger.error(f'[NavigationWatchdog] Error handling target close: {e}')# ========== Security Methods ==========@@ -500,7 +499,7 @@ class NavigationWatchdog(BaseWatchdog):self.browser_session.current_target_id = self.current_target_idawait self._dispatch_focus_changed()target_url = await self._get_target_url(self.current_target_id)- logger.info(f'[NavigationWatchdog] Initial agent focus set to tab 0: {target_url}')+ self.logger.info(f'[NavigationWatchdog] Initial agent focus set to tab 0: {target_url}')async def _update_agent_focus_to_latest_tab(self) -> None:"""Update agent focus to the latest (most recently created) tab."""@@ -512,7 +511,7 @@ class NavigationWatchdog(BaseWatchdog):await self._dispatch_focus_changed()target_url = await self._get_target_url(self.current_target_id)tab_index = await self._get_current_tab_index()- logger.info(f'[NavigationWatchdog] 👀 Agent focus moved to new tab {tab_index}: {target_url}')+ self.logger.info(f'[NavigationWatchdog] 👀 Agent focus moved to new tab {tab_index}: {target_url}')async def _switch_agent_focus_to_tab(self, tab_index: int) -> None:"""Switch agent focus to a specific tab index."""@@ -522,7 +521,7 @@ class NavigationWatchdog(BaseWatchdog):self.browser_session.current_target_id = self.current_target_idawait self._dispatch_focus_changed()target_url = await self._get_target_url(self.current_target_id)- logger.info(f'[NavigationWatchdog] Agent focus switched to tab {tab_index}: {target_url}')+ self.logger.info(f'[NavigationWatchdog] Agent focus switched to tab {tab_index}: {target_url}')async def _find_new_agent_target(self) -> None:"""Find a new target for agent focus when current one is closed."""@@ -535,7 +534,7 @@ class NavigationWatchdog(BaseWatchdog):self.browser_session.current_target_id = self.current_target_idawait self._dispatch_focus_changed()target_url = await self._get_target_url(self.current_target_id)- logger.info(f'[NavigationWatchdog] Agent focus moved to tab {new_index}: {target_url}')+ self.logger.info(f'[NavigationWatchdog] Agent focus moved to tab {new_index}: {target_url}')else:self.current_target_id = Noneif self.browser_session:@@ -555,7 +554,7 @@ class NavigationWatchdog(BaseWatchdog):))except Exception as e:- logger.error(f'[NavigationWatchdog] Error dispatching focus change: {e}')+ self.logger.error(f'[NavigationWatchdog] Error dispatching focus change: {e}')async def get_or_create_target(self) -> str:"""Get current agent target or create a new one if none exists."""@@ -563,7 +562,7 @@ class NavigationWatchdog(BaseWatchdog):# Check if current target URL is still allowedtarget_url = await self._get_target_url(self.current_target_id)if target_url and not self._is_url_allowed(target_url):- logger.warning(f'⛔️ Current target URL no longer allowed: {target_url}')+ self.logger.warning(f'⛔️ Current target URL no longer allowed: {target_url}')# Close the current target and find/create a new onetry:await self.browser_session._cdp_close_page(self.current_target_id)@@ -586,7 +585,7 @@ class NavigationWatchdog(BaseWatchdog):pass# No tabs available or no allowed tabs, create a new one with about:blank- logger.info('[NavigationWatchdog] No active target, creating new tab')+ self.logger.info('[NavigationWatchdog] No active target, creating new tab')nav_event = self.event_bus.dispatch(NavigateToUrlEvent(url='about:blank', new_tab=True))await nav_event # Wait for navigation to completediff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex c45819389..7c3248fd8 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -1305,6 +1305,31 @@ class BrowserSession(BaseModel):# Use helper to navigate on the targetawait self._cdp_execute_on_target(target_to_use, commands=[('Page.enable', {}), ('Page.navigate', {'url': url})])+ @staticmethod+ def _is_valid_target(target_info: dict) -> bool:+ """Check if a target should be processed.++ Args:+ target_info: Target info dict from CDP++ Returns:+ True if target should be processed, False if it should be skipped+ """+ target_type = target_info.get('type', '')+ url = target_info.get('url', '')++ # Exclude chrome extension and error pages+ if url.startswith('chrome-extension://') or url.startswith('chrome-error://'):+ return False++ # Exclude any worker targets+ if 'worker' in target_type.lower():+ return False++ # Include specific target types+ valid_types = {'page', 'tab', 'iframe', 'webview', 'browser'}+ return target_type in valid_types+async def get_all_frames(self) -> tuple[dict[str, dict], dict[str, str]]:"""Get a complete frame hierarchy from all browser targets.@@ -1327,6 +1352,10 @@ class BrowserSession(BaseModel):if not target_id:continue+ # Skip invalid targets+ if not self._is_valid_target(target):+ continue+# Attach to targetsession = await self.cdp_client.send.Target.attachToTarget(params={'targetId': target_id, 'flatten': True}