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: track browser document identity across cloud sessions
Gregor Žuničc239546c1920
diff --git a/browser_use/integrations/anthropic/browser_use.py b/browser_use/integrations/anthropic/browser_use.pyindex 866045ea2..8eaa3c00e 100644--- a/browser_use/integrations/anthropic/browser_use.py+++ b/browser_use/integrations/anthropic/browser_use.py@@ -11,6 +11,7 @@ import base64import contextlibimport jsonimport re+import secretsimport timefrom collections import defaultdict, dequefrom collections.abc import Callable@@ -89,6 +90,7 @@ class BrowserUse(BetaAsyncAbstractBrowserToolset20260801):self._next_ref = 1self._documents: dict[str, str] = {}self._next_document = 1+ self._document_property = f'__browser_use_document_{secrets.token_hex(16)}'self._reported_tabs: set[str] = set()self._last_tabs: list[dict] = []self._observer: CDPClient | None = None@@ -161,7 +163,6 @@ class BrowserUse(BetaAsyncAbstractBrowserToolset20260801):active = self.browser.agent_focus_target_idif targets and active not in {t.target_id for t in targets}:active = targets[0].target_id- previous_urls = {tab['tab_id']: tab['url'] for tab in self._last_tabs}tabs = [dict(tab_id=t.target_id,@@ -171,10 +172,6 @@ class BrowserUse(BetaAsyncAbstractBrowserToolset20260801):)for t in targets]- for tab in tabs:- previous = previous_urls.get(tab['tab_id'])- if previous is not None and previous != tab['url']:- self._invalidate_refs(tab['tab_id'])self._last_tabs = tabsexcept Exception:pass # State reporting must still work after a CDP action fails.@@ -419,16 +416,33 @@ class BrowserUse(BetaAsyncAbstractBrowserToolset20260801):self._documents.pop(tab, None)async def _document(self, page):- # Prime DOM.resolveNode for this attached session. Do not derive document- # identity from CDP node, frame, loader, or session IDs: Cloud transports- # may remap each of those between calls while the page is unchanged.+ # Prime DOM.resolveNode for this attached session. Cloud transports may+ # remap CDP document, frame, loader, and session IDs between calls while the+ # page is unchanged. A non-enumerable marker in the page's main world stays+ # stable across those remaps and disappears when a new document is created.session_id = await page.session_idawait self._cdp.send.DOM.getDocument(params={'depth': 0}, session_id=session_id)tab = page._target_id- if tab not in self._documents:- self._documents[tab] = f'{tab}:{self._next_document}'- self._next_document += 1- return self._documents[tab]+ candidate = f'{tab}:{self._next_document}'+ self._next_document += 1+ key = json.dumps(self._document_property)+ value = json.dumps(candidate)+ document = await self._eval(+ page,+ f"""(() => {{+ const key = {key};+ if (!Object.prototype.hasOwnProperty.call(globalThis, key)) {{+ Object.defineProperty(globalThis, key, {{value: {value}, configurable: false}});+ }}+ return globalThis[key];+ }})()""",+ )+ if not isinstance(document, str):+ raise ToolError('Unable to identify the current browser document.')+ if self._documents.get(tab) != document:+ self._invalidate_refs(tab)+ self._documents[tab] = document+ return documentdef _reference(self, page, document: str, backend: int):reference = Reference(page._target_id, document, backend)diff --git a/tests/ci/integrations/test_anthropic_browser_use.py b/tests/ci/integrations/test_anthropic_browser_use.pyindex 8a313acfc..5627da4cd 100644--- a/tests/ci/integrations/test_anthropic_browser_use.py+++ b/tests/ci/integrations/test_anthropic_browser_use.py@@ -139,6 +139,12 @@ async def test_reference_document_identity_survives_cdp_session_rotation() -> Nodriver = BrowserUse()driver.browser = SimpleNamespace(cdp_client=FakeCDP())+ current_document = 'document-a'++ async def fake_eval(page, expression):+ return current_document++ driver._eval = fake_evalpage = FakePage()document = await driver._document(page)ref = driver._reference(page, document, 42)@@ -147,7 +153,7 @@ async def test_reference_document_identity_survives_cdp_session_rotation() -> Noassert await driver._document(page) == documentassert ref in driver._refs- driver._invalidate_refs('tab-a')+ current_document = 'document-b'assert await driver._document(page) != documentassert ref not in driver._refs