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
refactor: update agent focus handling to use target ID consistently
reformedotbf350bc4b0d8
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex cc6438a8d..3fa9128aa 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -475,8 +475,8 @@ class Agent(Generic[Context, AgentStructuredOutput]):_browser_session_id = self.browser_session.id if self.browser_session else '----'_current_target_id = (- self.browser_session.agent_focus.target_id[-2:]- if self.browser_session and self.browser_session.agent_focus and self.browser_session.agent_focus.target_id+ self.browser_session.agent_focus_target_id[-2:]+ if self.browser_session and self.browser_session.agent_focus_target_idelse '--')return logging.getLogger(f'browser_use.Agentπ ° {self.task_id[-4:]} β’ π {_browser_session_id[-4:]} π £ {_current_target_id}')diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex d01e3186e..43688cf0f 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -398,7 +398,7 @@ class BrowserSession(BaseModel):_cdp_client_root: CDPClient | None = PrivateAttr(default=None)# PUBLIC: SessionManager instance (OWNS all targets and sessions - single source of truth)- session_manager: Any = Field(default=None, exclude=True) # SessionManager - not serialized+ session_manager: Any = Field(default=None, exclude=True) # SessionManager_cached_browser_state_summary: Any = PrivateAttr(default=None)_cached_selector_map: dict[int, EnhancedDOMTreeNode] = PrivateAttr(default_factory=dict)diff --git a/browser_use/browser/watchdog_base.py b/browser_use/browser/watchdog_base.pyindex ddb9ad586..99507c253 100644--- a/browser_use/browser/watchdog_base.py+++ b/browser_use/browser/watchdog_base.py@@ -131,19 +131,17 @@ class BaseWatchdog(BaseModel):# attempt to repair potentially crashed CDP sessiontry:- if browser_session.agent_focus and browser_session.agent_focus.target_id:+ if browser_session.agent_focus_target_id:# With event-driven sessions, Chrome will send detach/attach events# SessionManager handles pool cleanup automatically- target_id_to_restore = browser_session.agent_focus.target_id+ target_id_to_restore = browser_session.agent_focus_target_idbrowser_session.logger.debug(- f'π {watchdog_and_handler_str} β οΈ Session error detected, waiting for CDP events to sync\n\t{browser_session.agent_focus}'+ f'π {watchdog_and_handler_str} β οΈ Session error detected, waiting for CDP events to sync (target: {target_id_to_restore})')# Wait for new attach event to restore the session# This will raise ValueError if target doesn't re-attach- browser_session.agent_focus = await browser_session.get_or_create_cdp_session(- target_id=target_id_to_restore, focus=True- )+ await browser_session.get_or_create_cdp_session(target_id=target_id_to_restore, focus=True)else:# Try to get any available sessionawait browser_session.get_or_create_cdp_session(target_id=None, focus=True)diff --git a/browser_use/browser/watchdogs/crash_watchdog.py b/browser_use/browser/watchdogs/crash_watchdog.pyindex ce60f28e5..6723bc73e 100644--- a/browser_use/browser/watchdogs/crash_watchdog.py+++ b/browser_use/browser/watchdogs/crash_watchdog.py@@ -71,8 +71,8 @@ class CrashWatchdog(BaseWatchdog):async def on_TabCreatedEvent(self, event: TabCreatedEvent) -> None:"""Attach to new tab."""- assert self.browser_session.agent_focus is not None, 'No current target ID'- await self.attach_to_target(self.browser_session.agent_focus.target_id)+ assert self.browser_session.agent_focus_target_id is not None, 'No current target ID'+ await self.attach_to_target(self.browser_session.agent_focus_target_id)async def on_TabClosedEvent(self, event: TabClosedEvent) -> None:"""Clean up tracking when tab closes."""@@ -163,8 +163,8 @@ class CrashWatchdog(BaseWatchdog):is_agent_focus = (target_info- and self.browser_session.agent_focus- and target_info['targetId'] == self.browser_session.agent_focus.target_id+ and self.browser_session.agent_focus_target_id+ and target_info['targetId'] == self.browser_session.agent_focus_target_id)if is_agent_focus and target_info:@@ -280,7 +280,7 @@ class CrashWatchdog(BaseWatchdog):"""Check if browser and targets are still responsive."""try:- self.logger.debug(f'[CrashWatchdog] Checking browser health for target {self.browser_session.agent_focus}')+ self.logger.debug(f'[CrashWatchdog] Checking browser health for target {self.browser_session.agent_focus_target_id}')cdp_session = await self.browser_session.get_or_create_cdp_session()for target in (await self.browser_session.cdp_client.send.Target.getTargets()).get('targetInfos', []):@@ -300,10 +300,12 @@ class CrashWatchdog(BaseWatchdog):cdp_session.cdp_client.send.Runtime.evaluate(params={'expression': '1+1'}, session_id=cdp_session.session_id),timeout=1.0,)- self.logger.debug(f'[CrashWatchdog] Browser health check passed for target {self.browser_session.agent_focus}')+ self.logger.debug(+ f'[CrashWatchdog] Browser health check passed for target {self.browser_session.agent_focus_target_id}'+ )except Exception as e:self.logger.error(- f'[CrashWatchdog] β Crashed/unresponsive session detected for target {self.browser_session.agent_focus} '+ f'[CrashWatchdog] β Crashed/unresponsive session detected for target {self.browser_session.agent_focus_target_id} 'f'error: {type(e).__name__}: {e} (Chrome will send detach event, SessionManager will auto-recover)')diff --git a/browser_use/browser/watchdogs/default_action_watchdog.py b/browser_use/browser/watchdogs/default_action_watchdog.pyindex ebc8ef091..e74a7a598 100644--- a/browser_use/browser/watchdogs/default_action_watchdog.py+++ b/browser_use/browser/watchdogs/default_action_watchdog.py@@ -155,7 +155,7 @@ class DefaultActionWatchdog(BaseWatchdog):"""Handle click request with CDP."""try:# Check if session is alive before attempting any operations- if not self.browser_session.agent_focus or not self.browser_session.agent_focus.target_id:+ if not self.browser_session.agent_focus_target_id:error_msg = 'Cannot execute click: browser session is corrupted (target_id=None). Session may have crashed.'self.logger.error(f'{error_msg}')raise BrowserError(error_msg)@@ -163,7 +163,7 @@ class DefaultActionWatchdog(BaseWatchdog):# Use the provided nodeelement_node = event.nodeindex_for_logging = element_node.backend_node_id or 'unknown'- starting_target_id = self.browser_session.agent_focus.target_id+ starting_target_id = self.browser_session.agent_focus_target_id# Check if element is a file input (should not be clicked)if self.browser_session.is_file_input(element_node):@@ -277,7 +277,7 @@ class DefaultActionWatchdog(BaseWatchdog):async def on_ScrollEvent(self, event: ScrollEvent) -> None:"""Handle scroll request with CDP."""# Check if we have a current target for scrolling- if not self.browser_session.agent_focus:+ if not self.browser_session.agent_focus_target_id:error_msg = 'No active target for scrolling'raise BrowserError(error_msg)@@ -1631,9 +1631,13 @@ class DefaultActionWatchdog(BaseWatchdog):"""try:# Get CDP client and session- assert self.browser_session.agent_focus is not None, 'CDP session not initialized - browser may not be connected yet'- cdp_client = self.browser_session.agent_focus.cdp_client- session_id = self.browser_session.agent_focus.session_id+ assert self.browser_session.agent_focus_target_id is not None, (+ 'CDP session not initialized - browser may not be connected yet'+ )+ cdp_session = await self.browser_session.session_manager.get_focused_session()+ assert cdp_session is not None, 'No session for focused target'+ cdp_client = cdp_session.cdp_client+ session_id = cdp_session.session_id# Get viewport dimensionslayout_metrics = await cdp_client.send.Page.getLayoutMetrics(session_id=session_id)@@ -1778,8 +1782,12 @@ class DefaultActionWatchdog(BaseWatchdog):self.logger.debug(f'Error getting frame session: {e}, using main session')# Use main target session- assert self.browser_session.agent_focus is not None, 'CDP session not initialized - browser may not be connected yet'- return self.browser_session.agent_focus.session_id+ assert self.browser_session.agent_focus_target_id is not None, (+ 'CDP session not initialized - browser may not be connected yet'+ )+ cdp_session = await self.browser_session.session_manager.get_focused_session()+ assert cdp_session is not None, 'No session for focused target'+ return cdp_session.session_idasync def on_GoBackEvent(self, event: GoBackEvent) -> None:"""Handle navigate back request with CDP."""@@ -2103,9 +2111,11 @@ class DefaultActionWatchdog(BaseWatchdog):# Get CDP client and sessioncdp_client = self.browser_session.cdp_client- if self.browser_session.agent_focus is None:+ if self.browser_session.agent_focus_target_id is None:raise BrowserError('CDP session not initialized - browser may not be connected yet')- session_id = self.browser_session.agent_focus.session_id+ cdp_session = await self.browser_session.session_manager.get_focused_session()+ assert cdp_session is not None, 'No session for focused target'+ session_id = cdp_session.session_id# Enable DOMawait cdp_client.send.DOM.enable(session_id=session_id)diff --git a/browser_use/browser/watchdogs/dom_watchdog.py b/browser_use/browser/watchdogs/dom_watchdog.pyindex a82bd9266..439862e72 100644--- a/browser_use/browser/watchdogs/dom_watchdog.py+++ b/browser_use/browser/watchdogs/dom_watchdog.py@@ -100,7 +100,7 @@ class DOMWatchdog(BaseWatchdog):from browser_use.browser.views import NetworkRequesttry:- if not self.browser_session.agent_focus:+ if not self.browser_session.agent_focus_target_id:return []cdp_session = await self.browser_session.get_or_create_cdp_session(focus=True)@@ -257,9 +257,11 @@ class DOMWatchdog(BaseWatchdog):self.logger.debug('π DOMWatchdog.on_BrowserStateRequestEvent: STARTING browser state request')page_url = await self.browser_session.get_current_page_url()self.logger.debug(f'π DOMWatchdog.on_BrowserStateRequestEvent: Got page URL: {page_url}')- if self.browser_session.agent_focus:+ if self.browser_session.agent_focus_target_id:+ cdp_session = await self.browser_session.session_manager.get_focused_session()+ session_id = cdp_session.session_id if cdp_session else 'unknown'self.logger.debug(- f'Current page URL: {page_url}, target_id: {self.browser_session.agent_focus.target_id}, session_id: {self.browser_session.agent_focus.session_id}'+ f'Current page URL: {page_url}, target_id: {self.browser_session.agent_focus_target_id}, session_id: {session_id}')else:self.logger.debug(f'Current page URL: {page_url}, no cdp_session attached')@@ -612,8 +614,8 @@ class DOMWatchdog(BaseWatchdog):self.logger.debug('π DOMWatchdog._capture_clean_screenshot: Capturing clean screenshot...')# Ensure we have a focused CDP session- assert self.browser_session.agent_focus is not None, 'No current target ID'- await self.browser_session.get_or_create_cdp_session(target_id=self.browser_session.agent_focus.target_id, focus=True)+ assert self.browser_session.agent_focus_target_id is not None, 'No current target ID'+ await self.browser_session.get_or_create_cdp_session(target_id=self.browser_session.agent_focus_target_id, focus=True)# Check if handler is registeredhandlers = self.event_bus.handlers.get('ScreenshotEvent', [])@@ -706,11 +708,11 @@ class DOMWatchdog(BaseWatchdog):from browser_use.browser.views import PageInfo# Get CDP session for the current target- if not self.browser_session.agent_focus:+ if not self.browser_session.agent_focus_target_id:raise RuntimeError('No active CDP session - browser may not be connected yet')cdp_session = await self.browser_session.get_or_create_cdp_session(- target_id=self.browser_session.agent_focus.target_id, focus=True+ target_id=self.browser_session.agent_focus_target_id, focus=True)# Get layout metrics which includes all the information we needdiff --git a/browser_use/browser/watchdogs/downloads_watchdog.py b/browser_use/browser/watchdogs/downloads_watchdog.pyindex 0e8038a14..7ddc35e8e 100644--- a/browser_use/browser/watchdogs/downloads_watchdog.py+++ b/browser_use/browser/watchdogs/downloads_watchdog.py@@ -90,7 +90,7 @@ class DownloadsWatchdog(BaseWatchdog):async def on_BrowserStateRequestEvent(self, event: BrowserStateRequestEvent) -> None:"""Handle browser state request events."""- cdp_session = self.browser_session.agent_focus+ cdp_session = await self.browser_session.session_manager.get_focused_session()if not cdp_session:return@@ -944,12 +944,17 @@ class DownloadsWatchdog(BaseWatchdog):"""self.logger.debug(f'[DownloadsWatchdog] Checking if target {target_id} is PDF viewer...')- session = await self.browser_session._session_manager.get_session_for_target(target_id)+ session = await self.browser_session.session_manager.get_session_for_target(target_id)if not session:self.logger.warning(f'[DownloadsWatchdog] No session found for {target_id}')return False- page_url = session.url+ # Get URL from target (not session - sessions don't have urls!)+ target = self.browser_session.session_manager.get_target(target_id)+ if not target:+ self.logger.warning(f'[DownloadsWatchdog] No target found for {target_id}')+ return False+ page_url = target.url# Check cache firstif page_url in self._pdf_viewer_cache:diff --git a/browser_use/browser/watchdogs/popups_watchdog.py b/browser_use/browser/watchdogs/popups_watchdog.pyindex 846714904..efbbf9101 100644--- a/browser_use/browser/watchdogs/popups_watchdog.py+++ b/browser_use/browser/watchdogs/popups_watchdog.py@@ -100,18 +100,18 @@ class PopupsWatchdog(BaseWatchdog):self.logger.debug(f'Approach 1 failed: {type(e).__name__}')# Approach 2: Try with current agent focus session- if not dismissed and self.browser_session._cdp_client_root and self.browser_session.agent_focus:+ if not dismissed and self.browser_session._cdp_client_root and self.browser_session.agent_focus_target_id:try:- self.logger.debug(- f'π Approach 2: Using agent focus session {self.browser_session.agent_focus.session_id[-8:]}'- )- await asyncio.wait_for(- self.browser_session._cdp_client_root.send.Page.handleJavaScriptDialog(- params={'accept': should_accept},- session_id=self.browser_session.agent_focus.session_id,- ),- timeout=0.5,- )+ cdp_session = await self.browser_session.session_manager.get_focused_session()+ if cdp_session:+ self.logger.debug(f'π Approach 2: Using agent focus session {cdp_session.session_id[-8:]}')+ await asyncio.wait_for(+ self.browser_session._cdp_client_root.send.Page.handleJavaScriptDialog(+ params={'accept': should_accept},+ session_id=cdp_session.session_id,+ ),+ timeout=0.5,+ )dismissed = Trueself.logger.info('β Dialog handled successfully via agent focus session')except (TimeoutError, Exception) as e:diff --git a/browser_use/cli.py b/browser_use/cli.pyindex 100261ed8..6965f3e80 100644--- a/browser_use/cli.py+++ b/browser_use/cli.py@@ -1303,13 +1303,10 @@ class BrowserUseApp(App):pass# Show the agent's current page URL if available- if browser_session.agent_focus:- current_url = (- browser_session.agent_focus.url.replace('https://', '')- .replace('http://', '')- .replace('www.', '')[:36]- + 'β¦'- )+ if browser_session.agent_focus_target_id:+ target = browser_session.session_manager.get_focused_target()+ target_url = target.url if target else 'about:blank'+ current_url = target_url.replace('https://', '').replace('http://', '').replace('www.', '')[:36] + 'β¦'browser_info.write(f'ποΈ [green]{current_url}[/]')except Exception as e:browser_info.write(f'[red]Error updating browser info: {str(e)}[/]')diff --git a/browser_use/dom/service.py b/browser_use/dom/service.pyindex 533a7f419..96cc597ce 100644--- a/browser_use/dom/service.py+++ b/browser_use/dom/service.py@@ -549,7 +549,7 @@ class DomService:attributes=attributes or {},is_scrollable=node.get('isScrollable', None),frame_id=node.get('frameId', None),- session_id=self.browser_session.agent_focus.session_id if self.browser_session.agent_focus else None,+ session_id=self.browser_session.current_session_id,target_id=target_id,content_document=None,shadow_root_type=shadow_root_type,