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): recover with cached state after timeout
MagMuellerbd45e4c22af4
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex 55424f82f..83975c26a 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -4,6 +4,7 @@ import asyncioimport loggingimport reimport time+from dataclasses import replacefrom functools import cached_propertyfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Literal, Self, Union, cast, overload@@ -1617,8 +1618,27 @@ class BrowserSession(BaseModel):),)- # The handler returns the BrowserStateSummary directly- result = await event.event_result(raise_if_none=True, raise_if_any=True)+ # The handler returns the BrowserStateSummary directly. If the remote+ # browser stops answering long enough for the whole state event to time+ # out, preserve agent recovery by returning the last known DOM instead of+ # skipping the model call repeatedly. Never reuse a stale screenshot.+ try:+ result = await event.event_result(raise_if_none=True, raise_if_any=True)+ except TimeoutError:+ cached_state = self._cached_browser_state_summary+ if cached_state is None or cached_state.dom_state is None:+ raise++ self.logger.warning('Browser state refresh timed out; returning the last known DOM without a screenshot')+ return replace(+ cached_state,+ screenshot=None,+ browser_errors=[+ *cached_state.browser_errors,+ 'Browser state refresh timed out; this is the last known page state.',+ ],+ )+assert 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 92d7d8f5b..68bbe9737 100644--- a/tests/ci/browser/test_dom_listener_detection.py+++ b/tests/ci/browser/test_dom_listener_detection.py@@ -111,3 +111,25 @@ async def test_screenshot_timeout_preserves_structural_dom(httpserver, browser_sassert state.screenshot is Noneassert state.dom_state is not Noneassert any(node.attributes.get('id') == 'continue' for node in state.dom_state.selector_map.values())+++async def test_state_timeout_returns_cached_dom_without_screenshot(httpserver, browser_session: BrowserSession, monkeypatch):+ """A whole-state timeout should still let the model receive the last known DOM."""+ httpserver.expect_request('/cached-state').respond_with_data(+ '<html><body><button id="continue">Continue</button></body></html>',+ content_type='text/html',+ )+ await browser_session.navigate_to(httpserver.url_for('/cached-state'))+ initial_state = await browser_session.get_browser_state_summary(include_screenshot=False)++ class TimedOutStateEvent:+ async def event_result(self, **_kwargs):+ raise TimeoutError++ monkeypatch.setattr(browser_session.event_bus, 'dispatch', lambda _event: TimedOutStateEvent())++ recovered_state = await browser_session.get_browser_state_summary(include_screenshot=True)++ assert recovered_state.screenshot is None+ assert recovered_state.dom_state is initial_state.dom_state+ assert recovered_state.browser_errors[-1] == 'Browser state refresh timed out; this is the last known page state.'