Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
Clean up failed browser reconnect initialization
Magnus Müller84bb55ae1a80
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex 30070cefc..f15fdea33 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -2202,49 +2202,60 @@ class BrowserSession(BaseModel):additional_headers=headers or None,max_ws_frame_size=200 * 1024 * 1024,)- await self._cdp_client_root.start()+ try:+ await self._cdp_client_root.start()- # 4. Re-initialize SessionManager- from browser_use.browser.session_manager import SessionManager+ from browser_use.browser.session_manager import SessionManager- self.session_manager = SessionManager(self)- await self.session_manager.start_monitoring()+ self.session_manager = SessionManager(self)+ await self.session_manager.start_monitoring()- # 5. Re-enable autoAttach- await self._cdp_client_root.send.Target.setAutoAttach(- params={'autoAttach': True, 'waitForDebuggerOnStart': False, 'flatten': True}- )+ await self._cdp_client_root.send.Target.setAutoAttach(+ params={'autoAttach': True, 'waitForDebuggerOnStart': False, 'flatten': True}+ )- # 6. Re-discover page targets and restore focus- page_targets = self.session_manager.get_all_page_targets()+ page_targets = self.session_manager.get_all_page_targets()- # Prefer the old focus target if it still exists- restored = False- if old_focus_target_id:- for target in page_targets:- if target.target_id == old_focus_target_id:- await self.get_or_create_cdp_session(old_focus_target_id, focus=True)- restored = True- self.logger.debug(f'🔄 Restored agent focus to previous target {old_focus_target_id[:8]}...')- break+ # Prefer the previous focus target when it remains available.+ restored = False+ if old_focus_target_id:+ for target in page_targets:+ if target.target_id == old_focus_target_id:+ await self.get_or_create_cdp_session(old_focus_target_id, focus=True)+ restored = True+ self.logger.debug(f'🔄 Restored agent focus to previous target {old_focus_target_id[:8]}...')+ break- if not restored:- if page_targets:- fallback_id = page_targets[0].target_id- await self.get_or_create_cdp_session(fallback_id, focus=True)- self.logger.debug(f'🔄 Agent focus set to fallback target {fallback_id[:8]}...')- else:- # No pages exist — create one- new_target = await self._cdp_client_root.send.Target.createTarget(params={'url': 'about:blank'})- target_id = new_target['targetId']- await self.get_or_create_cdp_session(target_id, focus=True)- self.logger.debug(f'🔄 Created new blank page during reconnect: {target_id[:8]}...')+ if not restored:+ if page_targets:+ fallback_id = page_targets[0].target_id+ await self.get_or_create_cdp_session(fallback_id, focus=True)+ self.logger.debug(f'🔄 Agent focus set to fallback target {fallback_id[:8]}...')+ else:+ new_target = await self._cdp_client_root.send.Target.createTarget(params={'url': 'about:blank'})+ target_id = new_target['targetId']+ await self.get_or_create_cdp_session(target_id, focus=True)+ self.logger.debug(f'🔄 Created new blank page during reconnect: {target_id[:8]}...')- # 7. Re-enable proxy auth if configured- await self._setup_proxy_auth()+ await self._setup_proxy_auth()- # 8. Attach the WS drop detection callback to the new client- self._attach_ws_drop_callback()+ self._attach_ws_drop_callback()+ except BaseException:+ client, manager = self._cdp_client_root, self.session_manager+ self._cdp_client_root = None+ self.session_manager = None+ self.agent_focus_target_id = None+ if client:+ try:+ await client.stop()+ except Exception:+ self.logger.debug('Failed to close the replacement CDP client')+ if manager:+ try:+ await manager.clear()+ except Exception:+ self.logger.debug('Failed to clear the replacement session manager')+ raiseasync def _auto_reconnect(self, max_attempts: int = 3) -> None:"""Attempt to reconnect with exponential backoff.diff --git a/tests/ci/test_browser_session.py b/tests/ci/test_browser_session.pyindex 0fe4bb978..b715afbcb 100644--- a/tests/ci/test_browser_session.py+++ b/tests/ci/test_browser_session.py@@ -1,5 +1,7 @@import asyncio+import pytest+from browser_use.browser.profile import BrowserProfilefrom browser_use.browser.session import BrowserSession@@ -41,3 +43,47 @@ async def test_ws_drop_during_reconnect_triggers_follow_up_attempt(monkeypatch)await session._reconnect_taskassert reconnect_attempts == 2await session.event_bus.stop(clear=True, timeout=5)++[email protected]('method', ['Target.setDiscoverTargets', 'Target.setAutoAttach'])[email protected]('failure', ['cancel', 'error'])+async def test_failed_reconnect_closes_replacement_client(monkeypatch, method, failure):+ from browser_use.browser._cdp_timeout import TimeoutWrappedCDPClient++ session = BrowserSession(browser_profile=BrowserProfile(headless=True, user_data_dir=None, cdp_url='ws://127.0.0.1:9222'))+ started = asyncio.Event()+ clients = []++ async def start(client):+ clients.append(client)+ client._message_handler_task = asyncio.create_task(asyncio.Event().wait())++ async def send_raw(client, method: str, params=None, session_id=None):+ if method == blocked_method:+ started.set()+ if failure == 'error':+ raise ConnectionError('Initialization failed')+ await asyncio.Event().wait()+ return {'targetInfos': []} if method == 'Target.getTargets' else {}++ blocked_method = method+ monkeypatch.setattr(TimeoutWrappedCDPClient, 'start', start)+ monkeypatch.setattr(TimeoutWrappedCDPClient, 'send_raw', send_raw)+ reconnect = asyncio.create_task(session.reconnect())+ try:+ await asyncio.wait_for(started.wait(), timeout=5)+ if failure == 'cancel':+ reconnect.cancel()+ with pytest.raises(asyncio.CancelledError if failure == 'cancel' else ConnectionError):+ await reconnect+ assert session._cdp_client_root is None+ assert session.session_manager is None+ assert session.agent_focus_target_id is None+ assert clients[0]._message_handler_task is None+ finally:+ if not reconnect.done():+ reconnect.cancel()+ await asyncio.gather(reconnect, return_exceptions=True)+ for client in clients:+ await client.stop()+ await session.event_bus.stop(clear=True, timeout=5)