Skip to content

fix: invoke _download_complete_callbacks for remote browser downloads - #1

Merged
AdarshJ173 merged 1 commit into
mainfrom
fix/remote-download-complete-callback
Jul 20, 2026
Merged

AdarshJ173 merged 1 commit into
mainfrom
fix/remote-download-complete-callback

Conversation

@AdarshJ173

Copy link
Copy Markdown
Owner

Summary

Fixes a bug where downloads on remote browsers (is_local=False) would silently succeed but leave any waiting click action permanently blocked, causing a timeout.

Root Cause

In download_progress_handler inside attach_to_target, when state == 'completed' is received:

  • Local branch → calls self._track_download(file_path, guid=guid), which internally iterates _download_complete_callbacks and dispatches FileDownloadedEvent. ✅
  • Remote branch → dispatched FileDownloadedEvent correctly, but never called _download_complete_callbacks. ❌

This meant any caller that registered an on_complete callback via register_download_callbacks() (e.g. DefaultActionWatchdog._execute_click_with_download_detection) would wait forever for download_completed.set(), eventually timing out — even though the file downloaded successfully.

Fix

In the remote state == 'completed' branch, build the same complete_info dict that _track_download produces and iterate _download_complete_callbacks before dispatching FileDownloadedEvent, making the remote path fully symmetric with the local path.

