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
fix downloads watchdog and aboutblank watchdog
Nick Sweeting5a8e9b3bfaca
diff --git a/browser_use/browser/aboutblank_watchdog.py b/browser_use/browser/aboutblank_watchdog.pyindex 6ff69d646..37b3e4a7d 100644--- a/browser_use/browser/aboutblank_watchdog.py+++ b/browser_use/browser/aboutblank_watchdog.py@@ -4,8 +4,12 @@ from typing import TYPE_CHECKING, Any, ClassVarfrom bubus import BaseEventfrom playwright.async_api import Page+from pydantic import PrivateAttr+from browser_use.browser.crash_watchdog import CrashWatchdogfrom browser_use.browser.events import (+ AboutBlankDVDScreensaverShownEvent,+ BrowserStopEvent,BrowserStoppedEvent,CloseTabEvent,NavigateToUrlEvent,@@ -24,6 +28,7 @@ class AboutBlankWatchdog(BaseWatchdog):# Event contractsLISTENS_TO: ClassVar[list[type[BaseEvent]]] = [+ BrowserStopEvent,BrowserStoppedEvent,TabCreatedEvent,TabClosedEvent,@@ -31,21 +36,40 @@ class AboutBlankWatchdog(BaseWatchdog):EMITS: ClassVar[list[type[BaseEvent]]] = [NavigateToUrlEvent,CloseTabEvent,+ AboutBlankDVDScreensaverShownEvent,]+ _stopping: bool = PrivateAttr(default=False)++ async def on_BrowserStopEvent(self, event: BrowserStopEvent) -> None:+ """Handle browser stop request - stop creating new tabs."""+ logger.info('[AboutBlankWatchdog] Browser stop requested, stopping tab creation')+ self._stopping = True+async def on_BrowserStoppedEvent(self, event: BrowserStoppedEvent) -> None:"""Handle browser stopped event."""logger.info('[AboutBlankWatchdog] Browser stopped')+ self._stopping = Trueasync def on_TabCreatedEvent(self, event: TabCreatedEvent) -> None:"""Check tabs when a new tab is created."""logger.debug(f'[AboutBlankWatchdog] Tab created: {event.url}')- await self._check_and_ensure_about_blank_tab()++ # If a new tab page was created, show DVD screensaver on it+ if CrashWatchdog._is_new_tab_page(event.url):+ await self._show_dvd_screensaver_on_about_blank_tabs()+ else:+ await self._check_and_ensure_about_blank_tab()async def on_TabClosedEvent(self, event: TabClosedEvent) -> None:"""Check tabs when a tab is closed and proactively create about:blank if needed."""logger.debug('[AboutBlankWatchdog] Tab closing, checking if we need to create about:blank tab')+ # Don't create new tabs if browser is shutting down+ if self._stopping:+ logger.debug('[AboutBlankWatchdog] Browser is stopping, not creating new tabs')+ return+# Check if we're about to close the last page (event happens BEFORE tab closes)pages = self.browser_session.pagesif len(pages) <= 1:@@ -74,7 +98,7 @@ class AboutBlankWatchdog(BaseWatchdog):expected_title = f'Starting agent {browser_session_id}...'for page in pages:- if page.url == 'about:blank':+ if CrashWatchdog._is_new_tab_page(page.url):try:page_title = await page.title()if page_title == expected_title:@@ -106,13 +130,13 @@ class AboutBlankWatchdog(BaseWatchdog):logger.error(f'[AboutBlankWatchdog] Error ensuring about:blank tab: {e}')async def _show_dvd_screensaver_on_about_blank_tabs(self) -> None:- """Show DVD screensaver on all about:blank tabs."""+ """Show DVD screensaver on all new tab pages."""try:pages = self.browser_session.pagesbrowser_session_id = str(self.browser_session.id)[-4:]for page in pages:- if page.url == 'about:blank':+ if CrashWatchdog._is_new_tab_page(page.url):await self._show_dvd_screensaver_loading_animation(page, browser_session_id)except Exception as e:@@ -123,14 +147,17 @@ class AboutBlankWatchdog(BaseWatchdog):Injects a DVD screensaver-style bouncing logo loading animation overlay into the given Playwright Page.This is used to visually indicate that the browser is setting up or waiting."""+ # Get tab index for the event+ tab_index = self.browser_session.get_tab_index(page)+try:await page.evaluate(- """(browser_session_label) => {+ """function(browser_session_label) {// Ensure document.body exists before proceedingif (!document.body) {// Try again after DOM is readyif (document.readyState === 'loading') {- document.addEventListener('DOMContentLoaded', () => arguments.callee(browser_session_label));+ document.addEventListener('DOMContentLoaded', function() { arguments.callee(browser_session_label); });}return;}@@ -226,5 +253,12 @@ class AboutBlankWatchdog(BaseWatchdog):}""",browser_session_label,)++ # Emit success event+ self.event_bus.dispatch(AboutBlankDVDScreensaverShownEvent(tab_index=tab_index, error=None))+except Exception as e:logger.debug(f'[AboutBlankWatchdog] Failed to show DVD loading animation: {type(e).__name__}: {e}')++ # Emit error event+ self.event_bus.dispatch(AboutBlankDVDScreensaverShownEvent(tab_index=tab_index, error=str(e)))diff --git a/browser_use/browser/crash_watchdog.py b/browser_use/browser/crash_watchdog.pyindex 39ba7d9a4..d7a6074db 100644--- a/browser_use/browser/crash_watchdog.py+++ b/browser_use/browser/crash_watchdog.py@@ -358,7 +358,8 @@ class CrashWatchdog(BaseWatchdog):except (asyncio.CancelledError, Exception):pass- def _is_new_tab_page(self, url: str) -> bool:+ @staticmethod+ def _is_new_tab_page(url: str) -> bool:"""Check if URL is a new tab page."""return url in ['about:blank', 'chrome://new-tab-page/', 'chrome://newtab/']diff --git a/browser_use/browser/downloads_watchdog.py b/browser_use/browser/downloads_watchdog.pyindex ff01fb6d3..4945458fc 100644--- a/browser_use/browser/downloads_watchdog.py+++ b/browser_use/browser/downloads_watchdog.py@@ -109,6 +109,7 @@ class DownloadsWatchdog(BaseWatchdog):returnlogger.info(f'[DownloadsWatchdog] Setting up download listener for page: {page.url}')+# Set up Playwright download event listenerpage.on('download', self._handle_download)# Track that we've added a listener to prevent duplicates@@ -143,51 +144,42 @@ class DownloadsWatchdog(BaseWatchdog):else:downloads_dir = str(downloads_dir) # Ensure it's a string- current_step = 'generating_unique_filename'- # Ensure unique filename- 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]}...')-- 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)}')+ # Check if Playwright already auto-downloaded the file (due to CDP setup)+ original_path = Path(downloads_dir) / suggested_filename+ if original_path.exists() and original_path.stat().st_size > 0:+ logger.info(+ f'[DownloadsWatchdog] File already downloaded by Playwright: {original_path} ({original_path.stat().st_size} bytes)'+ )- try:- 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}')- current_step = 'save_as_completed'- except Exception as save_error:- logger.error(f'[DownloadsWatchdog] save_as() failed with error: {save_error}')- if 'canceled' in str(save_error).lower():- # Download was canceled - try using the path method as fallback- logger.warning(f'[DownloadsWatchdog] save_as() was canceled, trying path() method: {save_error}')- current_step = 'using_path_fallback'- try:- # Use download.path() to access the file that was already downloaded- source_path = await download.path()- if source_path and Path(source_path).exists():- # Move the file from the temporary location to our desired location- import shutil-- shutil.move(str(source_path), str(download_path))- logger.info(f'[DownloadsWatchdog] Successfully moved download from {source_path} to: {download_path}')- current_step = 'path_fallback_completed'- else:- raise Exception(f'Downloaded file not found at path: {source_path}')- except Exception as path_error:- logger.error(f'[DownloadsWatchdog] Path fallback also failed: {path_error}')- raise save_error # Re-raise the original error- else:- # Some other save error+ # Use the existing file instead of creating a duplicate+ download_path = original_path+ file_size = original_path.stat().st_size+ unique_filename = suggested_filename+ else:+ current_step = 'generating_unique_filename'+ # Ensure unique filename+ 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]}...')++ 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)}')++ try:+ 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}')+ current_step = 'save_as_completed'+ except Exception as save_error:+ logger.error(f'[DownloadsWatchdog] save_as() failed with error: {save_error}')raise save_error- # Get file info- file_size = download_path.stat().st_size if download_path.exists() else 0+ # Get file info+ file_size = download_path.stat().st_size if download_path.exists() else 0# Determine file type from extensionfile_ext = download_path.suffix.lower().lstrip('.')diff --git a/browser_use/browser/events.py b/browser_use/browser/events.pyindex 70e956aec..569e0ecfd 100644--- a/browser_use/browser/events.py+++ b/browser_use/browser/events.py@@ -276,3 +276,25 @@ class FileDownloadedEvent(BaseEvent):mime_type: str | None = None # e.g., 'application/pdf'from_cache: bool = Falseauto_download: bool = False # Whether this was an automatic download (e.g., PDF auto-download)+++class AboutBlankDVDScreensaverShownEvent(BaseEvent):+ """AboutBlankWatchdog has shown DVD screensaver animation on an about:blank tab."""++ tab_index: int+ error: str | None = None+++# check that event names are valid and non-overlapping (naiively n^2 so it's pretty slow but ok for now, optimize when >20 events)+event_names = {+ name+ for name in globals().keys()+ if not name.startswith('_') and issubclass(globals()[name], BaseEvent) and name != 'BaseEvent'+}+for name_a in event_names:+ assert name_a.endswith('Event'), f'Event with name {name_a} does not end with "Event"'+ for name_b in event_names:+ if name_a != name_b: # Skip self-comparison+ assert name_a not in name_b, (+ f'Event with name {name_a} is a substring of {name_b}, all events must be completely unique to avoid find-and-replace accidents'+ )diff --git a/browser_use/browser/navigation_watchdog.py b/browser_use/browser/navigation_watchdog.pyindex b73f2ef04..4f26df020 100644--- a/browser_use/browser/navigation_watchdog.py+++ b/browser_use/browser/navigation_watchdog.py@@ -1,11 +1,11 @@"""Navigation watchdog for monitoring tab lifecycle and agent focus tracking."""import asyncio-from typing import TYPE_CHECKING, ClassVar+from typing import TYPE_CHECKING, Any, ClassVarfrom bubus import BaseEventfrom playwright.async_api import Page-from pydantic import Field+from pydantic import Field, PrivateAttrfrom browser_use.browser.events import (AgentFocusChangedEvent,@@ -48,6 +48,9 @@ class NavigationWatchdog(BaseWatchdog):# Agent focus tracking - using regular fields so they can be accessed as propertiespage: Page | None = Field(default=None, exclude=True)+ # Track page close handlers so we can remove them on shutdown+ _page_close_handlers: dict[Page, Any] = PrivateAttr(default_factory=dict)+async def attach_to_page(self, page: Page) -> None:"""Set up monitoring for a page - tracks page lifecycle."""page.on('close', self._handle_page_close)@@ -56,6 +59,13 @@ class NavigationWatchdog(BaseWatchdog):async def on_BrowserStoppedEvent(self, event: BrowserStoppedEvent) -> None:"""Clear agent focus when browser stops."""+ # Remove close handlers from all pages to prevent TabClosedEvent during shutdown+ for page, handler in list(self._page_close_handlers.items()):+ try:+ page.remove_listener('close', handler)+ except Exception:+ pass # Page might already be closed+ self._page_close_handlers.clear()self.page = None# ========== Tab Lifecycle Events ==========@@ -92,6 +102,11 @@ class NavigationWatchdog(BaseWatchdog):async def on_NavigateToUrlEvent(self, event: NavigateToUrlEvent) -> None:"""Handle all navigation requests with security enforcement and complete logic."""+ # Check if browser context is still available+ if not self.browser_session or not self.browser_session._browser_context:+ logger.debug('[NavigationWatchdog] No browser context 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}')@@ -336,8 +351,12 @@ class NavigationWatchdog(BaseWatchdog):"""Track a page for lifecycle events."""logger.debug(f'[NavigationWatchdog] Started tracking page: {page.url}')- # Set up page close handler- page.on('close', lambda p: self._handle_page_close(page))+ # Set up page close handler and store it so we can remove it later+ def close_handler(*args, **kwargs):+ self._handle_page_close(page)++ self._page_close_handlers[page] = close_handler+ page.on('close', close_handler)def _handle_page_close(self, page: Page) -> None:"""Handle page close event."""@@ -351,6 +370,9 @@ class NavigationWatchdog(BaseWatchdog):self.event_bus.dispatch(TabClosedEvent(tab_index=tab_index))logger.info(f'[NavigationWatchdog] Page closed, emitted TabClosedEvent for tab {tab_index}')+ # Clean up the handler from our tracking dict+ self._page_close_handlers.pop(page, None)+except Exception as e:logger.error(f'[NavigationWatchdog] Error handling page close: {e}')diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex 347ca11ce..90f18205f 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -174,13 +174,17 @@ class BrowserSession(BaseModel):self.event_bus.on(ScreenshotEvent, self.on_ScreenshotEvent)self.event_bus.on(ExecuteJavaScriptEvent, self.on_ExecuteJavaScriptEvent)- # simple logger- self.event_bus.on('*', lambda e: print(e))+ # simple logger - disabled to prevent recursion issues during cleanup+ # self.event_bus.on('*', self._log_event)# Storage state is handled by StorageStateWatchdog# ========== Event Handlers ==========+ def _log_event(self, event) -> None:+ """Simple event logger that doesn't create closures."""+ print(event)+async def on_BrowserStartEvent(self, event: BrowserStartEvent) -> None:"""Handle browser start request."""@@ -240,6 +244,27 @@ class BrowserSession(BaseModel):**self.browser_profile.kwargs_for_connect().model_dump(),)+ # Enable downloads via CDP Browser.setDownloadBehavior+ if self.browser_profile.downloads_path:+ try:+ logger.info('[Session] Attempting to set Browser.setDownloadBehavior...')+ # Get CDP session for the browser (not a specific page)+ cdp_session = await self._browser.new_browser_cdp_session()+ logger.info(f'[Session] Got CDP session: {cdp_session}')+ result = await cdp_session.send(+ 'Browser.setDownloadBehavior',+ {'behavior': 'allow', 'downloadPath': str(self.browser_profile.downloads_path)},+ )+ logger.info(f'[Session] Browser.setDownloadBehavior result: {result}')+ logger.info(+ f'[Session] Enabled downloads via Browser.setDownloadBehavior to: {self.browser_profile.downloads_path}'+ )+ except Exception as e:+ logger.error(f'[Session] Failed to set browser download behavior via CDP: {e}')+ import traceback++ logger.error(f'[Session] Traceback: {traceback.format_exc()}')+# Set up browser contextif self._browser.contexts:self._browser_context = self._browser.contexts[0]@@ -247,18 +272,6 @@ class BrowserSession(BaseModel):raise ValueError('Creating a new incognito context in an existing browser is not currently supported, you should connect to an existing browser instead')- # Get context kwargs- new_context_args = self.browser_profile.kwargs_for_new_context()- context_kwargs = new_context_args.model_dump(exclude_none=True)-- # # Log storage state info- # logger.info(f'BrowserProfile storage_state: {self.browser_profile.storage_state}')- # logger.info(f'NewContextArgs storage_state: {new_context_args.storage_state}')- # logger.info(f'Context kwargs keys: {list(context_kwargs.keys())}')- # logger.info(f'Context kwargs storage_state: {context_kwargs.get("storage_state")}')- # logger.info(f'Context kwargs accept_downloads: {context_kwargs.get("accept_downloads")}')-- self._browser_context = await self._browser.new_context(**context_kwargs)# Set initial page if existsassert self._browser_context@@ -541,6 +554,7 @@ class BrowserSession(BaseModel):def _generate_recent_events_summary(self, max_events: int = 10) -> str:"""Generate a JSON summary of recent browser events."""+ # TODO: filter/summarize/truncate any events that the LLM doesnt need to see (e.g. AboutBlankDVDScreensaverShownEvent)# Get recent events from the event bus history (it's a dict of UUID -> Event)all_events = list(self.event_bus.event_history.values())diff --git a/browser_use/browser/storage_state_watchdog.py b/browser_use/browser/storage_state_watchdog.pyindex a3c44b0a4..b9aafad90 100644--- a/browser_use/browser/storage_state_watchdog.py+++ b/browser_use/browser/storage_state_watchdog.py@@ -61,11 +61,15 @@ class StorageStateWatchdog(BaseWatchdog):logger.info('[StorageStateWatchdog] Browser stop requested, saving final storage state')# Save storage state before stopping and wait for completion+ logger.info('[StorageStateWatchdog] Dispatching SaveStorageStateEvent...')save_event = self.event_bus.dispatch(SaveStorageStateEvent())+ logger.info('[StorageStateWatchdog] Waiting for save event to complete...')await save_event+ logger.info('[StorageStateWatchdog] Save event completed, stopping monitoring...')# Stop monitoringawait self._stop_monitoring()+ logger.info('[StorageStateWatchdog] Browser stop handling complete')# No cleanup needed - browser context is managed by sessionasync def on_SaveStorageStateEvent(self, event: SaveStorageStateEvent) -> None:diff --git a/tests/ci/conftest.py b/tests/ci/conftest.pyindex d3c9be8f0..25d0333aa 100644--- a/tests/ci/conftest.py+++ b/tests/ci/conftest.py@@ -168,6 +168,8 @@ async def browser_session():await session.start()yield sessionawait session.kill()+ # Ensure event bus is properly stopped+ await session.event_bus.stop(clear=True, timeout=5)@pytest.fixture(scope='function')diff --git a/tests/ci/test_aboutblank_watchdog.py b/tests/ci/test_aboutblank_watchdog.pyindex 013ce2ff1..adc0e6c42 100644--- a/tests/ci/test_aboutblank_watchdog.py+++ b/tests/ci/test_aboutblank_watchdog.py@@ -5,6 +5,7 @@ import asyncioimport pytestfrom browser_use.browser.events import (+ AboutBlankDVDScreensaverShownEvent,BrowserConnectedEvent,BrowserStartEvent,BrowserStopEvent,@@ -33,8 +34,25 @@ async def test_aboutblank_watchdog_lifecycle():finally:# Stop browser- session.event_bus.dispatch(BrowserStopEvent())- await session.event_bus.expect(BrowserStoppedEvent, timeout=5.0)+ stop_event = session.event_bus.dispatch(BrowserStopEvent())+ try:+ await asyncio.wait_for(session.event_bus.expect(BrowserStoppedEvent), timeout=5.0)+ except TimeoutError:+ print('BrowserStoppedEvent timed out')++ # Force close browser context if it exists+ try:+ if hasattr(session, '_browser_context') and session._browser_context:+ await session._browser_context.close()+ except Exception:+ pass++ # Stop playwright if it exists+ try:+ if hasattr(session, '_playwright') and session._playwright:+ await session._playwright.stop()+ except Exception:+ pass@pytest.mark.asyncio@@ -62,8 +80,25 @@ async def test_aboutblank_watchdog_creates_animation_tab():finally:# Stop browser- session.event_bus.dispatch(BrowserStopEvent())- await session.event_bus.expect(BrowserStoppedEvent, timeout=5.0)+ stop_event = session.event_bus.dispatch(BrowserStopEvent())+ try:+ await asyncio.wait_for(session.event_bus.expect(BrowserStoppedEvent), timeout=5.0)+ except TimeoutError:+ print('BrowserStoppedEvent timed out')++ # Force close browser context if it exists+ try:+ if hasattr(session, '_browser_context') and session._browser_context:+ await session._browser_context.close()+ except Exception:+ pass++ # Stop playwright if it exists+ try:+ if hasattr(session, '_playwright') and session._playwright:+ await session._playwright.stop()+ except Exception:+ pass@pytest.mark.asyncio@@ -93,8 +128,25 @@ async def test_aboutblank_watchdog_handles_tab_creation():finally:# Stop browser- session.event_bus.dispatch(BrowserStopEvent())- await session.event_bus.expect(BrowserStoppedEvent, timeout=5.0)+ stop_event = session.event_bus.dispatch(BrowserStopEvent())+ try:+ await asyncio.wait_for(session.event_bus.expect(BrowserStoppedEvent), timeout=5.0)+ except TimeoutError:+ print('BrowserStoppedEvent timed out')++ # Force close browser context if it exists+ try:+ if hasattr(session, '_browser_context') and session._browser_context:+ await session._browser_context.close()+ except Exception:+ pass++ # Stop playwright if it exists+ try:+ if hasattr(session, '_playwright') and session._playwright:+ await session._playwright.stop()+ except Exception:+ pass@pytest.mark.asyncio@@ -130,8 +182,25 @@ async def test_aboutblank_watchdog_dvd_screensaver():finally:# Stop browser- session.event_bus.dispatch(BrowserStopEvent())- await session.event_bus.expect(BrowserStoppedEvent, timeout=5.0)+ stop_event = session.event_bus.dispatch(BrowserStopEvent())+ try:+ await asyncio.wait_for(session.event_bus.expect(BrowserStoppedEvent), timeout=5.0)+ except TimeoutError:+ print('BrowserStoppedEvent timed out')++ # Force close browser context if it exists+ try:+ if hasattr(session, '_browser_context') and session._browser_context:+ await session._browser_context.close()+ except Exception:+ pass++ # Stop playwright if it exists+ try:+ if hasattr(session, '_playwright') and session._playwright:+ await session._playwright.stop()+ except Exception:+ pass@pytest.mark.asyncio@@ -169,11 +238,29 @@ async def test_aboutblank_watchdog_animation_tab_management():finally:# Stop browser- session.event_bus.dispatch(BrowserStopEvent())- await session.event_bus.expect(BrowserStoppedEvent, timeout=5.0)+ stop_event = session.event_bus.dispatch(BrowserStopEvent())+ try:+ await asyncio.wait_for(session.event_bus.expect(BrowserStoppedEvent), timeout=5.0)+ except TimeoutError:+ print('BrowserStoppedEvent timed out')++ # Force close browser context if it exists+ try:+ if hasattr(session, '_browser_context') and session._browser_context:+ await session._browser_context.close()+ except Exception:+ pass++ # Stop playwright if it exists+ try:+ if hasattr(session, '_playwright') and session._playwright:+ await session._playwright.stop()+ except Exception:+ pass@pytest.mark.asyncioasync def test_aboutblank_watchdog_javascript_execution():"""Test that the DVD screensaver JavaScript executes without errors."""profile = BrowserProfile(headless=True)@@ -184,55 +271,69 @@ async def test_aboutblank_watchdog_javascript_execution():session.event_bus.dispatch(BrowserStartEvent())await session.event_bus.expect(BrowserConnectedEvent, timeout=5.0)- # Create an about:blank page- session.event_bus.dispatch(NavigateToUrlEvent(url='about:blank', new_tab=True))- await asyncio.sleep(0.5)+ # Test 1: Initial new tab should get animation+ # The watchdog should detect the chrome://newtab/ page is a new tab and show animation+ initial_pages = session.pages+ assert len(initial_pages) == 1, 'Should have one initial tab'+ assert 'newtab' in initial_pages[0].url or 'new-tab-page' in initial_pages[0].url, 'Initial tab should be a new tab page'- # Get the about:blank page- pages = session.pages- about_blank_page = next((p for p in pages if p.url == 'about:blank'), None)- assert about_blank_page is not None, 'Should have an about:blank page'+ # Wait for AboutBlankWatchdog to show DVD screensaver on the initial new tab+ dvd_event1 = await session.event_bus.expect(AboutBlankDVDScreensaverShownEvent, timeout=10.0)+ assert dvd_event1.error is None, f'DVD screensaver failed on initial tab: {dvd_event1.error}'- # Get aboutblank watchdog- watchdog = session._aboutblank_watchdog+ # Get the page and verify animation+ page1 = session.get_page_by_tab_index(dvd_event1.tab_index)+ assert page1 is not None, f'Could not find page at tab index {dvd_event1.tab_index}'++ # Verify the animation was created+ animation_exists = await page1.evaluate("""() => {+ return document.getElementById('pretty-loading-animation') !== null;+ }""")+ assert animation_exists, 'DVD screensaver animation should have been created on initial tab'++ # Test 2: Close the tab and verify watchdog creates new about:blank tab with animation+ await page1.close()++ # Wait for new about:blank tab to be created and animation shown+ dvd_event2 = await session.event_bus.expect(AboutBlankDVDScreensaverShownEvent, timeout=10.0)+ assert dvd_event2.error is None, f'DVD screensaver failed on auto-created tab: {dvd_event2.error}'++ # Get the new page+ page2 = 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'++ # Verify animation on the new tab+ animation_exists2 = await page2.evaluate("""() => {+ return document.getElementById('pretty-loading-animation') !== null;+ }""")+ assert animation_exists2, 'DVD screensaver animation should have been created on auto-created tab'- # Capture console errors+ # Verify no JavaScript errors occurred (particularly arguments.callee)console_errors = []- async def capture_console_error(msg):+ async def capture_console(msg):if msg.type == 'error':console_errors.append(msg.text)- about_blank_page.on('console', capture_console_error)-- # Try to inject the DVD screensaver- browser_session_id = str(session.id)[-4:]- await watchdog._show_dvd_screensaver_loading_animation(about_blank_page, browser_session_id)-- # Give time for any errors to surface+ page2.on('console', capture_console)await asyncio.sleep(0.5)- # Check for console errorsif console_errors:- # Check specifically for arguments.callee errorfor error in console_errors:- if 'arguments' in error.lower() and ('callee' in error.lower() or 'arrow function' in error.lower()):- pytest.fail(f'JavaScript error related to arguments.callee in arrow function: {error}')- # Also fail on any other errors for completeness- pytest.fail(f'JavaScript console error: {error}')+ if 'arguments' in error.lower():+ pytest.fail(f'JavaScript error detected: {error}')- # Also verify the animation was actually created- animation_exists = await about_blank_page.evaluate("""() => {- return document.getElementById('pretty-loading-animation') !== null;- }""")- assert animation_exists, 'DVD screensaver animation should have been created'+ finally:+ # Allow any pending operations to complete+ await asyncio.sleep(0.5)- # Check that the title was set- title = await about_blank_page.title()- expected_title = f'Starting agent {browser_session_id}...'- assert title == expected_title, f'Title should be "{expected_title}" but was "{title}"'+ # Stop browser properly through the session+ stop_event = session.event_bus.dispatch(BrowserStopEvent())+ try:+ await asyncio.wait_for(stop_event, timeout=5.0)+ except TimeoutError:+ print('BrowserStopEvent processing timed out')- finally:- # Stop browser- session.event_bus.dispatch(BrowserStopEvent())- await session.event_bus.expect(BrowserStoppedEvent, timeout=5.0)+ # Wait a bit more for playwright internal cleanup+ await asyncio.sleep(1.0)diff --git a/tests/ci/test_downloads_watchdog.py b/tests/ci/test_downloads_watchdog.pyindex 9c0a54a11..63773476d 100644--- a/tests/ci/test_downloads_watchdog.py+++ b/tests/ci/test_downloads_watchdog.py@@ -89,6 +89,8 @@ async def test_downloads_watchdog_lifecycle():except Exception:# If graceful shutdown fails, force cleanupawait session.kill()+ # Always stop event bus to prevent hanging+ await session.event_bus.stop(clear=True, timeout=5)@pytest.mark.asyncio@@ -117,23 +119,33 @@ async def test_downloads_watchdog_file_detection(download_test_server):await session.navigate(test_url)# Click download link to trigger download- try:- await session.click('a[href="/download/test.pdf"]')+ await session.click('a[href="/download/test.pdf"]')++ # Wait for download to complete+ await asyncio.sleep(2.0)++ # Verify file was downloaded with correct content+ downloaded_files = list(downloads_path.glob('*.pdf'))+ assert len(downloaded_files) > 0, 'PDF download must succeed - no files downloaded is not acceptable'++ downloaded_file = downloaded_files[0]+ assert downloaded_file.exists(), f'Downloaded PDF file must exist: {downloaded_file}'- # Wait for download to complete- await asyncio.sleep(2.0)+ # Verify file size and content (we sent 'fake pdf content' which is 25 bytes)+ file_size = downloaded_file.stat().st_size+ assert file_size == 25, f'Downloaded PDF must be 25 bytes (fake pdf content), got {file_size} bytes'- # Check if file was downloaded- downloaded_files = list(downloads_path.glob('*.pdf'))- if downloaded_files:- # Verify FileDownloadedEvent was emitted- pdf_events = [e for e in download_events if 'pdf' in e.path.lower()]- # Note: Download detection can be flaky in headless mode, so we don't assert- # assert len(pdf_events) > 0, "Should have detected PDF download"+ file_content = downloaded_file.read_bytes()+ expected_content = b'%PDF-1.4 fake pdf content'+ assert file_content == expected_content, (+ f'Downloaded PDF content must match. Expected: {expected_content!r}, got: {file_content!r}'+ )- except Exception as e:- # Download clicks can be flaky in test environment- print(f'Download test encountered expected issue: {e}')+ # Verify FileDownloadedEvent was emitted+ pdf_events = [e for e in download_events if 'pdf' in e.path.lower()]+ assert len(pdf_events) > 0, 'FileDownloadedEvent must be dispatched for PDF download'++ print(f'✅ PDF download successful: {downloaded_file} ({file_size} bytes) with correct content')finally:# Clean shutdown@@ -143,6 +155,8 @@ async def test_downloads_watchdog_file_detection(download_test_server):except Exception:# If graceful shutdown fails, force cleanupawait session.kill()+ # Always stop event bus to prevent hanging+ await session.event_bus.stop(clear=True, timeout=5)@pytest.mark.asyncio@@ -186,6 +200,8 @@ async def test_downloads_watchdog_page_attachment():except Exception:# If graceful shutdown fails, force cleanupawait session.kill()+ # Always stop event bus to prevent hanging+ await session.event_bus.stop(clear=True, timeout=5)@pytest.mark.asyncio@@ -216,6 +232,8 @@ async def test_downloads_watchdog_default_downloads_path():except Exception:# If graceful shutdown fails, force cleanupawait session.kill()+ # Always stop event bus to prevent hanging+ await session.event_bus.stop(clear=True, timeout=5)@pytest.mark.asyncio@@ -339,6 +357,7 @@ async def test_downloads_watchdog_detection_timing(comprehensive_download_test_sassert result is None # No download happenedawait browser_with_downloads.close()+ await browser_with_downloads.event_bus.stop(clear=True, timeout=5)# Test 2: With downloads_dir set to None (disables download detection)browser_no_downloads = BrowserSession(@@ -383,6 +402,7 @@ async def test_downloads_watchdog_detection_timing(comprehensive_download_test_sassert result_text == 'Clicked!'await browser_no_downloads.close()+ await browser_no_downloads.event_bus.stop(clear=True, timeout=5)# Check timing differencesprint(f'Click with downloads_dir: {duration_with_downloads:.2f}s')@@ -464,33 +484,29 @@ async def test_downloads_watchdog_actual_download_detection(comprehensive_downlofiles = os.listdir(downloads_path)print(f'Files in downloads directory: {files}')- # Check if files were actually downloaded- if len(downloaded_files) > 0:- # Check the most recent download- latest_download = downloaded_files[0] # Files are sorted by newest first- assert 'test.pdf' in latest_download- assert os.path.exists(latest_download)+ # Verify files were actually downloaded with correct content+ assert len(downloaded_files) > 0, 'Download must succeed - no files downloaded is not acceptable'- # Verify the file size is correct (we sent 'PDF content' which is 11 bytes)- file_size = os.path.getsize(latest_download)- assert file_size == 11, f'Expected 11 bytes, got {file_size}'+ # Check the most recent download+ latest_download = downloaded_files[0] # Files are sorted by newest first+ assert 'test.pdf' in latest_download, f'Downloaded file should be named test.pdf, got: {latest_download}'+ assert os.path.exists(latest_download), f'Downloaded file must exist on disk: {latest_download}'- # Should be relatively fast since download is detected- assert duration < 2.0, f'Download click took {duration:.2f}s, expected <2s'- else:- # Downloads can be flaky in headless test environment- # Verify that at least the download mechanism was triggered- print('Warning: No files downloaded in test environment')- print('This is expected in headless mode - download detection is working')+ # Verify the file has the correct content and size+ file_size = os.path.getsize(latest_download)+ assert file_size == 11, f'Downloaded file must be 11 bytes (PDF content), got {file_size} bytes'- # Verify the download click was attempted and took reasonable time- assert duration < 15.0, f'Download click took {duration:.2f}s, should be fast even if download fails'+ # Verify the actual file content matches what the server sent+ file_content = Path(latest_download).read_bytes()+ expected_content = b'PDF content'+ assert file_content == expected_content, (+ f'Downloaded file content must match. Expected: {expected_content!r}, got: {file_content!r}'+ )- # Verify the downloads watchdog exists and is configured- assert browser_session._downloads_watchdog is not None- assert browser_session.browser_profile.downloads_path is not None+ print(f'✅ Download successful: {latest_download} ({file_size} bytes) with correct content: {file_content!r}')await browser_session.close()+ await browser_session.event_bus.stop(clear=True, timeout=5)@pytest.mark.asyncio@@ -526,26 +542,33 @@ async def test_downloads_watchdog_event_dispatching(comprehensive_download_test_event_history = list(browser_session.event_bus.event_history.values())download_events = [e for e in event_history if isinstance(e, FileDownloadedEvent)]- if len(download_events) >= 1:- # Verify the event contains correct information- latest_download_event = download_events[-1]- assert latest_download_event.path is not None- assert 'test.pdf' in latest_download_event.path- assert os.path.exists(latest_download_event.path)- else:- # Downloads can be flaky in headless test environment- print('Warning: No FileDownloadedEvent dispatched in test environment')- print('This is expected in headless mode - event system is working')-- # Verify the downloads watchdog exists and is monitoring- assert browser_session._downloads_watchdog is not None- assert browser_session.browser_profile.downloads_path is not None-- # Verify event history is being tracked (should have other events)- # Check that event history increased (browser start, tab creation, navigation events)- print(f'Initial event count: {initial_history_count}, Current event count: {len(event_history)}')- # Should have at least a few events from browser startup, tab creation, navigation- assert len(event_history) >= 5, f'Event bus should be tracking events, got {len(event_history)}'+ # FileDownloadedEvent must be dispatched - no failures accepted+ assert len(download_events) >= 1, 'FileDownloadedEvent must be dispatched when download succeeds - no failures acceptable'++ # Verify the event contains correct information+ latest_download_event = download_events[-1]+ assert latest_download_event.path is not None, 'FileDownloadedEvent must have a valid path'+ assert 'test.pdf' in latest_download_event.path, (+ f'FileDownloadedEvent path should contain test.pdf, got: {latest_download_event.path}'+ )+ assert os.path.exists(latest_download_event.path), (+ f'FileDownloadedEvent path must exist on disk: {latest_download_event.path}'+ )++ # Verify the downloaded file has correct content and size+ file_size = os.path.getsize(latest_download_event.path)+ assert file_size == 11, f'Downloaded file from event must be 11 bytes (PDF content), got {file_size} bytes'++ file_content = Path(latest_download_event.path).read_bytes()+ expected_content = b'PDF content'+ assert file_content == expected_content, (+ f'Downloaded file content must match. Expected: {expected_content!r}, got: {file_content!r}'+ )++ print(+ f'✅ FileDownloadedEvent dispatched correctly for: {latest_download_event.path} ({file_size} bytes) with correct content: {file_content!r}'+ )finally:await browser_session.kill()+ await browser_session.event_bus.stop(clear=True, timeout=5)