Skip to content

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

fix(downloads): prevent duplicate local downloads via single-dispatch; disable local JS fetch

Jay Ozera874d2c046dd
diff --git a/browser_use/browser/watchdogs/downloads_watchdog.py b/browser_use/browser/watchdogs/downloads_watchdog.py
index 4b27af9b0..05cc4b5d8 100644
--- a/browser_use/browser/watchdogs/downloads_watchdog.py
+++ b/browser_use/browser/watchdogs/downloads_watchdog.py
@@ -53,6 +53,7 @@ class DownloadsWatchdog(BaseWatchdog):
_download_cdp_session: Any = PrivateAttr(default=None) # Store CDP session reference
_cdp_event_tasks: set[asyncio.Task] = PrivateAttr(default_factory=set) # Track CDP event handler tasks
_cdp_downloads_info: dict[str, dict[str, Any]] = PrivateAttr(default_factory=dict) # Map guid -> info
+ _use_js_fetch_for_local: bool = PrivateAttr(default=False) # Guard JS fetch path for local regular downloads
async def on_BrowserLaunchEvent(self, event: BrowserLaunchEvent) -> None:
self.logger.debug(f'[DownloadsWatchdog] Received BrowserLaunchEvent, EventBus ID: {id(self.event_bus)}')
@@ -173,6 +174,7 @@ class DownloadsWatchdog(BaseWatchdog):
self._cdp_downloads_info[guid] = {
'url': event.get('url', ''),
'suggested_filename': suggested_filename,
+ 'handled': False,
}
except Exception:
pass
@@ -182,21 +184,27 @@ class DownloadsWatchdog(BaseWatchdog):
# 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)
- 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'
- )
+ 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, {})
@@ -295,8 +303,8 @@ class DownloadsWatchdog(BaseWatchdog):
files_before = list(downloads_dir.iterdir())
self.logger.debug(f'[DownloadsWatchdog] Files before download: {[f.name for f in files_before]}')
- # Try manual JavaScript fetch as a fallback for local browsers
- if self.browser_session.is_local:
+ # Try manual JavaScript fetch as a fallback for local browsers (disabled for regular local downloads)
+ if self.browser_session.is_local and self._use_js_fetch_for_local:
self.logger.debug(f'[DownloadsWatchdog] Attempting JS fetch fallback for {download_url}')
unique_filename = None
@@ -373,6 +381,12 @@ class DownloadsWatchdog(BaseWatchdog):
auto_download=False,
)
)
+ # Mark as handled to prevent duplicate dispatch from progress/polling paths
+ try:
+ if guid in self._cdp_downloads_info:
+ self._cdp_downloads_info[guid]['handled'] = True
+ except Exception:
+ pass
self.logger.debug(
f'[DownloadsWatchdog] ✅ File download completed via CDP: {suggested_filename} ({file_size} bytes) saved to {expected_path}'
)
@@ -420,14 +434,15 @@ class DownloadsWatchdog(BaseWatchdog):
f'[DownloadsWatchdog] ✅ Found downloaded file: {file_path} ({file_size} bytes)'
)
- # Track the download
- self.browser_session._downloaded_files.append(str(file_path))
-
# Determine file type from extension
file_ext = file_path.suffix.lower().lstrip('.')
file_type = file_ext if file_ext else None
# Dispatch download event
+ # Skip if already handled by progress/JS fetch
+ info = self._cdp_downloads_info.get(guid, {})
+ if info.get('handled'):
+ return
self.event_bus.dispatch(
FileDownloadedEvent(
url=download_url,
@@ -437,6 +452,12 @@ class DownloadsWatchdog(BaseWatchdog):
file_type=file_type,
)
)
+ # Mark as handled after dispatch
+ try:
+ if guid in self._cdp_downloads_info:
+ self._cdp_downloads_info[guid]['handled'] = True
+ except Exception:
+ pass
return
except Exception as e:
self.logger.debug(f'[DownloadsWatchdog] Error checking file {file_path}: {e}')