# NEW: fire complete callbacks so click-action waiters are unblocked
complete_info = {
    'guid': guid,
    'url': info.get('url', ''),
    'path': str(effective_path),
    'file_name': file_name,
    'file_size': 0,
    '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 cb_err:
        self.logger.debug(f'[DownloadsWatchdog] Error in download complete callback (remote): {cb_err}')

Testing

  • Local browser download — unchanged behaviour (existing tests cover this)
  • Remote browser download — on_complete callback now fires; click actions no longer time out

Fixes browser-use#5132

When is_local=False and state=='completed', the remote branch in
download_progress_handler dispatched FileDownloadedEvent correctly but
never called _download_complete_callbacks.  This meant any click action
registered via DefaultActionWatchdog._execute_click_with_download_detection
would wait forever for download_completed.set(), causing a timeout even
though the download actually succeeded.

Fix: after constructing the completion metadata in the remote branch,
iterate over _download_complete_callbacks exactly as _track_download does
for local browsers.

Fixes browser-use#5132
@AdarshJ173
AdarshJ173 merged commit b4d8ac5 into main Jul 20, 2026

@AdarshJ173 AdarshJ173 left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deep Codebase Review — Findings beyond PR #1

Going all in. I've audited the full watchdog layer, download pipeline, crash detection, and event bus usage. Below are all findings I'm attaching as review comments on individual files.


🔴 Critical

  1. crash_watchdog.py — wrong target_id in on_TabCreatedEvent (see inline comment)
    New tabs are never added to crash monitoring because the handler passes agent_focus_target_id instead of event.target_id.

  2. downloads_watchdog.py — _cdp_downloads_info leaks on interrupted state (see inline)
    The progress handler only cleans _cdp_downloads_info on completed. If a download is interrupted (network cut, user cancel), the guid entry is never removed — unbounded dict growth in long-running sessions.


🟡 Medium

  1. downloads_watchdog.py — _initial_downloads_snapshot grows forever (see inline)
    Files are added to the snapshot but never pruned. In a long-running agent with many downloads the set grows without bound.

  2. crash_watchdog.py — _check_network_timeouts mutates dict while iterating (see inline)
    del self._active_requests[request_id] is called from a loop over _active_requests.items(), separated by a list copy — this is safe as written, but only because of the intermediate timed_out_requests list. A comment should make this explicit to prevent future regressions.

  3. downloads_watchdog.py — download_file_from_url 15-second JS fetch timeout may be too short for large files (see inline)
    The CDP Runtime.evaluate call fetches the entire binary into a JS array before returning. For files >50 MB this will reliably time out. Should be configurable via BrowserProfile.


🟢 Nits / Improvements

  1. crash_watchdog.py — _is_new_tab_page includes about:blank in the redirect list but then navigates to about:blank — infinite loop risk if about:blank is already the URL (see inline).

  2. downloads_watchdog.py — double if not self._download_cdp_session_setup: guard — redundant nested check (see inline).

  3. downloads_watchdog.py — _handle_download (Playwright path) calls download.failure() unconditionally with a TODO comment admitting it always fails — dead code that should be removed.

@AdarshJ173

Copy link
Copy Markdown
Owner Author

🔎 Full Autonomous Codebase Review

Deep-reviewed the entire watchdog layer, download pipeline, event bus, and crash detection. Here are all findings beyond the fix in this PR:


🔴 Critical Bugs

1. crash_watchdog.py — Wrong target_id in on_TabCreatedEvent

File: browser_use/browser/watchdogs/crash_watchdog.py

# CURRENT (broken)
async def on_TabCreatedEvent(self, event: TabCreatedEvent) -> None:
    assert self.browser_session.agent_focus_target_id is not None
    await self.attach_to_target(self.browser_session.agent_focus_target_id)  # ← WRONG

When a new tab is created, the handler monitors the already-focused tab instead of the new tab. Since agent_focus_target_id is likely already in _targets_with_listeners, this is a silent no-op — new tabs are never added to crash monitoring. Background popups and new windows can crash without any BrowserErrorEvent being dispatched.

Fix:

async def on_TabCreatedEvent(self, event: TabCreatedEvent) -> None:
    if event.target_id:
        await self.attach_to_target(event.target_id)

Compare with DownloadsWatchdog.on_TabCreatedEvent which correctly uses event.target_id.


2. downloads_watchdog.py — _cdp_downloads_info leaks on interrupted/canceled state

File: browser_use/browser/watchdogs/downloads_watchdog.py — download_progress_handler

The state == 'completed' branch (both local and remote paths) correctly removes the guid from _cdp_downloads_info. But state in ('interrupted', 'canceled') is never handled — those guid entries stay in the dict forever. In long-running sessions with flaky networks, this grows unbounded.

Fix: Add cleanup for terminal non-completed states:

elif state in ('interrupted', 'canceled'):
    self._cdp_downloads_info.pop(guid, None)
    self.logger.debug(f'[DownloadsWatchdog] Download {state}, cleaned up tracking for guid={guid}')

🟡 Medium Issues

3. _initial_downloads_snapshot grows forever

File: browser_use/browser/watchdogs/downloads_watchdog.py

Files are only ever added to _initial_downloads_snapshot, never removed. In long-running agents that perform hundreds of downloads, the set grows without bound. Consider capping the snapshot size or periodically pruning filenames that no longer exist on disk.


4. download_file_from_url hardcoded 15-second timeout will fail for large files

File: browser_use/browser/watchdogs/downloads_watchdog.py — download_file_from_url

The CDP Runtime.evaluate call fetches the entire binary blob into a JS Uint8Array before returning. For files > ~30–50 MB this reliably times out at the 15-second hardcoded limit. This should be configurable via BrowserProfile (e.g. download_timeout_seconds: float = 60.0).


5. crash_watchdog.py — _is_new_tab_page includes about:blank but redirects TO about:blank

File: browser_use/browser/watchdogs/crash_watchdog.py — _check_browser_health

if self._is_new_tab_page(target.url) and target.url != 'about:blank':
    # redirect to about:blank

The guard and target.url != 'about:blank' is correct, but _is_new_tab_page includes 'about:blank' in its return-true set, making the method semantically misleading. The static method should only match Chrome's new tab variants (chrome://new-tab-page/, chrome://newtab/), not about:blank itself.


🟢 Code Quality / Nits

6. Double-redundant if not self._download_cdp_session_setup guard

File: downloads_watchdog.py — attach_to_target

if self._download_cdp_session_setup:  # outer guard returns early
    return

if not self._download_cdp_session_setup:  # inner guard is always True here
    # ... setup ...

The inner if not self._download_cdp_session_setup: check is always True at that point (the outer guard already returned). Remove the inner check.


7. Dead code in _handle_download (Playwright path)

File: downloads_watchdog.py — _handle_download

failure = await download.failure()
self.logger.warning(f'Download state - canceled: {failure}, url: {download.url}')
# TODO: it always fails for some reason, figure out why connect_over_cdp makes accept_downloads not work

The TODO has been unresolved and the method is clearly not exercised in the CDP path. This Playwright path should either be removed or properly gated behind a is_playwright_browser check to avoid confusion.


All 7 items are ready to be addressed in follow-up PRs. Happy to send branches for any of them.

AdarshJ173 added a commit that referenced this pull request Jul 20, 2026
Previously on_TabCreatedEvent passed agent_focus_target_id to
attach_to_target(), which is typically already in _targets_with_listeners
so the call was a silent no-op. New tabs (popups, ctrl+click, etc.) were
never registered for crash monitoring, meaning TargetCrashedEvent on
non-focus tabs would never fire BrowserErrorEvent.

Fix: use event.target_id (the actually-new tab), mirroring the correct
behaviour in DownloadsWatchdog.on_TabCreatedEvent.

Also fix _is_new_tab_page() to exclude 'about:blank' from its match set;
the health-check redirect loop already guards against it with an explicit
`and target.url != 'about:blank'` but the helper method including it is
misleading and error-prone for future callers.

Fixes browser-use#2 from review comment on PR #1.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Remote browser downloads can complete without triggering click download completion callback, causing click action timeout

1 participant