Skip to content

Bug: CDP connection instability causing indefinite hangs with remote browsers #4579

Open

Description

@MrLeit

Browser Use Version

0.12.5

Bug Description, Steps to Reproduce, Screenshots

Individual CDP calls within handlers lack timeouts, causing indefinite hangs with remote browsers

Summary

When using browser-use with remote browsers via CDP (e.g., Browserless), individual CDP calls like Runtime.evaluate inside DOMWatchdog.on_BrowserStateRequestEvent can hang indefinitely if the CDP WebSocket connection becomes stale. There is no per-call timeout — the only safety net is the event-level timeout (default 30s), which wastes the entire timeout window before failing.

Environment

  • browser-use 0.12.5
  • Remote browser via CDP (Browserless)
  • keep_alive=True

Observed behaviour

When running sequential agents on the same browser session with keep_alive=True, there are naturally idle periods between agent runs where no CDP traffic flows. After such an idle period, the next BrowserStateRequestEvent can hang:

  1. DownloadsWatchdog completes but its CDP call (get_current_page_url) takes 3.0s instead of the usual 0.00-0.01s — an early signal the connection is degraded
  2. DOMWatchdog enters _get_pending_network_requests
  3. get_or_create_cdp_session(focus=True) succeeds but also takes 3.0s
  4. The subsequent Runtime.evaluate call never returns — no error, no timeout, just an indefinite await
  5. The handler blocks until the event-level timeout fires

The connection degradation is not deterministic — sometimes connections survive long idle periods, sometimes they become stale after relatively short gaps. No CDP errors or WebSocket close frames are logged when the connection degrades. The WebSocket appears open but is silently half-dead (sends succeed, responses never arrive).

This was identified by adding diagnostic instrumentation around the key methods in DOMWatchdog — wrapping _get_pending_network_requests, _capture_clean_screenshot, and _build_dom_tree_without_highlights with timing logs, and adding a heartbeat task to on_BrowserStateRequestEvent. This confirmed the handler was alive but stuck awaiting the CDP call indefinitely.

With local browsers this is unlikely to occur because the browser process is co-located. With remote browsers behind a WebSocket proxy, idle connections can degrade without either side detecting it.

Relation to #4374

This creates a catch-22 for remote browser users with keep_alive=True:

Both paths lead to broken sessions. The underlying issue is that browser-use assumes the CDP connection is always healthy if the WebSocket is open.

Root cause

CDP calls in handler code (e.g., _get_pending_network_requests, _build_dom_tree_without_highlights, _capture_clean_screenshot) await CDP protocol methods with no individual timeout. If the remote browser stops responding — due to WebSocket proxy recycling, idle timeout, or network conditions — these awaits block forever.

The relevant code path in dom_watchdog.py:

async def _get_pending_network_requests(self):
    cdp_session = await self.browser_session.get_or_create_cdp_session(focus=True)
    # This Runtime.evaluate has no timeout — hangs forever if CDP is stale
    result = await cdp_session.execute(
        Runtime.evaluate(expression=..., await_promise=True, ...)
    )

Reproduction

This is timing-dependent and requires a remote browser. The conditions are:

  1. Connect to a remote browser via CDP with keep_alive=True
  2. Apply the workaround from Bug: Agent.close() with keep_alive=True drops CDP WebSocket connections, triggering unnecessary reconnection cycle #4374 to prevent Agent.close() from tearing down the event bus (otherwise the CDP connection is killed on close and the session is lost before this issue can manifest)
  3. Run an agent to completion (agent closes, browser session and CDP connection persist)
  4. Wait with no CDP traffic (duration varies — sometimes 30s is enough, sometimes minutes are fine)
  5. Start a new agent on the same browser session
  6. The first BrowserStateRequestEvent has a chance of hanging indefinitely

The probability is non-deterministic and depends on the remote browser provider's WebSocket proxy behaviour and network conditions.

Failing Python Code

It is difficult to provide a minimal replication as it involves CDP and multiple browser instances.

It also requires addressing https://github.com/browser-use/browser-use/issues/4374 locally so that keep_alive actually works.

LLM Model

No response

Operating System & Browser Versions

No response

Full DEBUG Log Output

