Skip to content

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

fix(downloads): move CDP handlers outside try; tabs indentation; align except

Jay Ozer5891ed305456
diff --git a/browser_use/browser/watchdogs/downloads_watchdog.py b/browser_use/browser/watchdogs/downloads_watchdog.py
index c3a52a910..68fa4437d 100644
--- a/browser_use/browser/watchdogs/downloads_watchdog.py
+++ b/browser_use/browser/watchdogs/downloads_watchdog.py
@@ -132,6 +132,71 @@ class DownloadsWatchdog(BaseWatchdog):
async def attach_to_target(self, target_id: TargetID) -> None:
"""Set up download monitoring for a specific target."""
+ # Define CDP event handlers outside of try to avoid indentation/scope issues
+ async def download_will_begin_handler(event: DownloadWillBeginEvent, session_id: SessionID | None):
+ self.logger.debug(f'[DownloadsWatchdog] Download will begin: {event}')
+ # Cache info for later completion event handling (esp. remote browsers)
+ guid = event.get('guid', '')
+ try:
+ suggested_filename = event.get('suggestedFilename')
+ assert suggested_filename, 'CDP DownloadWillBegin missing suggestedFilename'
+ self._cdp_downloads_info[guid] = {
+ 'url': event.get('url', ''),
+ 'suggested_filename': suggested_filename,
+ 'handled': False,
+ }
+ except Exception:
+ pass
+ # Create and track the task
+ task = asyncio.create_task(self._handle_cdp_download(event, target_id, session_id))
+ self._cdp_event_tasks.add(task)
+ # Remove from set when done
+ task.add_done_callback(lambda t: self._cdp_event_tasks.discard(t))
+
+ async def download_progress_handler(event: DownloadProgressEvent, session_id: SessionID | None):
+ # Check if download is complete
+ if event.get('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)
+ # Mark as handled to prevent fallback duplicate dispatch
+ try:
+ if guid in self._cdp_downloads_info:
+ self._cdp_downloads_info[guid]['handled'] = True
+ except Exception:
+ pass
+ else:
+ # No local file path provided, local polling in _handle_cdp_download will handle it
+ self.logger.debug(
+ '[DownloadsWatchdog] No filePath in progress event (local); polling will handle detection'
+ )
+ else:
+ # Remote browser: do not touch local filesystem. Fallback to downloadPath+suggestedFilename
+ info = self._cdp_downloads_info.get(guid, {})
+ try:
+ suggested_filename = info['suggested_filename']
+ downloads_path = str(self.browser_session.browser_profile.downloads_path or '')
+ effective_path = file_path or str(Path(downloads_path) / suggested_filename)
+ file_name = Path(effective_path).name
+ file_ext = Path(file_name).suffix.lower().lstrip('.')
+ self.event_bus.dispatch(
+ FileDownloadedEvent(
+ url=info.get('url', ''),
+ path=str(effective_path),
+ file_name=file_name,
+ file_size=0,
+ file_type=file_ext if file_ext else None,
+ )
+ )
+ self.logger.debug(f'[DownloadsWatchdog] ✅ (remote) Download completed: {effective_path}')
+ finally:
+ if guid in self._cdp_downloads_info:
+ del self._cdp_downloads_info[guid]
+
try:
downloads_path_raw = self.browser_session.browser_profile.downloads_path
if not downloads_path_raw:
@@ -163,70 +228,6 @@ class DownloadsWatchdog(BaseWatchdog):
}
)
- # Register download event handlers
- async def download_will_begin_handler(event: DownloadWillBeginEvent, session_id: SessionID | None):
- self.logger.debug(f'[DownloadsWatchdog] Download will begin: {event}')
- # Cache info for later completion event handling (esp. remote browsers)
- guid = event.get('guid', '')
- try:
- suggested_filename = event.get('suggestedFilename')
- assert suggested_filename, 'CDP DownloadWillBegin missing suggestedFilename'
- self._cdp_downloads_info[guid] = {
- 'url': event.get('url', ''),
- 'suggested_filename': suggested_filename,
- 'handled': False,
- }
- except Exception:
- pass
- # Create and track the task
- task = asyncio.create_task(self._handle_cdp_download(event, target_id, session_id))
- self._cdp_event_tasks.add(task)
- # Remove from set when done
- task.add_done_callback(lambda t: self._cdp_event_tasks.discard(t))
-
- async def download_progress_handler(event: DownloadProgressEvent, session_id: SessionID | None):
- # Check if download is complete
- if event.get('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)
- # Mark as handled to prevent fallback duplicate dispatch
- try:
- if guid in self._cdp_downloads_info:
- self._cdp_downloads_info[guid]['handled'] = True
- except Exception:
- pass
- else:
- # No local file path provided, local polling in _handle_cdp_download will handle it
- self.logger.debug(
- '[DownloadsWatchdog] No filePath in progress event (local); polling will handle detection'
- )
- else:
- # Remote browser: do not touch local filesystem. Fallback to downloadPath+suggestedFilename
- info = self._cdp_downloads_info.get(guid, {})
- try:
- suggested_filename = info['suggested_filename']
- downloads_path = str(self.browser_session.browser_profile.downloads_path or '')
- effective_path = file_path or str(Path(downloads_path) / suggested_filename)
- file_name = Path(effective_path).name
- file_ext = Path(file_name).suffix.lower().lstrip('.')
- self.event_bus.dispatch(
- FileDownloadedEvent(
- url=info.get('url', ''),
- path=str(effective_path),
- file_name=file_name,
- file_size=0,
- file_type=file_ext if file_ext else None,
- )
- )
- self.logger.debug(f'[DownloadsWatchdog] ✅ (remote) Download completed: {effective_path}')
- finally:
- if guid in self._cdp_downloads_info:
- del self._cdp_downloads_info[guid]
# Register the handlers with CDP
cdp_client.register.Browser.downloadWillBegin(download_will_begin_handler) # type: ignore[arg-type]