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
Fix
LarsenCundricc67c31932ef7
diff --git a/browser_use/browser/events.py b/browser_use/browser/events.pyindex d7c0d9377..afc492de3 100644--- a/browser_use/browser/events.py+++ b/browser_use/browser/events.py@@ -406,7 +406,7 @@ class TabClosedEvent(BaseEvent):# new_focus_target_id: int | None = None# new_focus_url: str | None = None- event_timeout: float | None = Field(default_factory=lambda: _get_timeout('TIMEOUT_TabClosedEvent', 10.0)) # seconds+ event_timeout: float | None = Field(default_factory=lambda: _get_timeout('TIMEOUT_TabClosedEvent', 3.0)) # seconds# TODO: emit this when DOM changes significantly, inner frame navigates, form submits, history.pushState(), etc.diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex 43f2d4f8e..76d23d922 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -390,6 +390,23 @@ class BrowserSession(BaseModel):"""Whether this is a local browser instance from browser profile."""return self.browser_profile.is_local+ @property+ def is_cdp_connected(self) -> bool:+ """Check if the CDP WebSocket connection is alive and usable.++ Returns True only if the root CDP client exists and its WebSocket is in OPEN state.+ A dead/closing/closed WebSocket returns False, preventing handlers from dispatching+ CDP commands that would hang until timeout on a broken connection.+ """+ if self._cdp_client_root is None or self._cdp_client_root.ws is None:+ return False+ try:+ from websockets.protocol import State++ return self._cdp_client_root.ws.state is State.OPEN+ except Exception:+ return False+@propertydef cloud_browser(self) -> bool:"""Whether to use cloud browser service from browser profile."""@@ -653,7 +670,14 @@ class BrowserSession(BaseModel):# Only connect if not already connectedif self._cdp_client_root is None:# Setup browser via CDP (for both local and remote cases)- await self.connect(cdp_url=self.cdp_url)+ # Global timeout prevents connect() from hanging indefinitely on+ # slow/broken WebSocket connections (common on Lambda → remote browser)+ try:+ await asyncio.wait_for(self.connect(cdp_url=self.cdp_url), timeout=15.0)+ except TimeoutError:+ raise RuntimeError(+ f'connect() timed out after 15s — CDP connection to {self.cdp_url} is too slow or unresponsive'+ )assert self.cdp_client is not None# Notify that browser is connected (single place)@@ -1592,22 +1616,27 @@ class BrowserSession(BaseModel):# SessionManager has already discovered all targets via start_monitoring()page_targets_from_manager = self.session_manager.get_all_page_targets()- # Check for chrome://newtab pages and redirect them to about:blank+ # Check for chrome://newtab pages and redirect them to about:blank (in parallel)from browser_use.utils import is_new_tab_page- for target in page_targets_from_manager:+ async def _redirect_newtab(target):target_url = target.url- if is_new_tab_page(target_url) and target_url != 'about:blank':- target_id = target.target_id- self.logger.debug(f'🔄 Redirecting {target_url} to about:blank for target {target_id}')- try:- # Use public API with focus=False to avoid changing focus during init- session = await self.get_or_create_cdp_session(target_id, focus=False)- await session.cdp_client.send.Page.navigate(params={'url': 'about:blank'}, session_id=session.session_id)- # Update target url- target.url = 'about:blank'- except Exception as e:- self.logger.warning(f'Failed to redirect {target_url}: {e}')+ target_id = target.target_id+ self.logger.debug(f'🔄 Redirecting {target_url} to about:blank for target {target_id}')+ try:+ session = await self.get_or_create_cdp_session(target_id, focus=False)+ await session.cdp_client.send.Page.navigate(params={'url': 'about:blank'}, session_id=session.session_id)+ target.url = 'about:blank'+ except Exception as e:+ self.logger.warning(f'Failed to redirect {target_url}: {e}')++ redirect_tasks = [+ _redirect_newtab(target)+ for target in page_targets_from_manager+ if is_new_tab_page(target.url) and target.url != 'about:blank'+ ]+ if redirect_tasks:+ await asyncio.gather(*redirect_tasks, return_exceptions=True)# Ensure we have at least one pageif not page_targets_from_manager:diff --git a/browser_use/browser/watchdog_base.py b/browser_use/browser/watchdog_base.pyindex b7569fbd2..ce82df502 100644--- a/browser_use/browser/watchdog_base.py+++ b/browser_use/browser/watchdog_base.py@@ -73,10 +73,31 @@ class BaseWatchdog(BaseModel):watchdog_instance = getattr(handler, '__self__', None)watchdog_class_name = watchdog_instance.__class__.__name__ if watchdog_instance else 'Unknown'+ # Events that should always run even when CDP is disconnected (lifecycle management)+ LIFECYCLE_EVENT_NAMES = frozenset(+ {+ 'BrowserStartEvent',+ 'BrowserStopEvent',+ 'BrowserStoppedEvent',+ 'BrowserLaunchEvent',+ 'BrowserErrorEvent',+ 'BrowserKillEvent',+ }+ )+# Create a wrapper function with unique name to avoid duplicate handler warnings# Capture handler by value to avoid closure issuesdef make_unique_handler(actual_handler):async def unique_handler(event):+ # Circuit breaker: skip handler if CDP WebSocket is dead+ # (prevents handlers from hanging on broken connections until timeout)+ # Lifecycle events are exempt — they manage browser start/stop+ if event.event_type not in LIFECYCLE_EVENT_NAMES and not browser_session.is_cdp_connected:+ browser_session.logger.debug(+ f'🚌 [{watchdog_class_name}.{actual_handler.__name__}] ⚡ Skipped — CDP not connected'+ )+ return None+# just for debug logging, not used for anything elseparent_event = event_bus.event_history.get(event.event_parent_id) if event.event_parent_id else Nonegrandparent_event = (diff --git a/browser_use/browser/watchdogs/aboutblank_watchdog.py b/browser_use/browser/watchdogs/aboutblank_watchdog.pyindex e38d148f5..f6a7a740d 100644--- a/browser_use/browser/watchdogs/aboutblank_watchdog.py+++ b/browser_use/browser/watchdogs/aboutblank_watchdog.py@@ -59,11 +59,14 @@ class AboutBlankWatchdog(BaseWatchdog):async def on_TabClosedEvent(self, event: TabClosedEvent) -> None:"""Check tabs when a tab is closed and proactively create about:blank if needed."""- # logger.debug('[AboutBlankWatchdog] Tab closing, checking if we need to create about:blank tab')-# Don't create new tabs if browser is shutting downif self._stopping:- # logger.debug('[AboutBlankWatchdog] Browser is stopping, not creating new tabs')+ return++ # Don't attempt CDP operations if the WebSocket is dead — dispatching+ # NavigateToUrlEvent on a broken connection will hang until timeout+ if not self.browser_session.is_cdp_connected:+ self.logger.debug('[AboutBlankWatchdog] CDP not connected, skipping tab recovery')return# Check if we're about to close the last tab (event happens BEFORE tab closes)@@ -89,6 +92,9 @@ class AboutBlankWatchdog(BaseWatchdog):async def _check_and_ensure_about_blank_tab(self) -> None:"""Check current tabs and ensure exactly one about:blank tab with animation exists."""try:+ if not self.browser_session.is_cdp_connected:+ return+# For quick checks, just get page targets without titles to reduce noisepage_targets = await self.browser_session._cdp_get_all_pages()