Activity

  1. added
    bug
    on Mar 31, 2026
  2. laithrw commented on Apr 15, 2026

    @laithrw
    Contributor

    @MrLeit, thank you for reporting this. Could you please share full debug logs that include the websocket ping/pong behavior? Also, is this for Browserless only or other remote CDP providers, too?

    For example, you could reproduce this with DEBUG logging enabled for websockets.client, cdp_use.client, and browser_use, and write logs to a file with timestamps.

  3. MrLeit commented on Apr 16, 2026

    @MrLeit
    ContributorAuthor

    @laithrw - I'll try to find some time next week to reproduce again and capture the logs. I unfortunately did not keep my custom instrumentation or detailed logs from the runs. However I can try with standard DEBUG logging for websockets.client, cdp_use.client, and browser_use and provide.

    I have only experienced the issue with browerless via CDP using keepAlive=true. (ghcr.io/browserless/chromium). If I create a new browser for every request via CDP for browserless I have never hit this issue.

    The keepAlive is the ideal solution as we waste a lot time time for each task starting the browser up and logging in to the target system (often 50% of the total runtime).

  4. MrLeit commented on May 11, 2026

    @MrLeit
    ContributorAuthor

    @laithrw - I just spent a few hours on this and although I can reproduce it I didn't manage to capture the dang websockets.client logs, only cdp_use.client which gave just a generic looking failure.

    Here is a cut down and anonymise log file.

    debug2.log

    There is an error getting a screenshot and then a warning about a session error being detected. It seems at this point this never recovered and then the timeouts start happening.

    2026-05-11 12:08:28,989 [DEBUG] cdp_use.client: 🌎 ← #330: Page.captureScreenshot()
    2026-05-11 12:08:29,279 [DEBUG] cdp_use.client: 🌎 → #330: ❌ {code:-32603,message:Int...49ED60BC4875D3054F5CC}
    2026-05-11 12:08:29,279 [DEBUG] cdp_use.client: CDP Error for request 330: {'code': -32603, 'message': 'Internal error'}
    2026-05-11 12:08:29,279 [ERROR] browser_use.BrowserSession🅑 cf69 🅣 9F: [ScreenshotWatchdog] Screenshot failed: {'code': -32603, 'message': 'Internal error'}
    2026-05-11 12:08:29,279 [ERROR] browser_use.BrowserSession🅑 cf69 🅣 9F: 🚌 [ScreenshotWatchdog.on_ScreenshotEvent(#02ea)]         ❌ Failed (6.31s): RuntimeError: {'code': -32603, 'message': 'Internal error'}
    2026-05-11 12:08:29,279 [DEBUG] browser_use.BrowserSession🅑 cf69 🅣 9F: 🚌 [ScreenshotWatchdog.on_ScreenshotEvent(#02ea)]         ⚠️ Session error detected, waiting for CDP events to sync (target: 98CD7B614CA9DB2FE96122C1046D5D9F)
    2026-05-11 12:08:29,280 [DEBUG] cdp_use.client: 🌎 ← #331: Runtime.runIfWaitingForD...()
    2026-05-11 12:08:31,042 [DEBUG] cdp_use.client: ✔ PING (288.4ms)
    

    By the way, I think this even even much worse as it seems that while the system is trying to recreate the CDP session (with no timeout) it is holding a global lock on the BUBUS event bus. This in fact appears to block ALL browsers, not just the one that is having issues.

    My analysis.


    bubus global lock blocks all browser sessions

    The lock

    bubus/service.py holds a process-wide singleton lock (_global_eventbus_lock) acquired in EventBus.step() for the full duration of every event handler. All BrowserSession instances share it — they have separate EventBus objects but contend on the same lock.

    Impact

    DOMWatchdog.on_BrowserStateRequestEvent holds the lock while doing 6–7 CDP round-trips (DOM snapshot, accessibility tree, screenshot, etc.). Every other browser session in the pool is blocked from processing any events for that entire duration.

    The lock is also not released early on CDP errors. If a child operation fails (e.g. Page.captureScreenshot returning -32603 Internal error), the handler enters a recovery wait rather than exiting, burning the full 30s timeout with the lock still held.

    With N concurrent sessions, worst case is N × 30s of serialized blocking.

    Observed

    • 12:08:17 — DOMWatchdog.on_BrowserStateRequestEvent starts on session cf69, lock acquired
    • 12:08:29 — captureScreenshot fails with CDP -32603, handler enters sync wait
    • 12:08:32 — bubus 15s warning fires; lock still held
    • 12:08:47 — handler hits 30s timeout, lock released; other sessions unblocked
  5. aaronlab commented on May 11, 2026

    @aaronlab

    The latest log points to two separable failure boundaries, which may make this easier to fix and review:

    1. Per-CDP-call timeout / health marking. BrowserStateRequestEvent has an event-level timeout, but individual remote CDP calls such as Page.captureScreenshot, Runtime.evaluate, DOM snapshot, or accessibility-tree reads should probably have shorter method-level timeouts. If one method times out or returns a transport-level/session error, the handler can mark that browser session unhealthy and abort the state build quickly instead of spending the whole event timeout window.

    2. Lock scope during remote browser I/O. If EventBus.step() holds a process-wide lock while a handler performs several CDP round trips and then enters recovery wait, one degraded remote browser can serialize unrelated browser sessions. Even if the global lock is intentional for event ordering, the recovery path should not hold it for the full timeout after a CDP failure.

    For the next repro log, the most useful extra fields would be:

    • event id and browser/session/target id
    • event-bus lock wait, acquire, and release timestamps
    • CDP request id, method name, start/end timestamp, duration, and result/error/timeout
    • websocket ping/pong timestamps near the stuck request
    • whether a request id was sent but never received a matching response
    • whether recovery waits are entered while the event-bus lock is still held

    That would distinguish "remote CDP method failed fast" from "request was sent and response never arrived" from "Browser Use recovery held the global lock after the failure." Those are different fixes, and the log you attached suggests the lock/recovery path may be as important as the screenshot error itself.

    From a tracing/debugging perspective, I would treat this as a method-timing plus lock-timing problem, not only a screenshot problem. The screenshot failure is likely the first visible symptom; the broader user-visible failure is the stale CDP session blocking later state collection and possibly other sessions.

  6. Parth-001-git commented on May 20, 2026

    @Parth-001-git

    Added a fix for the remote CDP hang path around DOMWatchdog timeouts and connection recovery handling.

    All checks are passing now. Happy to adjust the timeout/recovery behavior further if there’s a preferred direction for long-lived pooled browser sessions.

  7. added a commit that references this issue on May 21, 2026
    4bc538d
  8. MrLeit commented on Jun 7, 2026

    @MrLeit
    ContributorAuthor

    We moved away from keep alive on browsers and added static login when creating them and before handing back to the agent. This is a small time overhead but is relatively quick and completely deterministic.

    The main reason was that we also record video per session and it seems that it is always linked to browser lifecycle today.

  9. pirate commented on Jun 22, 2026

    @pirate
    Contributor

    I have some context on this excellent report @MrLeit, even though I'm no longer at browser-use, I feel I should answer because I wrote this part of the code haha.

    At the time I wanted a deliberate global lock between browsers to keep the agent's view of the world serialized, even if it meant blocking up to event timeouts sometimes. The bottleneck would always be an agent loop and multi-second LLM waits, and so I preferred correctness over performance at the time. I don't work at the company anymore so I don't know what the state is now.

    I added the ability to easily set event-level concurrency options, but it's in my fork of bubus: https://abxbus.archivebox.io/concurrency/events-parallel and would need to be backported to bubus to fix it in BU.

  10. IgorGanapolsky commented on Jul 22, 2026

    @IgorGanapolsky

    Reliability note

    Production automation failures usually reduce to a contract issue before a model/prompt issue:

    1. Success criteria — durable artifact id (message/booking/row), not only node green
    2. Side-effect before complete — never blind-retry without an idempotency key on the business object
    3. Tool vs path split — external action can succeed while the node/agent path still errors (silent-green / false-red)

    If you have one failing execution + expected vs actual, reply with stack/version and I will send a free root-cause checklist.

  11. jinngimk-lang commented on Aug 17, 2026

    @jinngimk-lang

    A WebSocket that is technically open while Runtime.evaluate can wait forever is the exact reason connection state cannot stand in for route health.

    AgentCI is recruiting half-dead transport breakers like this. A portable fixture could bind connection generation + bounded safe probe + per-call deadline + reconnect/failure evidence, with an intentionally stale endpoint as the negative control. If the observer/control route stops answering, readiness must downgrade immediately instead of spending the whole event timeout pretending it is healthy.

    If you or an external agent contribute the smallest fake/remote transport fixture, we’ll preserve this issue as provenance and give permanent public credit in AgentCI’s Breaker Hall of Fame + priority conversion help.

    AgentCI: https://github.com/jinngimk-lang/agentci · recognition: https://github.com/jinngimk-lang/agentci/blob/main/COMMUNITY.md

    Affiliation disclosed; no Browser Use certification claim.

  12. neilmorse commented on Oct 15, 2026

    @neilmorse

    Hi @MrLeit — I am Kaelenx, an independent open-source researcher prototyping a local-first Agent Contract testing and replay tool.

    Using this issue as a reference, I built a local fake-CDP fixture where the WebSocket remains open but one Runtime.evaluate call never returns. The fixture checks four boundaries: per-call deadline, degraded-session marking, bounded recovery, and whether a healthy browser session remains unaffected.

    Does that capture the important failure boundary from your Browserless/keep_alive experience? For a useful redacted replay bundle, which fields would matter most: CDP method and request id, browser/session id, timeout duration, WebSocket health signals, event-bus lock timing, or recovery outcome?

    I will not connect to any remote browser or ask for private logs. A reply here with public guidance is enough; I am trying to learn what a maintainer would actually find useful in an issue report or CI fixture.

    — Kaelenx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions