Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

add tool to wait for file download, fixing issue where it'd call complete before download

Laith Weinberger40e1a80a9812
diff --git a/browser_use/browser/watchdog_base.py b/browser_use/browser/watchdog_base.py
index 99507c253..e8097dffb 100644
--- a/browser_use/browser/watchdog_base.py
+++ b/browser_use/browser/watchdog_base.py
@@ -177,6 +177,26 @@ class BaseWatchdog(BaseModel):
event_bus.on(event_class, unique_handler)
+ @staticmethod
+ def detach_handler_from_session(
+ browser_session: 'BrowserSession', event_class: type[BaseEvent[Any]], handler
+ ) -> None:
+ """Detach a single event handler from a browser session."""
+ event_bus = browser_session.event_bus
+
+ # Get the watchdog instance if this is a bound method
+ watchdog_instance = getattr(handler, '__self__', None)
+ watchdog_class_name = watchdog_instance.__class__.__name__ if watchdog_instance else 'Unknown'
+
+ # Find and remove the handler by its unique name pattern
+ unique_handler_name = f'{watchdog_class_name}.{handler.__name__}'
+
+ existing_handlers = event_bus.handlers.get(event_class.__name__, [])
+ for existing_handler in existing_handlers[:]: # copy list to allow modification during iteration
+ if getattr(existing_handler, '__name__', '') == unique_handler_name:
+ existing_handlers.remove(existing_handler)
+ break
+
def attach_to_session(self) -> None:
"""Attach watchdog to its browser session and start monitoring.
diff --git a/browser_use/tools/service.py b/browser_use/tools/service.py
index d612c2bbb..fcf6c9668 100644
--- a/browser_use/tools/service.py
+++ b/browser_use/tools/service.py
@@ -51,6 +51,7 @@ 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
@@ -1128,6 +1129,57 @@ You will be given a query and the markdown of a webpage that has been filtered t
include_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 browser_use.browser.events import FileDownloadedEvent
+ from browser_use.browser.watchdog_base import BaseWatchdog
+
+ 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 asyncio.TimeoutError:
+ 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.py
index cf66b4122..816312589 100644
--- a/browser_use/tools/views.py
+++ b/browser_use/tools/views.py
@@ -105,3 +105,18 @@ class GetDropdownOptionsAction(BaseModel):
class SelectDropdownOptionAction(BaseModel):
index: int
text: 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',
+ )