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
more downloads watchdog and crash watchdog fixes
Nick Sweeting6ddb62e09341
diff --git a/browser_use/browser/downloads_watchdog.py b/browser_use/browser/downloads_watchdog.pyindex 4945458fc..95ed33504 100644--- a/browser_use/browser/downloads_watchdog.py+++ b/browser_use/browser/downloads_watchdog.py@@ -1,5 +1,6 @@"""Downloads watchdog for monitoring and handling file downloads."""+import asyncioimport jsonimport osfrom pathlib import Path@@ -108,16 +109,111 @@ class DownloadsWatchdog(BaseWatchdog):logger.debug(f'[DownloadsWatchdog] Download listener already exists for page: {page.url}')return- logger.info(f'[DownloadsWatchdog] Setting up download listener for page: {page.url}')+ logger.info(f'[DownloadsWatchdog] Setting up CDP download listener for page: {page.url}')++ # Use raw CDP Page.downloadWillBegin events instead of Playwright's download events+ # This is required when connected via CDP as Playwright download events don't work reliably+ cdp_session = await page.context.new_cdp_session(page)++ # Enable Page domain events+ await cdp_session.send('Page.enable')++ # Set up CDP download listener+ cdp_session.on(+ 'Page.downloadWillBegin', lambda event: asyncio.create_task(self._handle_cdp_download(event, page, cdp_session))+ )- # Set up Playwright download event listener- page.on('download', self._handle_download)# Track that we've added a listener to prevent duplicatesself._pages_with_listeners.add(page)- logger.info(f'[DownloadsWatchdog] Successfully set up download listener for page: {page.url}')+ logger.info(f'[DownloadsWatchdog] Successfully set up CDP download listener for page: {page.url}')++ except Exception as e:+ logger.warning(f'[DownloadsWatchdog] Failed to set up CDP download listener for page {page.url}: {e}')++ async def _handle_cdp_download(self, event: dict, page: Page, cdp_session) -> None:+ """Handle a CDP Page.downloadWillBegin event."""+ try:+ download_url = event.get('url', '')+ suggested_filename = event.get('suggestedFilename', 'download')+ guid = event.get('guid', '')++ logger.info(f'[DownloadsWatchdog] CDP download will begin: {suggested_filename} from {download_url[:100]}...')++ # Get download directory+ downloads_dir = self.browser_session.browser_profile.downloads_path+ if not downloads_dir:+ downloads_dir = str(Path.home() / 'Downloads')+ else:+ downloads_dir = str(downloads_dir)++ # Generate unique filename+ unique_filename = await self._get_unique_filename(downloads_dir, suggested_filename)+ download_path = Path(downloads_dir) / unique_filename++ # Use CDP Browser.downloadProgress to get the actual download data+ # We need to wait for the download to complete and then get its data+ logger.info(f'[DownloadsWatchdog] Waiting for CDP download to complete: {guid}')++ # Wait for download completion via CDP events+ download_complete = False+ download_data = b''++ def on_download_progress(progress_event):+ nonlocal download_complete, download_data+ if progress_event.get('guid') == guid:+ state = progress_event.get('state', '')+ if state == 'completed':+ download_complete = True+ logger.info(f'[DownloadsWatchdog] CDP download completed: {guid}')++ # Listen for download progress+ cdp_session.on('Browser.downloadProgress', on_download_progress)++ # Wait for download to complete (up to 30 seconds)+ for _ in range(150): # 150 * 0.2s = 30s timeout+ if download_complete:+ break+ await asyncio.sleep(0.2)++ if not download_complete:+ logger.error(f'[DownloadsWatchdog] CDP download timed out: {guid}')+ return++ # The download should now be in the downloads directory set by Browser.setDownloadBehavior+ # Check if the file exists at the expected location+ expected_path = Path(downloads_dir) / suggested_filename+ if expected_path.exists() and expected_path.stat().st_size > 0:+ download_path = expected_path+ file_size = expected_path.stat().st_size+ logger.info(f'[DownloadsWatchdog] Found completed download: {download_path} ({file_size} bytes)')+ else:+ logger.warning(f'[DownloadsWatchdog] CDP download completed but file not found: {expected_path}')+ return++ # Determine file type from extension+ file_ext = download_path.suffix.lower().lstrip('.')+ file_type = file_ext if file_ext else None++ # Emit download event+ self.event_bus.dispatch(+ FileDownloadedEvent(+ url=download_url,+ path=str(download_path),+ file_name=suggested_filename,+ file_size=file_size,+ file_type=file_type,+ mime_type=None,+ from_cache=False,+ auto_download=False,+ )+ )++ logger.info(+ f'[DownloadsWatchdog] CDP download completed: {suggested_filename} ({file_size} bytes) saved to {download_path}'+ )except Exception as e:- logger.warning(f'[DownloadsWatchdog] Failed to set up download listener for page {page.url}: {e}')+ logger.error(f'[DownloadsWatchdog] Error handling CDP download: {e}')async def _handle_download(self, download: Download) -> None:"""Handle a download event."""diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex b878b8e5c..006a258fd 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -1422,63 +1422,27 @@ class BrowserSession(BaseModel):download_path = Noneif expect_download and self.browser_profile.downloads_path:- # When expecting a download, use page.expect_download() to set up expectation before click- try:- logger.info('[Session] Setting up download expectation before click...')- async with page.expect_download() as download_info:- # Click the element (with new tab modifier if requested)- if new_tab:- import sys-- modifier = 'Meta' if sys.platform == 'darwin' else 'Control'- await locator.click(modifiers=[modifier])- else:- await locator.click()-- # Get the download object from the expectation- download = await download_info.value- logger.info(f'[Session] Download received: {download.suggested_filename}')-- # Check if download was cancelled- failure = await download.failure()- if failure:- logger.error(f'[Session] Download failed: {failure}')- raise Exception(f'Download failed: {failure}')-- # Generate unique filename and save- downloads_dir = str(self.browser_profile.downloads_path)- unique_filename = await self._get_unique_filename(downloads_dir, download.suggested_filename)- download_path = Path(downloads_dir) / unique_filename+ # When expecting a download with CDP connection, let the downloads watchdog handle it+ # and just wait for FileDownloadedEvent+ logger.info('[Session] Expecting download - letting downloads watchdog handle via CDP...')- logger.info(f'[Session] Saving download to: {download_path}')- await download.save_as(str(download_path))-- # Verify the file was saved successfully- if not download_path.exists():- raise Exception(f'Download file was not saved: {download_path}')-- file_size = download_path.stat().st_size- logger.info(f'[Session] Download successful: {download_path} ({file_size} bytes)')-- # Dispatch FileDownloadedEvent for consistency with watchdog behavior- self.event_bus.dispatch(- FileDownloadedEvent(- url=download.url,- path=str(download_path),- file_name=download.suggested_filename,- file_size=file_size,- file_type=download_path.suffix.lower().lstrip('.') if download_path.suffix else None,- mime_type=None, # Not easily available from Playwright download object- from_cache=False,- auto_download=False,- )- )+ # Click the element and wait for download to be handled by watchdog+ if new_tab:+ import sys- return str(download_path)+ modifier = 'Meta' if sys.platform == 'darwin' else 'Control'+ await locator.click(modifiers=[modifier])+ else:+ await locator.click()- except Exception as e:- logger.error(f'[Session] Download expectation failed: {e}')- raise+ # Wait for FileDownloadedEvent from downloads watchdog+ try:+ download_event = await self.event_bus.expect(FileDownloadedEvent, timeout=15.0)+ logger.info(f'[Session] Download completed via watchdog: {download_event.path}')+ return download_event.path+ except TimeoutError:+ logger.warning('[Session] Expected download but no FileDownloadedEvent received within timeout')+ return Noneelse:# Normal click or new tab click - let downloads watchdog handle any downloads in backgroundif new_tab:diff --git a/tests/ci/test_aboutblank_watchdog.py b/tests/ci/test_aboutblank_watchdog.pyindex bfdbcffd0..15e9692c2 100644--- a/tests/ci/test_aboutblank_watchdog.py+++ b/tests/ci/test_aboutblank_watchdog.py@@ -4,6 +4,7 @@ import asyncioimport pytest+from browser_use.browser.crash_watchdog import CrashWatchdogfrom browser_use.browser.events import (AboutBlankDVDScreensaverShownEvent,BrowserConnectedEvent,@@ -53,10 +54,10 @@ async def test_aboutblank_watchdog_creates_animation_tab():pages = session.pagesassert len(pages) >= 1, 'Should have at least one page'- # Look for about:blank pages (animation tab)- about_blank_pages = [p for p in pages if p.url == 'about:blank']- # AboutBlankWatchdog should create at least one animation tab- assert len(about_blank_pages) >= 1, f'Expected at least one about:blank animation tab, but found {len(about_blank_pages)}'+ # Look for new tab pages (animation tab)+ new_tab_pages = [p for p in pages if CrashWatchdog._is_new_tab_page(p.url)]+ # AboutBlankWatchdog should detect the initial new tab page+ assert len(new_tab_pages) >= 1, f'Expected at least one new tab page, but found {len(new_tab_pages)}'finally:await session.kill()@@ -109,16 +110,16 @@ async def test_aboutblank_watchdog_dvd_screensaver():# Wait for animation tab to be createdawait asyncio.sleep(0.5)- # Find about:blank pages+ # Find new tab pagespages = session.pages- about_blank_pages = [p for p in pages if p.url == 'about:blank']+ new_tab_pages = [p for p in pages if CrashWatchdog._is_new_tab_page(p.url)]- # AboutBlankWatchdog should have created at least one about:blank animation tab- assert len(about_blank_pages) >= 1, (- f'Expected at least one about:blank animation tab for DVD screensaver test, but found {len(about_blank_pages)}'+ # AboutBlankWatchdog should have detected the initial new tab page+ assert len(new_tab_pages) >= 1, (+ f'Expected at least one new tab page for DVD screensaver test, but found {len(new_tab_pages)}')- if about_blank_pages:+ if new_tab_pages:# Try to show screensaver on first about:blank pagetry:await watchdog._show_dvd_screensaver_on_about_blank_tabs()@@ -210,7 +211,7 @@ async def test_aboutblank_watchdog_javascript_execution():# Get the new pagepage2 = session.get_page_by_tab_index(dvd_event2.tab_index)assert page2 is not None, f'Could not find page at tab index {dvd_event2.tab_index}'- assert page2.url == 'about:blank', 'Auto-created tab should be about:blank'+ assert CrashWatchdog._is_new_tab_page(page2.url), f'Auto-created tab should be a new tab page, but got: {page2.url}'# Verify animation on the new tabanimation_exists2 = await page2.evaluate("""() => {