Skip to content

Bug: Agent.close() with keep_alive=True drops CDP WebSocket connections, triggering unnecessary reconnection cycle #4374

Open

Description

@MrLeit

Browser Use Version

0.12.2

Bug Description, Steps to Reproduce, Screenshots

Title

Agent.close() with keep_alive=True drops CDP WebSocket connections, triggering unnecessary reconnection cycle

Body

Context

We maintain a pool of pre-authenticated browsers using Browser(keep_alive=True). At startup, a lightweight agent logs each browser into our target application, then the browser sits idle in the pool until a real task arrives. This avoids repeating login for every task and lets us reuse authenticated sessions across sequential agent runs.

Bug Description

When Agent.close() completes with keep_alive=True, all CDP WebSocket connections are dropped. In 0.12.2, the built-in reconnection logic recovers (after ~1.7s), but this is unnecessary overhead — the connections shouldn't be dropped in the first place when the intent is to keep the browser alive.

Observed Behavior (0.12.2)

Immediately after warmup agent completes on a keep_alive=True browser:

WARNING  [BrowserSession] CDP WebSocket message handler exited unexpectedly (connection closed)
WARNING  [BrowserSession] CDP WebSocket message handler exited unexpectedly (connection closed)
WARNING  [BrowserSession] CDP WebSocket message handler exited unexpectedly (connection closed)
WARNING  [BrowserSession] WebSocket reconnection attempt 1/3...
INFO     [BrowserSession] [SessionManager] Cleared all owned data (targets, sessions, mappings)
WARNING  [BrowserSession] WebSocket reconnection attempt 1/3...
INFO     [BrowserSession] [SessionManager] Cleared all owned data (targets, sessions, mappings)
...
INFO     [BrowserSession] WebSocket reconnected after 1.7s (attempt 1)
INFO     [BrowserSession] WebSocket reconnected after 1.7s (attempt 1)

This happens for every Agent.close() on a keep_alive=True browser — multiple WebSocket handlers all disconnect and reconnect, clearing session manager data each time.

Expected Behavior

With keep_alive=True, Agent.close() should preserve the CDP WebSocket connections and session state. The browser should remain fully connected and ready for the next Agent.run() without any disconnection/reconnection cycle.

Impact

  • ~1.7s recovery delay after every agent run before the browser is usable again
  • Session manager data cleared on each reconnection ("Cleared all owned data (targets, sessions, mappings)")
  • In pre-0.12.x (which lacked WebSocket reconnection), this same issue caused permanent CDP connection collapse — the browser became unusable after the first agent completed
  • Multiple reconnection warnings per browser pollute logs in pooled setups

Reproduction

from browser_use import Agent, Browser

browser = Browser(keep_alive=True)

# First agent — e.g. a login warmup
agent1 = Agent(task="Navigate to example.com", browser=browser, llm=llm)
await agent1.run()
# Immediately after: CDP WebSocket handlers exit, reconnection cycle begins

# Browser recovers after ~1.7s, but all session data was cleared

Root Cause (from investigation)

In agent/service.py, Agent.close() with keep_alive=True tears down the event bus, which appears to cascade into closing CDP WebSocket connections. The 0.12.2 reconnection logic masks the issue but doesn't prevent the unnecessary disconnect.

Environment

  • browser-use: 0.12.2
  • Python: 3.13
  • OS: Cloud Foundry (Linux) with Browserless container via CDP
  • Setup: Pool of 3-5 Browser(keep_alive=True) instances, each warmed up by a login agent, then reused for sequential tasks

Failing Python Code

from browser_use import Agent, Browser

browser = Browser(keep_alive=True)

# First agent — e.g. a login warmup
agent1 = Agent(task="Navigate to example.com", browser=browser, llm=llm)
await agent1.run()
# Immediately after: CDP WebSocket handlers exit, reconnection cycle begins

# Browser recovers after ~1.7s, but all session data was cleared

LLM Model

No response

Operating System & Browser Versions

No response

Full DEBUG Log Output

The relevant section is:


WARNING  [BrowserSession] CDP WebSocket message handler exited unexpectedly (connection closed)
WARNING  [BrowserSession] CDP WebSocket message handler exited unexpectedly (connection closed)
WARNING  [BrowserSession] CDP WebSocket message handler exited unexpectedly (connection closed)
WARNING  [BrowserSession] WebSocket reconnection attempt 1/3...
INFO     [BrowserSession] [SessionManager] Cleared all owned data (targets, sessions, mappings)
WARNING  [BrowserSession] WebSocket reconnection attempt 1/3...
INFO     [BrowserSession] [SessionManager] Cleared all owned data (targets, sessions, mappings)
...
INFO     [BrowserSession] WebSocket reconnected after 1.7s (attempt 1)
INFO     [BrowserSession] WebSocket reconnected after 1.7s (attempt 1)

Activity

  1. added
    bug
    on Mar 16, 2026
  2. MrLeit commented on Mar 16, 2026

    @MrLeit
    ContributorAuthor

    Additional finding: keep_alive=True breaks CDP (remote browser) connections

    When using a remote browser via CDP (e.g. Browserless), Agent.close() with keep_alive=True destroys the connection entirely.

    The keep_alive=True path in close() calls event_bus.stop(clear=False) and then sets event_queue = None. This causes all CDP WebSocket message handlers to exit with "connection closed" warnings. The reconnection logic recovers after ~1.7s, but clears all SessionManager data (targets, sessions, mappings) — destroying the authenticated session state that keep_alive is supposed to preserve.

    This works fine with local browsers because the browser process keeps running independently of the event bus. But with CDP, the WebSocket is the only link to the browser — once the handlers exit, the connection is effectively dead. The reconnected WebSocket has no handlers feeding events to the new event bus.

    Workaround: Skip the event_bus.stop() / event_queue = None cleanup entirely when keep_alive=True. Only run the non-event-bus parts of close() (skill service cleanup, gc).

    async def _patched_close(self):
        session = getattr(self, "browser_session", None)
        keep_alive = getattr(
            getattr(session, "browser_profile", None), "keep_alive", False
        ) if session else False
    
        if not keep_alive:
            return await Agent._original_close(self)
    
        # keep_alive=True: skip event bus manipulation entirely
        skill_service = getattr(self, "skill_service", None)
        if skill_service is not None:
            await skill_service.close()
        gc.collect()
    
    Agent._original_close = Agent.close
    Agent.close = _patched_close

    Expected: Agent.close() with keep_alive=True should preserve the event bus and CDP WebSocket handlers so the browser session remains usable for subsequent agents.

  3. added a commit that references this issue on Mar 17, 2026
    8b0dd2e
  4. jda5 commented on Mar 25, 2026

    @jda5

    I'm having this problem too!

  5. Nbk7822 commented on Mar 27, 2026

    @Nbk7822

    CDP connection management for long-running sessions is brutal. We sidestepped this entirely by making the VM the unit of persistence, not the WebSocket. Agent connects to Chrome inside a container, and if the connection drops, the Chrome instance is still running, agent just reconnects. No state loss, no session teardown. The container stays up as long as you need it. We don't have session time caps for this reason. Here's how we structured it: open-computer-use

  6. added a commit that references this issue on Mar 29, 2026
    e85b20b
  7. MrLeit commented on Mar 31, 2026

    @MrLeit
    ContributorAuthor

    The next problem after addressing this is (as @Nbk7822 mentioned) CDP connection stability. I've raised the dependent ticket #4579.

    For now I've stopped trying to use persistent session state and keep_alive as it is too buggy. This of course has performance and token wastage implications.

  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.

  9. 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.

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