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(browser): bound cached state recovery attempts
MagMueller394ccc157e2c
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex 83975c26a..19814a9ed 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -562,6 +562,7 @@ class BrowserSession(BaseModel):_cached_browser_state_summary: Any = PrivateAttr(default=None)_cached_selector_map: dict[int, EnhancedDOMTreeNode] = PrivateAttr(default_factory=dict)_cached_selector_indices: dict[tuple[str, int], int] = PrivateAttr(default_factory=dict)+ _consecutive_state_refresh_timeouts: int = PrivateAttr(default=0)_downloaded_files: list[str] = PrivateAttr(default_factory=list) # Track files downloaded during this session_closed_popup_messages: list[str] = PrivateAttr(default_factory=list) # Store messages from auto-closed JavaScript dialogs@@ -662,6 +663,7 @@ class BrowserSession(BaseModel):self._cached_browser_state_summary = Noneself._cached_selector_map.clear()self._cached_selector_indices.clear()+ self._consecutive_state_refresh_timeouts = 0self._downloaded_files.clear()self.agent_focus_target_id = None@@ -1234,6 +1236,7 @@ class BrowserSession(BaseModel):self._cached_browser_state_summary = Noneself._cached_selector_map.clear()self._cached_selector_indices.clear()+ self._consecutive_state_refresh_timeouts = 0self.logger.debug('🔄 Cached browser state cleared')# Update agent focus if a specific target_id is provided (only for page/tab targets)@@ -1625,6 +1628,10 @@ class BrowserSession(BaseModel):try:result = await event.event_result(raise_if_none=True, raise_if_any=True)except TimeoutError:+ self._consecutive_state_refresh_timeouts += 1+ if self._consecutive_state_refresh_timeouts > 1:+ raise+cached_state = self._cached_browser_state_summaryif cached_state is None or cached_state.dom_state is None:raise@@ -1639,6 +1646,7 @@ class BrowserSession(BaseModel):],)+ self._consecutive_state_refresh_timeouts = 0assert result is not None and result.dom_state is not Nonereturn resultdiff --git a/tests/ci/browser/test_dom_listener_detection.py b/tests/ci/browser/test_dom_listener_detection.pyindex 68bbe9737..8f79fb314 100644--- a/tests/ci/browser/test_dom_listener_detection.py+++ b/tests/ci/browser/test_dom_listener_detection.py@@ -133,3 +133,6 @@ async def test_state_timeout_returns_cached_dom_without_screenshot(httpserver, bassert recovered_state.screenshot is Noneassert recovered_state.dom_state is initial_state.dom_stateassert recovered_state.browser_errors[-1] == 'Browser state refresh timed out; this is the last known page state.'++ with pytest.raises(TimeoutError):+ await browser_session.get_browser_state_summary(include_screenshot=True)