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
replace wait for download action w automatic wait listener
Laith Weinberger84b460d6ce55
diff --git a/browser_use/browser/events.py b/browser_use/browser/events.pyindex 4c40cb428..d7c0d9377 100644--- a/browser_use/browser/events.py+++ b/browser_use/browser/events.py@@ -521,9 +521,32 @@ class StorageStateLoadedEvent(BaseEvent):# ============================================================================+class DownloadStartedEvent(BaseEvent):+ """A file download has started (CDP downloadWillBegin received)."""++ guid: str # CDP download GUID to correlate with FileDownloadedEvent+ url: str+ suggested_filename: str+ auto_download: bool = False # Whether this was triggered automatically++ event_timeout: float | None = Field(default_factory=lambda: _get_timeout('TIMEOUT_DownloadStartedEvent', 5.0)) # seconds+++class DownloadProgressEvent(BaseEvent):+ """A file download progress update (CDP downloadProgress received)."""++ guid: str # CDP download GUID to correlate with other download events+ received_bytes: int+ total_bytes: int # 0 if unknown+ state: str # 'inProgress', 'completed', or 'canceled'++ event_timeout: float | None = Field(default_factory=lambda: _get_timeout('TIMEOUT_DownloadProgressEvent', 5.0)) # seconds++class FileDownloadedEvent(BaseEvent):"""A file has been downloaded."""+ guid: str | None = None # CDP download GUID to correlate with DownloadStartedEventurl: strpath: strfile_name: strdiff --git a/browser_use/browser/watchdogs/default_action_watchdog.py b/browser_use/browser/watchdogs/default_action_watchdog.pyindex ed584fb6d..29ed8a884 100644--- a/browser_use/browser/watchdogs/default_action_watchdog.py+++ b/browser_use/browser/watchdogs/default_action_watchdog.py@@ -10,6 +10,9 @@ from browser_use.actor.utils import get_key_infofrom browser_use.browser.events import (ClickCoordinateEvent,ClickElementEvent,+ DownloadProgressEvent,+ DownloadStartedEvent,+ FileDownloadedEvent,GetDropdownOptionsEvent,GoBackEvent,GoForwardEvent,@@ -41,6 +44,187 @@ UploadFileEvent.model_rebuild()class DefaultActionWatchdog(BaseWatchdog):"""Handles default browser actions like click, type, and scroll using CDP."""+ async def _execute_click_with_download_detection(+ self,+ click_coro,+ download_start_timeout: float = 0.5,+ download_complete_timeout: float = 30.0,+ ) -> dict | None:+ """Execute a click operation and automatically wait for any triggered download++ Args:+ click_coro: Coroutine that performs the click (should return click_metadata dict or None)+ download_start_timeout: Time to wait for download to start after click (seconds)+ download_complete_timeout: Time to wait for download to complete once started (seconds)++ Returns:+ Click metadata dict, potentially with 'download' key containing download info.+ If a download times out but is still in progress, includes 'download_in_progress' with status.+ """+ import time++ download_started = asyncio.Event()+ download_completed = asyncio.Event()+ download_info: dict = {}+ progress_info: dict = {'last_update': 0.0, 'received_bytes': 0, 'total_bytes': 0, 'state': ''}++ def on_download_start(info: dict) -> None:+ """Direct callback when download starts (called from CDP handler)."""+ if info.get('auto_download'):+ return # ignore auto-downloads+ download_info['guid'] = info.get('guid', '')+ download_info['url'] = info.get('url', '')+ download_info['suggested_filename'] = info.get('suggested_filename', 'download')+ download_started.set()+ self.logger.debug(f'[ClickWithDownload] Download started: {download_info["suggested_filename"]}')++ def on_download_progress(info: dict) -> None:+ """Direct callback when download progress updates (called from CDP handler)."""+ # Match by guid if available+ if download_info.get('guid') and info.get('guid') != download_info['guid']:+ return # different download+ progress_info['last_update'] = time.time()+ progress_info['received_bytes'] = info.get('received_bytes', 0)+ progress_info['total_bytes'] = info.get('total_bytes', 0)+ progress_info['state'] = info.get('state', '')+ self.logger.debug(+ f'[ClickWithDownload] Progress: {progress_info["received_bytes"]}/{progress_info["total_bytes"]} bytes ({progress_info["state"]})'+ )++ def on_download_complete(info: dict) -> None:+ """Direct callback when download completes (called from CDP handler)."""+ if info.get('auto_download'):+ return # ignore auto-downloads+ # Match by guid if available, otherwise accept any non-auto download+ if download_info.get('guid') and info.get('guid') and info.get('guid') != download_info['guid']:+ return # different download+ download_info['path'] = info.get('path', '')+ download_info['file_name'] = info.get('file_name', '')+ download_info['file_size'] = info.get('file_size', 0)+ download_info['file_type'] = info.get('file_type')+ download_info['mime_type'] = info.get('mime_type')+ download_completed.set()+ self.logger.debug(f'[ClickWithDownload] Download completed: {download_info["file_name"]}')++ # Get the downloads watchdog and register direct callbacks+ downloads_watchdog = self.browser_session._downloads_watchdog+ import sys; print(f'[DEBUG] downloads_watchdog={downloads_watchdog is not None}', file=sys.stderr) # TEMP DEBUG+ self.logger.debug(f'[ClickWithDownload] downloads_watchdog={downloads_watchdog is not None}')+ if downloads_watchdog:+ self.logger.debug('[ClickWithDownload] Registering download callbacks...')+ downloads_watchdog.register_download_callbacks(+ on_start=on_download_start,+ on_progress=on_download_progress,+ on_complete=on_download_complete,+ )+ else:+ self.logger.warning('[ClickWithDownload] No downloads_watchdog available!')++ try:+ # Perform the click+ click_metadata = await click_coro++ # Check for validation errors - return them immediately without waiting for downloads+ if isinstance(click_metadata, dict) and 'validation_error' in click_metadata:+ return click_metadata++ # Wait briefly to see if a download starts+ try:+ await asyncio.wait_for(download_started.wait(), timeout=download_start_timeout)++ # Download started!+ self.logger.info(f'📥 Download started: {download_info.get("suggested_filename", "unknown")}')++ # Now wait for it to complete with longer timeout+ try:+ await asyncio.wait_for(download_completed.wait(), timeout=download_complete_timeout)++ # Download completed successfully+ msg = f'Downloaded file: {download_info["file_name"]} ({download_info["file_size"]} bytes) saved to {download_info["path"]}'+ self.logger.info(f'💾 {msg}')++ # Merge download info into click_metadata+ if click_metadata is None:+ click_metadata = {}+ click_metadata['download'] = {+ 'path': download_info['path'],+ 'file_name': download_info['file_name'],+ 'file_size': download_info['file_size'],+ 'file_type': download_info.get('file_type'),+ 'mime_type': download_info.get('mime_type'),+ }+ except TimeoutError:+ # Download timed out - check if it's still in progress+ if click_metadata is None:+ click_metadata = {}++ filename = download_info.get('suggested_filename', 'unknown')+ received = progress_info.get('received_bytes', 0)+ total = progress_info.get('total_bytes', 0)+ state = progress_info.get('state', 'unknown')+ last_update = progress_info.get('last_update', 0.0)+ time_since_update = time.time() - last_update if last_update > 0 else float('inf')++ # Check if download is still actively progressing (received update in last 5 seconds)+ is_still_active = time_since_update < 5.0 and state == 'inProgress'++ if is_still_active:+ # Download is still progressing - suggest waiting+ if total > 0:+ percent = (received / total) * 100+ progress_str = f'{percent:.1f}% ({received:,}/{total:,} bytes)'+ else:+ progress_str = f'{received:,} bytes downloaded (total size unknown)'++ msg = (+ f'Download timed out after {download_complete_timeout}s but is still in progress: '+ f'{filename} - {progress_str}. '+ f'The download appears to be progressing normally. Consider using the wait action '+ f'to allow more time for the download to complete.'+ )+ self.logger.warning(f'⏱️ {msg}')+ click_metadata['download_in_progress'] = {+ 'file_name': filename,+ 'received_bytes': received,+ 'total_bytes': total,+ 'state': state,+ 'message': msg,+ }+ else:+ # Download may be stalled or completed+ if received > 0:+ msg = (+ f'Download timed out after {download_complete_timeout}s: {filename}. '+ f'Last progress: {received:,} bytes received. '+ f'The download may have stalled or completed - check the downloads folder.'+ )+ else:+ msg = (+ f'Download timed out after {download_complete_timeout}s: {filename}. '+ f'No progress data received - the download may have failed to start properly.'+ )+ self.logger.warning(f'⏱️ {msg}')+ click_metadata['download_timeout'] = {+ 'file_name': filename,+ 'received_bytes': received,+ 'total_bytes': total,+ 'message': msg,+ }+ except TimeoutError:+ # No download started within grace period+ pass++ return click_metadata if isinstance(click_metadata, dict) else None++ finally:+ # Unregister download callbacks+ if downloads_watchdog:+ downloads_watchdog.unregister_download_callbacks(+ on_start=on_download_start,+ on_progress=on_download_progress,+ on_complete=on_download_complete,+ )+def _is_print_related_element(self, element_node: EnhancedDOMTreeNode) -> bool:"""Check if an element is related to printing (print buttons, print dialogs, etc.).@@ -155,7 +339,7 @@ class DefaultActionWatchdog(BaseWatchdog):@observe_debug(ignore_input=True, ignore_output=True, name='click_element_event')async def on_ClickElementEvent(self, event: ClickElementEvent) -> dict | None:- """Handle click request with CDP."""+ """Handle click request with CDP. Automatically waits for file downloads if triggered."""try:# Check if session is alive before attempting any operationsif not self.browser_session.agent_focus_target_id:@@ -166,13 +350,11 @@ class DefaultActionWatchdog(BaseWatchdog):# Use the provided nodeelement_node = event.nodeindex_for_logging = element_node.backend_node_id or 'unknown'- starting_target_id = self.browser_session.agent_focus_target_id# Check if element is a file input (should not be clicked)if self.browser_session.is_file_input(element_node):msg = f'Index {index_for_logging} - has an element which opens file upload dialog. To upload files please use a specific function to upload files'self.logger.info(f'{msg}')- # Return validation error instead of raising to avoid ERROR logsreturn {'validation_error': msg}# Detect print-related elements and handle them specially@@ -181,42 +363,37 @@ class DefaultActionWatchdog(BaseWatchdog):self.logger.info(f'🖨️ Detected print button (index {index_for_logging}), generating PDF directly instead of opening dialog...')-- # Instead of clicking, directly generate PDF via CDPclick_metadata = await self._handle_print_button_click(element_node)-if click_metadata and click_metadata.get('pdf_generated'):msg = f'Generated PDF: {click_metadata.get("path")}'self.logger.info(f'💾 {msg}')return click_metadataelse:- # Fallback to regular click if PDF generation failedself.logger.warning('⚠️ PDF generation failed, falling back to regular click')- # Perform the actual click using internal implementation- click_metadata = await self._click_element_node_impl(element_node)- download_path = None # moved to downloads_watchdog.py+ # Execute click with automatic download detection+ click_metadata = await self._execute_click_with_download_detection(+ self._click_element_node_impl(element_node)+ )- # Check for validation errors - return them without raising to avoid ERROR logs+ # Check for validation errorsif isinstance(click_metadata, dict) and 'validation_error' in click_metadata:self.logger.info(f'{click_metadata["validation_error"]}')return click_metadata- # Build success message- if download_path:- msg = f'Downloaded file to {download_path}'- self.logger.info(f'💾 {msg}')- else:+ # Build success message for non-download clicks+ if 'download' not in (click_metadata or {}):msg = f'Clicked button {element_node.node_name}: {element_node.get_all_children_text(max_depth=2)}'self.logger.debug(f'🖱️ {msg}')self.logger.debug(f'Element xpath: {element_node.xpath}')- return click_metadata if isinstance(click_metadata, dict) else None- except Exception as e:+ return click_metadata++ except Exception:raiseasync def on_ClickCoordinateEvent(self, event: ClickCoordinateEvent) -> dict | None:- """Handle click at coordinates with CDP."""+ """Handle click at coordinates with CDP. Automatically waits for file downloads if triggered."""try:# Check if session is alive before attempting any operationsif not self.browser_session.agent_focus_target_id:@@ -224,19 +401,23 @@ class DefaultActionWatchdog(BaseWatchdog):self.logger.error(f'{error_msg}')raise BrowserError(error_msg)- # If force=True, skip safety checks and click directly+ # If force=True, skip safety checks and click directly (with download detection)if event.force:self.logger.debug(f'Force clicking at coordinates ({event.coordinate_x}, {event.coordinate_y})')- return await self._click_on_coordinate(event.coordinate_x, event.coordinate_y, force=True)+ return await self._execute_click_with_download_detection(+ self._click_on_coordinate(event.coordinate_x, event.coordinate_y, force=True)+ )# Get element at coordinates for safety checkselement_node = await self.browser_session.get_dom_element_at_coordinates(event.coordinate_x, event.coordinate_y)if element_node is None:- # No element found, click directly+ # No element found, click directly (with download detection)self.logger.debug(f'No element found at coordinates ({event.coordinate_x}, {event.coordinate_y}), proceeding with click anyway')- return await self._click_on_coordinate(event.coordinate_x, event.coordinate_y, force=False)+ return await self._execute_click_with_download_detection(+ self._click_on_coordinate(event.coordinate_x, event.coordinate_y, force=False)+ )# Safety check: file inputif self.browser_session.is_file_input(element_node):@@ -265,8 +446,10 @@ class DefaultActionWatchdog(BaseWatchdog):else:self.logger.warning('⚠️ PDF generation failed, falling back to regular click')- # All safety checks passed, click at coordinates- return await self._click_on_coordinate(event.coordinate_x, event.coordinate_y, force=False)+ # All safety checks passed, click at coordinates (with download detection)+ return await self._execute_click_with_download_detection(+ self._click_on_coordinate(event.coordinate_x, event.coordinate_y, force=False)+ )except Exception:raisediff --git a/browser_use/browser/watchdogs/downloads_watchdog.py b/browser_use/browser/watchdogs/downloads_watchdog.pyindex 71b40dfce..d759a8d55 100644--- a/browser_use/browser/watchdogs/downloads_watchdog.py+++ b/browser_use/browser/watchdogs/downloads_watchdog.py@@ -19,6 +19,8 @@ from browser_use.browser.events import (BrowserLaunchEvent,BrowserStateRequestEvent,BrowserStoppedEvent,+ DownloadProgressEvent,+ DownloadStartedEvent,FileDownloadedEvent,NavigationCompleteEvent,TabClosedEvent,@@ -46,6 +48,8 @@ class DownloadsWatchdog(BaseWatchdog):# Events this watchdog emitsEMITS: ClassVar[list[type[BaseEvent[Any]]]] = [+ DownloadProgressEvent,+ DownloadStartedEvent,FileDownloadedEvent,]@@ -63,6 +67,45 @@ class DownloadsWatchdog(BaseWatchdog):_detected_downloads: set[str] = PrivateAttr(default_factory=set) # Track detected download URLs to avoid duplicates_network_callback_registered: bool = PrivateAttr(default=False) # Track if global network callback is registered+ # Direct callback support for download waiting (bypasses event bus for synchronization)+ _download_start_callbacks: list[Any] = PrivateAttr(default_factory=list) # Callbacks for download start+ _download_progress_callbacks: list[Any] = PrivateAttr(default_factory=list) # Callbacks for download progress+ _download_complete_callbacks: list[Any] = PrivateAttr(default_factory=list) # Callbacks for download complete++ def register_download_callbacks(+ self,+ on_start: Any | None = None,+ on_progress: Any | None = None,+ on_complete: Any | None = None,+ ) -> None:+ """Register direct callbacks for download events++ Callbacks called sync from CDP event handlers, so click+ handlers receive download notif without waiting for event bus to process+ """+ self.logger.debug(f'[DownloadsWatchdog] Registering callbacks: start={on_start is not None}, progress={on_progress is not None}, complete={on_complete is not None}')+ if on_start:+ self._download_start_callbacks.append(on_start)+ self.logger.debug(f'[DownloadsWatchdog] Registered start callback, now have {len(self._download_start_callbacks)} start callbacks')+ if on_progress:+ self._download_progress_callbacks.append(on_progress)+ if on_complete:+ self._download_complete_callbacks.append(on_complete)++ def unregister_download_callbacks(+ self,+ on_start: Any | None = None,+ on_progress: Any | None = None,+ on_complete: Any | None = None,+ ) -> None:+ """Unregister previously registered download callbacks."""+ if on_start and on_start in self._download_start_callbacks:+ self._download_start_callbacks.remove(on_start)+ if on_progress and on_progress in self._download_progress_callbacks:+ self._download_progress_callbacks.remove(on_progress)+ if on_complete and on_complete in self._download_complete_callbacks:+ self._download_complete_callbacks.remove(on_complete)+async def on_BrowserLaunchEvent(self, event: BrowserLaunchEvent) -> None:self.logger.debug(f'[DownloadsWatchdog] Received BrowserLaunchEvent, EventBus ID: {id(self.event_bus)}')# Ensure downloads directory exists@@ -184,16 +227,43 @@ class DownloadsWatchdog(BaseWatchdog):self.logger.debug(f'[DownloadsWatchdog] Download will begin: {event}')# Cache info for later completion event handling (esp. remote browsers)guid = event.get('guid', '')+ url = event.get('url', '')+ suggested_filename = event.get('suggestedFilename', 'download')try:- suggested_filename = event.get('suggestedFilename')assert suggested_filename, 'CDP DownloadWillBegin missing suggestedFilename'self._cdp_downloads_info[guid] = {- 'url': event.get('url', ''),+ 'url': url,'suggested_filename': suggested_filename,'handled': False,}except (AssertionError, KeyError):pass++ # Call direct callbacks first (for click handlers waiting for downloads)+ download_info = {+ 'guid': guid,+ 'url': url,+ 'suggested_filename': suggested_filename,+ 'auto_download': False,+ }+ self.logger.debug(f'[DownloadsWatchdog] Calling {len(self._download_start_callbacks)} start callbacks')+ for callback in self._download_start_callbacks:+ try:+ self.logger.debug(f'[DownloadsWatchdog] Calling start callback: {callback}')+ callback(download_info)+ except Exception as e:+ self.logger.debug(f'[DownloadsWatchdog] Error in download start callback: {e}')++ # Emit DownloadStartedEvent so other components can react+ self.event_bus.dispatch(+ DownloadStartedEvent(+ guid=guid,+ url=url,+ suggested_filename=suggested_filename,+ auto_download=False, # CDP-triggered downloads are user-initiated+ )+ )+# Create and track the tasktask = create_task_with_error_handling(self._handle_cdp_download(event, target_id, session_id),@@ -206,15 +276,44 @@ class DownloadsWatchdog(BaseWatchdog):task.add_done_callback(lambda t: self._cdp_event_tasks.discard(t))def download_progress_handler(event: DownloadProgressEvent, session_id: SessionID | None) -> None:+ guid = event.get('guid', '')+ state = event.get('state', '')+ received_bytes = event.get('receivedBytes', 0)+ total_bytes = event.get('totalBytes', 0)++ # Call direct callbacks first (for click handlers tracking progress)+ progress_info = {+ 'guid': guid,+ 'received_bytes': received_bytes,+ 'total_bytes': total_bytes,+ 'state': state,+ }+ for callback in self._download_progress_callbacks:+ try:+ callback(progress_info)+ except Exception as e:+ self.logger.debug(f'[DownloadsWatchdog] Error in download progress callback: {e}')++ # Emit progress event for all states so listeners can track progress+ from browser_use.browser.events import DownloadProgressEvent as DownloadProgressEventInternal++ self.event_bus.dispatch(+ DownloadProgressEventInternal(+ guid=guid,+ received_bytes=received_bytes,+ total_bytes=total_bytes,+ state=state,+ )+ )+# Check if download is complete- if event.get('state') == 'completed':+ if state == 'completed':file_path = event.get('filePath')- guid = event.get('guid', '')if self.browser_session.is_local:if file_path:self.logger.debug(f'[DownloadsWatchdog] Download completed: {file_path}')# Track the download- self._track_download(file_path)+ self._track_download(file_path, guid=guid)# Mark as handled to prevent fallback duplicate dispatchtry:if guid in self._cdp_downloads_info:@@ -237,6 +336,7 @@ class DownloadsWatchdog(BaseWatchdog):file_ext = Path(file_name).suffix.lower().lstrip('.')self.event_bus.dispatch(FileDownloadedEvent(+ guid=guid,url=info.get('url', ''),path=str(effective_path),file_name=file_name,@@ -629,11 +729,12 @@ class DownloadsWatchdog(BaseWatchdog):self.logger.warning(f'[DownloadsWatchdog] Download failed: {type(e).__name__}: {e}')return None- def _track_download(self, file_path: str) -> None:+ def _track_download(self, file_path: str, guid: str | None = None) -> None:"""Track a completed download and dispatch the appropriate event.Args:file_path: The path to the downloaded file+ guid: Optional CDP download GUID for correlation with DownloadStartedEvent"""try:# Get file info@@ -642,11 +743,31 @@ class DownloadsWatchdog(BaseWatchdog):file_size = path.stat().st_sizeself.logger.debug(f'[DownloadsWatchdog] Tracked download: {path.name} ({file_size} bytes)')+ # Get file extension for file_type+ file_ext = path.suffix.lower().lstrip('.')++ # Call direct callbacks first (for click handlers waiting for downloads)+ complete_info = {+ 'guid': guid,+ 'url': str(path),+ 'path': str(path),+ 'file_name': path.name,+ 'file_size': file_size,+ 'file_type': file_ext if file_ext else None,+ 'auto_download': False,+ }+ for callback in self._download_complete_callbacks:+ try:+ callback(complete_info)+ except Exception as e:+ self.logger.debug(f'[DownloadsWatchdog] Error in download complete callback: {e}')+# Dispatch download eventfrom browser_use.browser.events import FileDownloadedEventself.event_bus.dispatch(FileDownloadedEvent(+ guid=guid,url=str(path), # Use the file path as URL for local filespath=str(path),file_name=path.name,@@ -762,6 +883,7 @@ class DownloadsWatchdog(BaseWatchdog):file_type = file_ext if file_ext else Noneself.event_bus.dispatch(FileDownloadedEvent(+ guid=guid,url=download_url,path=str(expected_path),file_name=unique_filename or expected_path.name,@@ -836,6 +958,7 @@ class DownloadsWatchdog(BaseWatchdog):returnself.event_bus.dispatch(FileDownloadedEvent(+ guid=guid,url=download_url,path=str(file_path),file_name=file_path.name,diff --git a/browser_use/tools/service.py b/browser_use/tools/service.pyindex 7f47da93e..d612c2bbb 100644--- a/browser_use/tools/service.py+++ b/browser_use/tools/service.py@@ -51,7 +51,6 @@ from browser_use.tools.views import (StructuredOutputAction,SwitchTabAction,UploadFileAction,- WaitForDownloadAction,)from browser_use.utils import create_task_with_error_handling, sanitize_surrogates, time_execution_sync@@ -1129,98 +1128,6 @@ You will be given a query and the markdown of a webpage that has been filtered tinclude_extracted_content_only_once=True,)- # Download Actions-- @self.registry.action(- 'Wait for a file download to complete. Use this after triggering a download (ex: clicking a download link) to confirm it finished and get the file path.',- param_model=WaitForDownloadAction,- )- async def wait_for_download(params: WaitForDownloadAction, browser_session: BrowserSession):- import re- from pathlib import Path-- from browser_use.browser.events import FileDownloadedEvent- from browser_use.browser.watchdog_base import BaseWatchdog-- def find_matching_download() -> dict | None:- """Find a download that matches the pattern (most recent first)."""- # Check downloads in reverse order (most recent first)- for file_path in reversed(browser_session.downloaded_files):- path = Path(file_path)- if path.exists():- file_name = path.name- # Check pattern if specified- if params.file_name_pattern:- if not re.search(params.file_name_pattern, file_name):- continue- return {- 'path': file_path,- 'file_name': file_name,- 'file_size': path.stat().st_size,- 'mime_type': None,- }- return None-- # Check if a matching download already exists- already_downloaded = find_matching_download()- if already_downloaded:- result_msg = f'Download completed: {already_downloaded["file_name"]} ({already_downloaded["file_size"]} bytes) saved to {already_downloaded["path"]}'- logger.info(f'📥 {result_msg}')- return ActionResult(- extracted_content=result_msg,- include_in_memory=True,- )-- # No matching download yet - wait for FileDownloadedEvent- download_complete = asyncio.Event()- downloaded_file_info: dict = {}-- async def on_FileDownloadedEvent(event: FileDownloadedEvent):- # If pattern specified, check if filename matches- if params.file_name_pattern:- if not re.search(params.file_name_pattern, event.file_name):- return # not the file-- downloaded_file_info['path'] = event.path- downloaded_file_info['file_name'] = event.file_name- downloaded_file_info['file_size'] = event.file_size- downloaded_file_info['mime_type'] = event.mime_type- download_complete.set()- return 'handled'-- # Attach handler- BaseWatchdog.attach_handler_to_session(browser_session, FileDownloadedEvent, on_FileDownloadedEvent)-- try:- await asyncio.wait_for(download_complete.wait(), timeout=params.timeout)- result_msg = f'Download completed: {downloaded_file_info["file_name"]} ({downloaded_file_info["file_size"]} bytes) saved to {downloaded_file_info["path"]}'- logger.info(f'📥 {result_msg}')- return ActionResult(- extracted_content=result_msg,- include_in_memory=True,- )- except TimeoutError:- # Check one more time in case download completed but event was missed- final_check = find_matching_download()- if final_check:- result_msg = f'Download completed: {final_check["file_name"]} ({final_check["file_size"]} bytes) saved to {final_check["path"]}'- logger.info(f'📥 {result_msg}')- return ActionResult(- extracted_content=result_msg,- include_in_memory=True,- )-- result_msg = f'Download timed out after {params.timeout} seconds. No file download was detected.'- logger.warning(f'⏱️ {result_msg}')- return ActionResult(- extracted_content=result_msg,- include_in_memory=True,- error='Download timeout',- )- finally:- # Detach handler to prevent memory leaks- BaseWatchdog.detach_handler_from_session(browser_session, FileDownloadedEvent, on_FileDownloadedEvent)-@self.registry.action("""Execute browser JavaScript. Best practice: wrap in IIFE (function(){...})() with try-catch for safety. Use ONLY browser APIs (document, window, DOM). NO Node.js APIs (fs, require, process). Example: (function(){try{const el=document.querySelector('#id');return el?el.value:'not found'}catch(e){return 'Error: '+e.message}})() Avoid comments. Use for hover, drag, zoom, custom selectors, extract/filter links, shadow DOM, or analysing page structure. Limit output size.""",)diff --git a/browser_use/tools/views.py b/browser_use/tools/views.pyindex 816312589..cf66b4122 100644--- a/browser_use/tools/views.py+++ b/browser_use/tools/views.py@@ -105,18 +105,3 @@ class GetDropdownOptionsAction(BaseModel):class SelectDropdownOptionAction(BaseModel):index: inttext: str = Field(description='exact text/value')---class WaitForDownloadAction(BaseModel):- """Wait for a file download to complete."""-- timeout: float = Field(- default=30.0,- description='Maximum time to wait for download in seconds',- ge=1.0,- le=300.0,- )- file_name_pattern: str | None = Field(- default=None,- description='Optional regex pattern to match the downloaded file name',- )